Merge "sysprop_library: Rename system scope to public"
diff --git a/Android.bp b/Android.bp
index 4db98f8..fff17ef 100644
--- a/Android.bp
+++ b/Android.bp
@@ -78,10 +78,12 @@
         "android/env.go",
     ],
     testSrcs: [
+        "android/android_test.go",
         "android/arch_test.go",
         "android/config_test.go",
         "android/expand_test.go",
         "android/module_test.go",
+        "android/mutator_test.go",
         "android/namespace_test.go",
         "android/neverallow_test.go",
         "android/onceper_test.go",
@@ -294,6 +296,7 @@
         "java/jdeps_test.go",
         "java/kotlin_test.go",
         "java/plugin_test.go",
+        "java/robolectric_test.go",
         "java/sdk_test.go",
     ],
     pluginFor: ["soong_build"],
diff --git a/android/android_test.go b/android/android_test.go
new file mode 100644
index 0000000..46b7054
--- /dev/null
+++ b/android/android_test.go
@@ -0,0 +1,46 @@
+// Copyright 2019 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package android
+
+import (
+	"io/ioutil"
+	"os"
+	"testing"
+)
+
+var buildDir string
+
+func setUp() {
+	var err error
+	buildDir, err = ioutil.TempDir("", "soong_android_test")
+	if err != nil {
+		panic(err)
+	}
+}
+
+func tearDown() {
+	os.RemoveAll(buildDir)
+}
+
+func TestMain(m *testing.M) {
+	run := func() int {
+		setUp()
+		defer tearDown()
+
+		return m.Run()
+	}
+
+	os.Exit(run())
+}
diff --git a/android/arch.go b/android/arch.go
index f4a3c06..46e582c 100644
--- a/android/arch.go
+++ b/android/arch.go
@@ -713,7 +713,7 @@
 // If host is supported for the module, the Host and HostCross OsClasses are selected.  If device is supported
 // for the module, the Device OsClass is selected.
 // Within each selected OsClass, the multilib selection is determined by:
-//    - The compile_multilib property if it set (which may be overriden by target.android.compile_multlib or
+//    - The compile_multilib property if it set (which may be overridden by target.android.compile_multilib or
 //      target.host.compile_multilib).
 //    - The default multilib passed to InitAndroidArchModule if compile_multilib was not set.
 // Valid multilib values include:
diff --git a/android/defaults.go b/android/defaults.go
index d4fbf48..844b4d4 100644
--- a/android/defaults.go
+++ b/android/defaults.go
@@ -80,6 +80,9 @@
 	return d.defaultableProperties
 }
 
+func (d *DefaultsModuleBase) GenerateAndroidBuildActions(ctx ModuleContext) {
+}
+
 func InitDefaultsModule(module DefaultableModule) {
 	module.AddProperties(
 		&hostAndDeviceProperties{},
diff --git a/android/defaults_test.go b/android/defaults_test.go
new file mode 100644
index 0000000..fa26595
--- /dev/null
+++ b/android/defaults_test.go
@@ -0,0 +1,116 @@
+// Copyright 2019 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package android
+
+import (
+	"testing"
+
+	"github.com/google/blueprint/proptools"
+)
+
+type defaultsTestProperties struct {
+	Foo []string
+}
+
+type defaultsTestModule struct {
+	ModuleBase
+	DefaultableModuleBase
+	properties defaultsTestProperties
+}
+
+func (d *defaultsTestModule) GenerateAndroidBuildActions(ctx ModuleContext) {
+	ctx.Build(pctx, BuildParams{
+		Rule:   Touch,
+		Output: PathForModuleOut(ctx, "out"),
+	})
+}
+
+func defaultsTestModuleFactory() Module {
+	module := &defaultsTestModule{}
+	module.AddProperties(&module.properties)
+	InitDefaultableModule(module)
+	InitAndroidModule(module)
+	return module
+}
+
+type defaultsTestDefaults struct {
+	ModuleBase
+	DefaultsModuleBase
+}
+
+func defaultsTestDefaultsFactory() Module {
+	defaults := &defaultsTestDefaults{}
+	defaults.AddProperties(&defaultsTestProperties{})
+	InitDefaultsModule(defaults)
+	return defaults
+}
+
+func TestDefaultsAllowMissingDependencies(t *testing.T) {
+	config := TestConfig(buildDir, nil)
+	config.TestProductVariables.Allow_missing_dependencies = proptools.BoolPtr(true)
+
+	ctx := NewTestContext()
+	ctx.SetAllowMissingDependencies(true)
+
+	ctx.RegisterModuleType("test", ModuleFactoryAdaptor(defaultsTestModuleFactory))
+	ctx.RegisterModuleType("defaults", ModuleFactoryAdaptor(defaultsTestDefaultsFactory))
+
+	ctx.PreArchMutators(RegisterDefaultsPreArchMutators)
+
+	ctx.Register()
+
+	bp := `
+		defaults {
+			name: "defaults",
+			defaults: ["missing"],
+			foo: ["defaults"],
+		}
+
+		test {
+			name: "missing_defaults",
+			defaults: ["missing"],
+			foo: ["module"],
+		}
+
+		test {
+			name: "missing_transitive_defaults",
+			defaults: ["defaults"],
+			foo: ["module"],
+		}
+	`
+
+	ctx.MockFileSystem(map[string][]byte{
+		"Android.bp": []byte(bp),
+	})
+
+	_, errs := ctx.ParseFileList(".", []string{"Android.bp"})
+	FailIfErrored(t, errs)
+	_, errs = ctx.PrepareBuildActions(config)
+	FailIfErrored(t, errs)
+
+	missingDefaults := ctx.ModuleForTests("missing_defaults", "").Output("out")
+	missingTransitiveDefaults := ctx.ModuleForTests("missing_transitive_defaults", "").Output("out")
+
+	if missingDefaults.Rule != ErrorRule {
+		t.Errorf("expected missing_defaults rule to be ErrorRule, got %#v", missingDefaults.Rule)
+	}
+
+	if g, w := missingDefaults.Args["error"], "module missing_defaults missing dependencies: missing\n"; g != w {
+		t.Errorf("want error %q, got %q", w, g)
+	}
+
+	// TODO: missing transitive defaults is currently not handled
+	_ = missingTransitiveDefaults
+}
diff --git a/android/module.go b/android/module.go
index 88eba87..87e2ca7 100644
--- a/android/module.go
+++ b/android/module.go
@@ -56,14 +56,40 @@
 type ModuleBuildParams BuildParams
 
 // BaseModuleContext is the same as blueprint.BaseModuleContext except that Config() returns
-// a Config instead of an interface{}, plus some extra methods that return Android-specific information
+// a Config instead of an interface{}, and some methods have been wrapped to use an android.Module
+// instead of a blueprint.Module, plus some extra methods that return Android-specific information
 // about the current module.
 type BaseModuleContext interface {
+	Module() Module
 	ModuleName() string
 	ModuleDir() string
 	ModuleType() string
 	Config() Config
 
+	OtherModuleName(m blueprint.Module) string
+	OtherModuleDir(m blueprint.Module) string
+	OtherModuleErrorf(m blueprint.Module, fmt string, args ...interface{})
+	OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
+	OtherModuleExists(name string) bool
+
+	GetDirectDepsWithTag(tag blueprint.DependencyTag) []Module
+	GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
+	GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
+
+	VisitDirectDepsBlueprint(visit func(blueprint.Module))
+	VisitDirectDeps(visit func(Module))
+	VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module))
+	VisitDirectDepsIf(pred func(Module) bool, visit func(Module))
+	// Deprecated: use WalkDeps instead to support multiple dependency tags on the same module
+	VisitDepsDepthFirst(visit func(Module))
+	// Deprecated: use WalkDeps instead to support multiple dependency tags on the same module
+	VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module))
+	WalkDeps(visit func(Module, Module) bool)
+	WalkDepsBlueprint(visit func(blueprint.Module, blueprint.Module) bool)
+	// GetWalkPath is supposed to be called in visit function passed in WalkDeps()
+	// and returns a top-down dependency path from a start module to current child module.
+	GetWalkPath() []Module
+
 	ContainsProperty(name string) bool
 	Errorf(pos scanner.Position, fmt string, args ...interface{})
 	ModuleErrorf(fmt string, args ...interface{})
@@ -76,9 +102,14 @@
 	// file that does not match the pattern is added to a searched directory.
 	GlobWithDeps(pattern string, excludes []string) ([]string, error)
 
+	Glob(globPattern string, excludes []string) Paths
+	GlobFiles(globPattern string, excludes []string) Paths
+
 	Fs() pathtools.FileSystem
 	AddNinjaFileDeps(deps ...string)
 
+	AddMissingDependencies(missingDeps []string)
+
 	Target() Target
 	TargetPrimary() bool
 	MultiTargets() []Target
@@ -114,8 +145,6 @@
 	ExpandSources(srcFiles, excludes []string) Paths
 	ExpandSource(srcFile, prop string) Path
 	ExpandOptionalSource(srcFile *string, prop string) OptionalPath
-	Glob(globPattern string, excludes []string) Paths
-	GlobFiles(globPattern string, excludes []string) Paths
 
 	InstallExecutable(installPath OutputPath, name string, srcPath Path, deps ...Path) OutputPath
 	InstallFile(installPath OutputPath, name string, srcPath Path, deps ...Path) OutputPath
@@ -123,8 +152,6 @@
 	InstallAbsoluteSymlink(installPath OutputPath, name string, absPath string) OutputPath
 	CheckbuildFile(srcPath Path)
 
-	AddMissingDependencies(deps []string)
-
 	InstallInData() bool
 	InstallInSanitizerDir() bool
 	InstallInRecovery() bool
@@ -133,30 +160,8 @@
 	HostRequiredModuleNames() []string
 	TargetRequiredModuleNames() []string
 
-	// android.ModuleContext methods
-	// These are duplicated instead of embedded so that can eventually be wrapped to take an
-	// android.Module instead of a blueprint.Module
-	OtherModuleName(m blueprint.Module) string
-	OtherModuleErrorf(m blueprint.Module, fmt string, args ...interface{})
-	OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
-
-	GetDirectDepsWithTag(tag blueprint.DependencyTag) []Module
-	GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
-	GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
-
 	ModuleSubDir() string
 
-	VisitDirectDepsBlueprint(visit func(blueprint.Module))
-	VisitDirectDeps(visit func(Module))
-	VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module))
-	VisitDirectDepsIf(pred func(Module) bool, visit func(Module))
-	// Deprecated: use WalkDeps instead to support multiple dependency tags on the same module
-	VisitDepsDepthFirst(visit func(Module))
-	// Deprecated: use WalkDeps instead to support multiple dependency tags on the same module
-	VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module))
-	WalkDeps(visit func(Module, Module) bool)
-	WalkDepsBlueprint(visit func(blueprint.Module, blueprint.Module) bool)
-
 	Variable(pctx PackageContext, name, value string)
 	Rule(pctx PackageContext, name string, params blueprint.RuleParams, argNames ...string) blueprint.Rule
 	// Similar to blueprint.ModuleContext.Build, but takes Paths instead of []string,
@@ -338,6 +343,8 @@
 	SkipInstall bool `blueprint:"mutated"`
 
 	NamespaceExportedToMake bool `blueprint:"mutated"`
+
+	MissingDeps []string `blueprint:"mutated"`
 }
 
 type hostAndDeviceProperties struct {
@@ -837,14 +844,22 @@
 func (m *ModuleBase) GenerateBuildActions(blueprintCtx blueprint.ModuleContext) {
 	ctx := &moduleContext{
 		module:            m.module,
-		ModuleContext:     blueprintCtx,
+		bp:                blueprintCtx,
 		baseModuleContext: m.baseModuleContextFactory(blueprintCtx),
 		installDeps:       m.computeInstallDeps(blueprintCtx),
 		installFiles:      m.installFiles,
-		missingDeps:       blueprintCtx.GetMissingDependencies(),
 		variables:         make(map[string]string),
 	}
 
+	// Temporarily continue to call blueprintCtx.GetMissingDependencies() to maintain the previous behavior of never
+	// reporting missing dependency errors in Blueprint when AllowMissingDependencies == true.
+	// TODO: This will be removed once defaults modules handle missing dependency errors
+	blueprintCtx.GetMissingDependencies()
+
+	// For the final GenerateAndroidBuildActions pass, require that all visited dependencies Soong modules and
+	// are enabled.
+	ctx.baseModuleContext.strictVisitDeps = true
+
 	if ctx.config.captureBuild {
 		ctx.ruleParams = make(map[blueprint.Rule]blueprint.RuleParams)
 	}
@@ -901,6 +916,12 @@
 			noticePath := filepath.Join(ctx.ModuleDir(), notice)
 			m.noticeFile = ExistentPathForSource(ctx, noticePath)
 		}
+	} else if ctx.Config().AllowMissingDependencies() {
+		// If the module is not enabled it will not create any build rules, nothing will call
+		// ctx.GetMissingDependencies(), and blueprint will consider the missing dependencies to be unhandled
+		// and report them as an error even when AllowMissingDependencies = true.  Call
+		// ctx.GetMissingDependencies() here to tell blueprint not to handle them.
+		ctx.GetMissingDependencies()
 	}
 
 	if m == ctx.FinalModule().(Module).base() {
@@ -923,15 +944,18 @@
 	debug         bool
 	kind          moduleKind
 	config        Config
+
+	walkPath []Module
+
+	strictVisitDeps bool // If true, enforce that all dependencies are enabled
 }
 
 type moduleContext struct {
-	blueprint.ModuleContext
+	bp blueprint.ModuleContext
 	baseModuleContext
 	installDeps     Paths
 	installFiles    Paths
 	checkbuildFiles Paths
-	missingDeps     []string
 	module          Module
 
 	// For tests
@@ -940,21 +964,18 @@
 	variables   map[string]string
 }
 
-func (m *moduleContext) ninjaError(desc string, outputs []string, err error) {
-	m.ModuleContext.Build(pctx.PackageContext, blueprint.BuildParams{
-		Rule:        ErrorRule,
-		Description: desc,
-		Outputs:     outputs,
-		Optional:    true,
+func (m *moduleContext) ninjaError(params BuildParams, err error) (PackageContext, BuildParams) {
+	return pctx, BuildParams{
+		Rule:            ErrorRule,
+		Description:     params.Description,
+		Output:          params.Output,
+		Outputs:         params.Outputs,
+		ImplicitOutput:  params.ImplicitOutput,
+		ImplicitOutputs: params.ImplicitOutputs,
 		Args: map[string]string{
 			"error": err.Error(),
 		},
-	})
-	return
-}
-
-func (m *moduleContext) Config() Config {
-	return m.ModuleContext.Config().(Config)
+	}
 }
 
 func (m *moduleContext) ModuleBuild(pctx PackageContext, params ModuleBuildParams) {
@@ -1006,13 +1027,13 @@
 		m.variables[name] = value
 	}
 
-	m.ModuleContext.Variable(pctx.PackageContext, name, value)
+	m.bp.Variable(pctx.PackageContext, name, value)
 }
 
 func (m *moduleContext) Rule(pctx PackageContext, name string, params blueprint.RuleParams,
 	argNames ...string) blueprint.Rule {
 
-	rule := m.ModuleContext.Rule(pctx.PackageContext, name, params, argNames...)
+	rule := m.bp.Rule(pctx.PackageContext, name, params, argNames...)
 
 	if m.config.captureBuild {
 		m.ruleParams[rule] = params
@@ -1022,65 +1043,79 @@
 }
 
 func (m *moduleContext) Build(pctx PackageContext, params BuildParams) {
+	if params.Description != "" {
+		params.Description = "${moduleDesc}" + params.Description + "${moduleDescSuffix}"
+	}
+
+	if missingDeps := m.GetMissingDependencies(); len(missingDeps) > 0 {
+		pctx, params = m.ninjaError(params, fmt.Errorf("module %s missing dependencies: %s\n",
+			m.ModuleName(), strings.Join(missingDeps, ", ")))
+	}
+
 	if m.config.captureBuild {
 		m.buildParams = append(m.buildParams, params)
 	}
 
-	bparams := convertBuildParams(params)
+	m.bp.Build(pctx.PackageContext, convertBuildParams(params))
+}
 
-	if bparams.Description != "" {
-		bparams.Description = "${moduleDesc}" + params.Description + "${moduleDescSuffix}"
-	}
+func (b *baseModuleContext) Module() Module {
+	module, _ := b.BaseModuleContext.Module().(Module)
+	return module
+}
 
-	if m.missingDeps != nil {
-		m.ninjaError(bparams.Description, bparams.Outputs,
-			fmt.Errorf("module %s missing dependencies: %s\n",
-				m.ModuleName(), strings.Join(m.missingDeps, ", ")))
-		return
-	}
-
-	m.ModuleContext.Build(pctx.PackageContext, bparams)
+func (b *baseModuleContext) Config() Config {
+	return b.BaseModuleContext.Config().(Config)
 }
 
 func (m *moduleContext) GetMissingDependencies() []string {
-	return m.missingDeps
+	var missingDeps []string
+	missingDeps = append(missingDeps, m.Module().base().commonProperties.MissingDeps...)
+	missingDeps = append(missingDeps, m.bp.GetMissingDependencies()...)
+	missingDeps = FirstUniqueStrings(missingDeps)
+	return missingDeps
 }
 
-func (m *moduleContext) AddMissingDependencies(deps []string) {
+func (b *baseModuleContext) AddMissingDependencies(deps []string) {
 	if deps != nil {
-		m.missingDeps = append(m.missingDeps, deps...)
-		m.missingDeps = FirstUniqueStrings(m.missingDeps)
+		missingDeps := &b.Module().base().commonProperties.MissingDeps
+		*missingDeps = append(*missingDeps, deps...)
+		*missingDeps = FirstUniqueStrings(*missingDeps)
 	}
 }
 
-func (m *moduleContext) validateAndroidModule(module blueprint.Module) Module {
+func (b *baseModuleContext) validateAndroidModule(module blueprint.Module, strict bool) Module {
 	aModule, _ := module.(Module)
+
+	if !strict {
+		return aModule
+	}
+
 	if aModule == nil {
-		m.ModuleErrorf("module %q not an android module", m.OtherModuleName(aModule))
+		b.ModuleErrorf("module %q not an android module", b.OtherModuleName(module))
 		return nil
 	}
 
 	if !aModule.Enabled() {
-		if m.Config().AllowMissingDependencies() {
-			m.AddMissingDependencies([]string{m.OtherModuleName(aModule)})
+		if b.Config().AllowMissingDependencies() {
+			b.AddMissingDependencies([]string{b.OtherModuleName(aModule)})
 		} else {
-			m.ModuleErrorf("depends on disabled module %q", m.OtherModuleName(aModule))
+			b.ModuleErrorf("depends on disabled module %q", b.OtherModuleName(aModule))
 		}
 		return nil
 	}
-
 	return aModule
 }
 
-func (m *moduleContext) getDirectDepInternal(name string, tag blueprint.DependencyTag) (blueprint.Module, blueprint.DependencyTag) {
+func (b *baseModuleContext) getDirectDepInternal(name string, tag blueprint.DependencyTag) (blueprint.Module, blueprint.DependencyTag) {
 	type dep struct {
 		mod blueprint.Module
 		tag blueprint.DependencyTag
 	}
 	var deps []dep
-	m.VisitDirectDepsBlueprint(func(module blueprint.Module) {
+	b.VisitDirectDepsBlueprint(func(module blueprint.Module) {
 		if aModule, _ := module.(Module); aModule != nil && aModule.base().BaseModuleName() == name {
-			returnedTag := m.ModuleContext.OtherModuleDependencyTag(aModule)
+			returnedTag := b.BaseModuleContext.OtherModuleDependencyTag(aModule)
 			if tag == nil || returnedTag == tag {
 				deps = append(deps, dep{aModule, returnedTag})
 			}
@@ -1090,17 +1125,17 @@
 		return deps[0].mod, deps[0].tag
 	} else if len(deps) >= 2 {
 		panic(fmt.Errorf("Multiple dependencies having same BaseModuleName() %q found from %q",
-			name, m.ModuleName()))
+			name, b.ModuleName()))
 	} else {
 		return nil, nil
 	}
 }
 
-func (m *moduleContext) GetDirectDepsWithTag(tag blueprint.DependencyTag) []Module {
+func (b *baseModuleContext) GetDirectDepsWithTag(tag blueprint.DependencyTag) []Module {
 	var deps []Module
-	m.VisitDirectDepsBlueprint(func(module blueprint.Module) {
+	b.VisitDirectDepsBlueprint(func(module blueprint.Module) {
 		if aModule, _ := module.(Module); aModule != nil {
-			if m.ModuleContext.OtherModuleDependencyTag(aModule) == tag {
+			if b.BaseModuleContext.OtherModuleDependencyTag(aModule) == tag {
 				deps = append(deps, aModule)
 			}
 		}
@@ -1113,37 +1148,37 @@
 	return module
 }
 
-func (m *moduleContext) GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag) {
-	return m.getDirectDepInternal(name, nil)
+func (b *baseModuleContext) GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag) {
+	return b.getDirectDepInternal(name, nil)
 }
 
-func (m *moduleContext) VisitDirectDepsBlueprint(visit func(blueprint.Module)) {
-	m.ModuleContext.VisitDirectDeps(visit)
+func (b *baseModuleContext) VisitDirectDepsBlueprint(visit func(blueprint.Module)) {
+	b.BaseModuleContext.VisitDirectDeps(visit)
 }
 
-func (m *moduleContext) VisitDirectDeps(visit func(Module)) {
-	m.ModuleContext.VisitDirectDeps(func(module blueprint.Module) {
-		if aModule := m.validateAndroidModule(module); aModule != nil {
+func (b *baseModuleContext) VisitDirectDeps(visit func(Module)) {
+	b.BaseModuleContext.VisitDirectDeps(func(module blueprint.Module) {
+		if aModule := b.validateAndroidModule(module, b.strictVisitDeps); aModule != nil {
 			visit(aModule)
 		}
 	})
 }
 
-func (m *moduleContext) VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module)) {
-	m.ModuleContext.VisitDirectDeps(func(module blueprint.Module) {
-		if aModule := m.validateAndroidModule(module); aModule != nil {
-			if m.ModuleContext.OtherModuleDependencyTag(aModule) == tag {
+func (b *baseModuleContext) VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module)) {
+	b.BaseModuleContext.VisitDirectDeps(func(module blueprint.Module) {
+		if aModule := b.validateAndroidModule(module, b.strictVisitDeps); aModule != nil {
+			if b.BaseModuleContext.OtherModuleDependencyTag(aModule) == tag {
 				visit(aModule)
 			}
 		}
 	})
 }
 
-func (m *moduleContext) VisitDirectDepsIf(pred func(Module) bool, visit func(Module)) {
-	m.ModuleContext.VisitDirectDepsIf(
+func (b *baseModuleContext) VisitDirectDepsIf(pred func(Module) bool, visit func(Module)) {
+	b.BaseModuleContext.VisitDirectDepsIf(
 		// pred
 		func(module blueprint.Module) bool {
-			if aModule := m.validateAndroidModule(module); aModule != nil {
+			if aModule := b.validateAndroidModule(module, b.strictVisitDeps); aModule != nil {
 				return pred(aModule)
 			} else {
 				return false
@@ -1155,19 +1190,19 @@
 		})
 }
 
-func (m *moduleContext) VisitDepsDepthFirst(visit func(Module)) {
-	m.ModuleContext.VisitDepsDepthFirst(func(module blueprint.Module) {
-		if aModule := m.validateAndroidModule(module); aModule != nil {
+func (b *baseModuleContext) VisitDepsDepthFirst(visit func(Module)) {
+	b.BaseModuleContext.VisitDepsDepthFirst(func(module blueprint.Module) {
+		if aModule := b.validateAndroidModule(module, b.strictVisitDeps); aModule != nil {
 			visit(aModule)
 		}
 	})
 }
 
-func (m *moduleContext) VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module)) {
-	m.ModuleContext.VisitDepsDepthFirstIf(
+func (b *baseModuleContext) VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module)) {
+	b.BaseModuleContext.VisitDepsDepthFirstIf(
 		// pred
 		func(module blueprint.Module) bool {
-			if aModule := m.validateAndroidModule(module); aModule != nil {
+			if aModule := b.validateAndroidModule(module, b.strictVisitDeps); aModule != nil {
 				return pred(aModule)
 			} else {
 				return false
@@ -1179,15 +1214,21 @@
 		})
 }
 
-func (m *moduleContext) WalkDepsBlueprint(visit func(blueprint.Module, blueprint.Module) bool) {
-	m.ModuleContext.WalkDeps(visit)
+func (b *baseModuleContext) WalkDepsBlueprint(visit func(blueprint.Module, blueprint.Module) bool) {
+	b.BaseModuleContext.WalkDeps(visit)
 }
 
-func (m *moduleContext) WalkDeps(visit func(Module, Module) bool) {
-	m.ModuleContext.WalkDeps(func(child, parent blueprint.Module) bool {
-		childAndroidModule := m.validateAndroidModule(child)
-		parentAndroidModule := m.validateAndroidModule(parent)
+func (b *baseModuleContext) WalkDeps(visit func(Module, Module) bool) {
+	b.walkPath = []Module{b.Module()}
+	b.BaseModuleContext.WalkDeps(func(child, parent blueprint.Module) bool {
+		childAndroidModule, _ := child.(Module)
+		parentAndroidModule, _ := parent.(Module)
 		if childAndroidModule != nil && parentAndroidModule != nil {
+			// record walkPath before visit
+			for b.walkPath[len(b.walkPath)-1] != parentAndroidModule {
+				b.walkPath = b.walkPath[0 : len(b.walkPath)-1]
+			}
+			b.walkPath = append(b.walkPath, childAndroidModule)
 			return visit(childAndroidModule, parentAndroidModule)
 		} else {
 			return false
@@ -1195,18 +1236,26 @@
 	})
 }
 
+func (b *baseModuleContext) GetWalkPath() []Module {
+	return b.walkPath
+}
+
 func (m *moduleContext) VisitAllModuleVariants(visit func(Module)) {
-	m.ModuleContext.VisitAllModuleVariants(func(module blueprint.Module) {
+	m.bp.VisitAllModuleVariants(func(module blueprint.Module) {
 		visit(module.(Module))
 	})
 }
 
 func (m *moduleContext) PrimaryModule() Module {
-	return m.ModuleContext.PrimaryModule().(Module)
+	return m.bp.PrimaryModule().(Module)
 }
 
 func (m *moduleContext) FinalModule() Module {
-	return m.ModuleContext.FinalModule().(Module)
+	return m.bp.FinalModule().(Module)
+}
+
+func (m *moduleContext) ModuleSubDir() string {
+	return m.bp.ModuleSubDir()
 }
 
 func (b *baseModuleContext) Target() Target {
@@ -1584,20 +1633,20 @@
 	return m.module.base().commonProperties.Target_required
 }
 
-func (m *moduleContext) Glob(globPattern string, excludes []string) Paths {
-	ret, err := m.GlobWithDeps(globPattern, excludes)
+func (b *baseModuleContext) Glob(globPattern string, excludes []string) Paths {
+	ret, err := b.GlobWithDeps(globPattern, excludes)
 	if err != nil {
-		m.ModuleErrorf("glob: %s", err.Error())
+		b.ModuleErrorf("glob: %s", err.Error())
 	}
-	return pathsForModuleSrcFromFullPath(m, ret, true)
+	return pathsForModuleSrcFromFullPath(b, ret, true)
 }
 
-func (m *moduleContext) GlobFiles(globPattern string, excludes []string) Paths {
-	ret, err := m.GlobWithDeps(globPattern, excludes)
+func (b *baseModuleContext) GlobFiles(globPattern string, excludes []string) Paths {
+	ret, err := b.GlobWithDeps(globPattern, excludes)
 	if err != nil {
-		m.ModuleErrorf("glob: %s", err.Error())
+		b.ModuleErrorf("glob: %s", err.Error())
 	}
-	return pathsForModuleSrcFromFullPath(m, ret, false)
+	return pathsForModuleSrcFromFullPath(b, ret, false)
 }
 
 func init() {
diff --git a/android/mutator.go b/android/mutator.go
index cd0d152..081c2b2 100644
--- a/android/mutator.go
+++ b/android/mutator.go
@@ -115,35 +115,14 @@
 type TopDownMutatorContext interface {
 	BaseModuleContext
 
-	OtherModuleExists(name string) bool
 	Rename(name string)
-	Module() Module
-
-	OtherModuleName(m blueprint.Module) string
-	OtherModuleDir(m blueprint.Module) string
-	OtherModuleErrorf(m blueprint.Module, fmt string, args ...interface{})
-	OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
 
 	CreateModule(blueprint.ModuleFactory, ...interface{})
-
-	GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
-	GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
-
-	VisitDirectDeps(visit func(Module))
-	VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module))
-	VisitDirectDepsIf(pred func(Module) bool, visit func(Module))
-	VisitDepsDepthFirst(visit func(Module))
-	VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module))
-	WalkDeps(visit func(Module, Module) bool)
-	// GetWalkPath is supposed to be called in visit function passed in WalkDeps()
-	// and returns a top-down dependency path from a start module to current child module.
-	GetWalkPath() []Module
 }
 
 type topDownMutatorContext struct {
-	blueprint.TopDownMutatorContext
+	bp blueprint.TopDownMutatorContext
 	baseModuleContext
-	walkPath []Module
 }
 
 type BottomUpMutator func(BottomUpMutatorContext)
@@ -151,9 +130,7 @@
 type BottomUpMutatorContext interface {
 	BaseModuleContext
 
-	OtherModuleExists(name string) bool
 	Rename(name string)
-	Module() blueprint.Module
 
 	AddDependency(module blueprint.Module, tag blueprint.DependencyTag, name ...string)
 	AddReverseDependency(module blueprint.Module, tag blueprint.DependencyTag, name string)
@@ -167,7 +144,7 @@
 }
 
 type bottomUpMutatorContext struct {
-	blueprint.BottomUpMutatorContext
+	bp blueprint.BottomUpMutatorContext
 	baseModuleContext
 }
 
@@ -175,8 +152,8 @@
 	f := func(ctx blueprint.BottomUpMutatorContext) {
 		if a, ok := ctx.Module().(Module); ok {
 			actx := &bottomUpMutatorContext{
-				BottomUpMutatorContext: ctx,
-				baseModuleContext:      a.base().baseModuleContextFactory(ctx),
+				bp:                ctx,
+				baseModuleContext: a.base().baseModuleContextFactory(ctx),
 			}
 			m(actx)
 		}
@@ -190,8 +167,8 @@
 	f := func(ctx blueprint.TopDownMutatorContext) {
 		if a, ok := ctx.Module().(Module); ok {
 			actx := &topDownMutatorContext{
-				TopDownMutatorContext: ctx,
-				baseModuleContext:     a.base().baseModuleContextFactory(ctx),
+				bp:                ctx,
+				baseModuleContext: a.base().baseModuleContextFactory(ctx),
 			}
 			m(actx)
 		}
@@ -216,99 +193,6 @@
 	}
 }
 
-func (t *topDownMutatorContext) Config() Config {
-	return t.config
-}
-
-func (b *bottomUpMutatorContext) Config() Config {
-	return b.config
-}
-
-func (t *topDownMutatorContext) Module() Module {
-	module, _ := t.TopDownMutatorContext.Module().(Module)
-	return module
-}
-
-func (t *topDownMutatorContext) VisitDirectDeps(visit func(Module)) {
-	t.TopDownMutatorContext.VisitDirectDeps(func(module blueprint.Module) {
-		if aModule, _ := module.(Module); aModule != nil {
-			visit(aModule)
-		}
-	})
-}
-
-func (t *topDownMutatorContext) VisitDirectDepsWithTag(tag blueprint.DependencyTag, visit func(Module)) {
-	t.TopDownMutatorContext.VisitDirectDeps(func(module blueprint.Module) {
-		if aModule, _ := module.(Module); aModule != nil {
-			if t.TopDownMutatorContext.OtherModuleDependencyTag(aModule) == tag {
-				visit(aModule)
-			}
-		}
-	})
-}
-
-func (t *topDownMutatorContext) VisitDirectDepsIf(pred func(Module) bool, visit func(Module)) {
-	t.TopDownMutatorContext.VisitDirectDepsIf(
-		// pred
-		func(module blueprint.Module) bool {
-			if aModule, _ := module.(Module); aModule != nil {
-				return pred(aModule)
-			} else {
-				return false
-			}
-		},
-		// visit
-		func(module blueprint.Module) {
-			visit(module.(Module))
-		})
-}
-
-func (t *topDownMutatorContext) VisitDepsDepthFirst(visit func(Module)) {
-	t.TopDownMutatorContext.VisitDepsDepthFirst(func(module blueprint.Module) {
-		if aModule, _ := module.(Module); aModule != nil {
-			visit(aModule)
-		}
-	})
-}
-
-func (t *topDownMutatorContext) VisitDepsDepthFirstIf(pred func(Module) bool, visit func(Module)) {
-	t.TopDownMutatorContext.VisitDepsDepthFirstIf(
-		// pred
-		func(module blueprint.Module) bool {
-			if aModule, _ := module.(Module); aModule != nil {
-				return pred(aModule)
-			} else {
-				return false
-			}
-		},
-		// visit
-		func(module blueprint.Module) {
-			visit(module.(Module))
-		})
-}
-
-func (t *topDownMutatorContext) WalkDeps(visit func(Module, Module) bool) {
-	t.walkPath = []Module{t.Module()}
-	t.TopDownMutatorContext.WalkDeps(func(child, parent blueprint.Module) bool {
-		childAndroidModule, _ := child.(Module)
-		parentAndroidModule, _ := parent.(Module)
-		if childAndroidModule != nil && parentAndroidModule != nil {
-			// record walkPath before visit
-			for t.walkPath[len(t.walkPath)-1] != parentAndroidModule {
-				t.walkPath = t.walkPath[0 : len(t.walkPath)-1]
-			}
-			t.walkPath = append(t.walkPath, childAndroidModule)
-			return visit(childAndroidModule, parentAndroidModule)
-		} else {
-			return false
-		}
-	})
-}
-
-func (t *topDownMutatorContext) GetWalkPath() []Module {
-	return t.walkPath
-}
-
 func (t *topDownMutatorContext) AppendProperties(props ...interface{}) {
 	for _, p := range props {
 		err := proptools.AppendMatchingProperties(t.Module().base().customizableProperties,
@@ -336,3 +220,61 @@
 		}
 	}
 }
+
+// android.topDownMutatorContext either has to embed blueprint.TopDownMutatorContext, in which case every method that
+// has an overridden version in android.BaseModuleContext has to be manually forwarded to BaseModuleContext to avoid
+// ambiguous method errors, or it has to store a blueprint.TopDownMutatorContext non-embedded, in which case every
+// non-overridden method has to be forwarded.  There are fewer non-overridden methods, so use the latter.  The following
+// methods forward to the identical blueprint versions for topDownMutatorContext and bottomUpMutatorContext.
+
+func (t *topDownMutatorContext) Rename(name string) {
+	t.bp.Rename(name)
+}
+
+func (t *topDownMutatorContext) CreateModule(factory blueprint.ModuleFactory, props ...interface{}) {
+	t.bp.CreateModule(factory, props...)
+}
+
+func (b *bottomUpMutatorContext) Rename(name string) {
+	b.bp.Rename(name)
+}
+
+func (b *bottomUpMutatorContext) AddDependency(module blueprint.Module, tag blueprint.DependencyTag, name ...string) {
+	b.bp.AddDependency(module, tag, name...)
+}
+
+func (b *bottomUpMutatorContext) AddReverseDependency(module blueprint.Module, tag blueprint.DependencyTag, name string) {
+	b.bp.AddReverseDependency(module, tag, name)
+}
+
+func (b *bottomUpMutatorContext) CreateVariations(variations ...string) []blueprint.Module {
+	return b.bp.CreateVariations(variations...)
+}
+
+func (b *bottomUpMutatorContext) CreateLocalVariations(variations ...string) []blueprint.Module {
+	return b.bp.CreateLocalVariations(variations...)
+}
+
+func (b *bottomUpMutatorContext) SetDependencyVariation(variation string) {
+	b.bp.SetDependencyVariation(variation)
+}
+
+func (b *bottomUpMutatorContext) AddVariationDependencies(variations []blueprint.Variation, tag blueprint.DependencyTag,
+	names ...string) {
+
+	b.bp.AddVariationDependencies(variations, tag, names...)
+}
+
+func (b *bottomUpMutatorContext) AddFarVariationDependencies(variations []blueprint.Variation,
+	tag blueprint.DependencyTag, names ...string) {
+
+	b.bp.AddFarVariationDependencies(variations, tag, names...)
+}
+
+func (b *bottomUpMutatorContext) AddInterVariantDependency(tag blueprint.DependencyTag, from, to blueprint.Module) {
+	b.bp.AddInterVariantDependency(tag, from, to)
+}
+
+func (b *bottomUpMutatorContext) ReplaceDependencies(name string) {
+	b.bp.ReplaceDependencies(name)
+}
diff --git a/android/mutator_test.go b/android/mutator_test.go
new file mode 100644
index 0000000..4cef400
--- /dev/null
+++ b/android/mutator_test.go
@@ -0,0 +1,99 @@
+// Copyright 2015 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package android
+
+import (
+	"io/ioutil"
+	"os"
+	"reflect"
+	"testing"
+
+	"github.com/google/blueprint/proptools"
+)
+
+type mutatorTestModule struct {
+	ModuleBase
+	props struct {
+	}
+
+	missingDeps []string
+}
+
+func mutatorTestModuleFactory() Module {
+	module := &mutatorTestModule{}
+	module.AddProperties(&module.props)
+	InitAndroidModule(module)
+	return module
+}
+
+func (m *mutatorTestModule) GenerateAndroidBuildActions(ctx ModuleContext) {
+	ctx.Build(pctx, BuildParams{
+		Rule:   Touch,
+		Output: PathForModuleOut(ctx, "output"),
+	})
+
+	m.missingDeps = ctx.GetMissingDependencies()
+}
+
+func (m *mutatorTestModule) DepsMutator(ctx BottomUpMutatorContext) {
+	ctx.AddDependency(ctx.Module(), nil, "regular_missing_dep")
+}
+
+func addMissingDependenciesMutator(ctx TopDownMutatorContext) {
+	ctx.AddMissingDependencies([]string{"added_missing_dep"})
+}
+
+func TestMutatorAddMissingDependencies(t *testing.T) {
+	buildDir, err := ioutil.TempDir("", "soong_mutator_test")
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer os.RemoveAll(buildDir)
+
+	config := TestConfig(buildDir, nil)
+	config.TestProductVariables.Allow_missing_dependencies = proptools.BoolPtr(true)
+
+	ctx := NewTestContext()
+	ctx.SetAllowMissingDependencies(true)
+
+	ctx.RegisterModuleType("test", ModuleFactoryAdaptor(mutatorTestModuleFactory))
+	ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
+		ctx.TopDown("add_missing_dependencies", addMissingDependenciesMutator)
+	})
+
+	bp := `
+		test {
+			name: "foo",
+		}
+	`
+
+	mockFS := map[string][]byte{
+		"Android.bp": []byte(bp),
+	}
+
+	ctx.MockFileSystem(mockFS)
+
+	ctx.Register()
+	_, errs := ctx.ParseFileList(".", []string{"Android.bp"})
+	FailIfErrored(t, errs)
+	_, errs = ctx.PrepareBuildActions(config)
+	FailIfErrored(t, errs)
+
+	foo := ctx.ModuleForTests("foo", "").Module().(*mutatorTestModule)
+
+	if g, w := foo.missingDeps, []string{"added_missing_dep", "regular_missing_dep"}; !reflect.DeepEqual(g, w) {
+		t.Errorf("want foo missing deps %q, got %q", w, g)
+	}
+}
diff --git a/android/namespace.go b/android/namespace.go
index 78d7f3c..27ec163 100644
--- a/android/namespace.go
+++ b/android/namespace.go
@@ -222,6 +222,11 @@
 }
 
 func (r *NameResolver) getNamespacesToSearchForModule(sourceNamespace *Namespace) (searchOrder []*Namespace) {
+	if sourceNamespace.visibleNamespaces == nil {
+		// When handling dependencies before namespaceMutator, assume they are non-Soong Blueprint modules and give
+		// access to all namespaces.
+		return r.sortedNamespaces.sortedItems()
+	}
 	return sourceNamespace.visibleNamespaces
 }
 
diff --git a/android/namespace_test.go b/android/namespace_test.go
index 9a791a5..20241fe 100644
--- a/android/namespace_test.go
+++ b/android/namespace_test.go
@@ -16,8 +16,6 @@
 
 import (
 	"errors"
-	"io/ioutil"
-	"os"
 	"path/filepath"
 	"reflect"
 	"testing"
@@ -93,6 +91,28 @@
 	// setupTest will report any errors
 }
 
+func TestDependingOnBlueprintModuleInRootNamespace(t *testing.T) {
+	_ = setupTest(t,
+		map[string]string{
+			".": `
+			blueprint_test_module {
+				name: "a",
+			}
+			`,
+			"dir1": `
+			soong_namespace {
+			}
+			blueprint_test_module {
+				name: "b",
+				deps: ["a"],
+			}
+			`,
+		},
+	)
+
+	// setupTest will report any errors
+}
+
 func TestDependingOnModuleInImportedNamespace(t *testing.T) {
 	ctx := setupTest(t,
 		map[string]string{
@@ -613,18 +633,13 @@
 }
 
 func setupTestFromFiles(bps map[string][]byte) (ctx *TestContext, errs []error) {
-	buildDir, err := ioutil.TempDir("", "soong_namespace_test")
-	if err != nil {
-		return nil, []error{err}
-	}
-	defer os.RemoveAll(buildDir)
-
 	config := TestConfig(buildDir, nil)
 
 	ctx = NewTestContext()
 	ctx.MockFileSystem(bps)
 	ctx.RegisterModuleType("test_module", ModuleFactoryAdaptor(newTestModule))
 	ctx.RegisterModuleType("soong_namespace", ModuleFactoryAdaptor(NamespaceFactory))
+	ctx.RegisterModuleType("blueprint_test_module", newBlueprintTestModule)
 	ctx.PreArchMutators(RegisterNamespaceMutator)
 	ctx.PreDepsMutators(func(ctx RegisterMutatorsContext) {
 		ctx.BottomUp("rename", renameMutator)
@@ -649,6 +664,7 @@
 }
 
 func setupTest(t *testing.T, bps map[string]string) (ctx *TestContext) {
+	t.Helper()
 	ctx, errs := setupTestExpectErrs(bps)
 	FailIfErrored(t, errs)
 	return ctx
@@ -726,3 +742,22 @@
 	InitAndroidModule(m)
 	return m
 }
+
+type blueprintTestModule struct {
+	blueprint.SimpleName
+	properties struct {
+		Deps []string
+	}
+}
+
+func (b *blueprintTestModule) DynamicDependencies(ctx blueprint.DynamicDependerModuleContext) []string {
+	return b.properties.Deps
+}
+
+func (b *blueprintTestModule) GenerateBuildActions(blueprint.ModuleContext) {
+}
+
+func newBlueprintTestModule() (blueprint.Module, []interface{}) {
+	m := &blueprintTestModule{}
+	return m, []interface{}{&m.properties, &m.SimpleName.Properties}
+}
diff --git a/android/neverallow.go b/android/neverallow.go
index 9314483..f751389 100644
--- a/android/neverallow.go
+++ b/android/neverallow.go
@@ -52,6 +52,7 @@
 	rules = append(rules, createTrebleRules()...)
 	rules = append(rules, createLibcoreRules()...)
 	rules = append(rules, createJavaDeviceForHostRules()...)
+	rules = append(rules, createJavaLibraryHostRules()...)
 	return rules
 }
 
@@ -95,6 +96,9 @@
 		"external/icu",
 		"external/okhttp",
 		"external/wycheproof",
+
+		// Not really a core library but still needs access to same capabilities.
+		"development",
 	}
 
 	// Core library constraints. The no_standard_libs can only be used in core
@@ -102,8 +106,11 @@
 	// visibility rules.
 	rules := []*rule{
 		neverallow().
-			notIn(append(coreLibraryProjects, "development")...).
+			notIn(coreLibraryProjects...).
 			with("no_standard_libs", "true"),
+		neverallow().
+			notIn(coreLibraryProjects...).
+			with("sdk_version", "none"),
 	}
 
 	return rules
@@ -124,6 +131,15 @@
 	}
 }
 
+func createJavaLibraryHostRules() []*rule {
+	return []*rule{
+		neverallow().
+			moduleType("java_library_host").
+			with("no_standard_libs", "true").
+			because("no_standard_libs makes no sense with java_library_host"),
+	}
+}
+
 func neverallowMutator(ctx BottomUpMutatorContext) {
 	m, ok := ctx.Module().(Module)
 	if !ok {
diff --git a/android/neverallow_test.go b/android/neverallow_test.go
index 00c51ea..62c5142 100644
--- a/android/neverallow_test.go
+++ b/android/neverallow_test.go
@@ -15,8 +15,6 @@
 package android
 
 import (
-	"io/ioutil"
-	"os"
 	"testing"
 )
 
@@ -148,15 +146,84 @@
 		},
 		expectedError: "java_device_for_host can only be used in whitelisted projects",
 	},
+	// Libcore rule tests
+	{
+		name: "no_standard_libs: true inside core libraries",
+		fs: map[string][]byte{
+			"libcore/Blueprints": []byte(`
+				java_library {
+					name: "inside_core_libraries",
+					no_standard_libs: true,
+				}`),
+		},
+	},
+	{
+		name: "no_standard_libs: true outside core libraries",
+		fs: map[string][]byte{
+			"Blueprints": []byte(`
+				java_library {
+					name: "outside_core_libraries",
+					no_standard_libs: true,
+				}`),
+		},
+		expectedError: "module \"outside_core_libraries\": violates neverallow",
+	},
+	{
+		name: "no_standard_libs: false",
+		fs: map[string][]byte{
+			"Blueprints": []byte(`
+				java_library {
+					name: "outside_core_libraries",
+					no_standard_libs: false,
+				}`),
+		},
+	},
+	{
+		name: "sdk_version: \"none\" inside core libraries",
+		fs: map[string][]byte{
+			"libcore/Blueprints": []byte(`
+				java_library {
+					name: "inside_core_libraries",
+					sdk_version: "none",
+				}`),
+		},
+	},
+	{
+		name: "sdk_version: \"none\" outside core libraries",
+		fs: map[string][]byte{
+			"Blueprints": []byte(`
+				java_library {
+					name: "outside_core_libraries",
+					sdk_version: "none",
+				}`),
+		},
+		expectedError: "module \"outside_core_libraries\": violates neverallow",
+	},
+	{
+		name: "sdk_version: \"current\"",
+		fs: map[string][]byte{
+			"Blueprints": []byte(`
+				java_library {
+					name: "outside_core_libraries",
+					sdk_version: "current",
+				}`),
+		},
+	},
+	// java_library_host rule tests
+	{
+		name: "java_library_host with no_standard_libs: true",
+		fs: map[string][]byte{
+			"libcore/Blueprints": []byte(`
+				java_library_host {
+					name: "inside_core_libraries",
+					no_standard_libs: true,
+				}`),
+		},
+		expectedError: "module \"inside_core_libraries\": violates neverallow",
+	},
 }
 
 func TestNeverallow(t *testing.T) {
-	buildDir, err := ioutil.TempDir("", "soong_neverallow_test")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer os.RemoveAll(buildDir)
-
 	config := TestConfig(buildDir, nil)
 
 	for _, test := range neverallowTests {
@@ -176,6 +243,7 @@
 	ctx := NewTestContext()
 	ctx.RegisterModuleType("cc_library", ModuleFactoryAdaptor(newMockCcLibraryModule))
 	ctx.RegisterModuleType("java_library", ModuleFactoryAdaptor(newMockJavaLibraryModule))
+	ctx.RegisterModuleType("java_library_host", ModuleFactoryAdaptor(newMockJavaLibraryModule))
 	ctx.RegisterModuleType("java_device_for_host", ModuleFactoryAdaptor(newMockJavaLibraryModule))
 	ctx.PostDepsMutators(registerNeverallowMutator)
 	ctx.Register()
@@ -227,7 +295,9 @@
 }
 
 type mockJavaLibraryProperties struct {
-	Libs []string
+	Libs             []string
+	No_standard_libs *bool
+	Sdk_version      *string
 }
 
 type mockJavaLibraryModule struct {
diff --git a/android/paths.go b/android/paths.go
index 52d22d5..20b8b82 100644
--- a/android/paths.go
+++ b/android/paths.go
@@ -367,7 +367,7 @@
 // each string. If incDirs is false, strip paths with a trailing '/' from the list.
 // It intended for use in globs that only list files that exist, so it allows '$' in
 // filenames.
-func pathsForModuleSrcFromFullPath(ctx ModuleContext, paths []string, incDirs bool) Paths {
+func pathsForModuleSrcFromFullPath(ctx BaseModuleContext, paths []string, incDirs bool) Paths {
 	prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
 	if prefix == "./" {
 		prefix = ""
diff --git a/android/paths_test.go b/android/paths_test.go
index 78cfbbe..7bcfe41 100644
--- a/android/paths_test.go
+++ b/android/paths_test.go
@@ -17,8 +17,6 @@
 import (
 	"errors"
 	"fmt"
-	"io/ioutil"
-	"os"
 	"reflect"
 	"strings"
 	"testing"
@@ -758,6 +756,11 @@
 	if !p.props.Module_handles_missing_deps {
 		p.missingDeps = ctx.GetMissingDependencies()
 	}
+
+	ctx.Build(pctx, BuildParams{
+		Rule:   Touch,
+		Output: PathForModuleOut(ctx, "output"),
+	})
 }
 
 type pathForModuleSrcOutputFileProviderModule struct {
@@ -875,12 +878,6 @@
 }
 
 func TestPathsForModuleSrc(t *testing.T) {
-	buildDir, err := ioutil.TempDir("", "soong_paths_for_module_src_test")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer os.RemoveAll(buildDir)
-
 	tests := []pathForModuleSrcTestCase{
 		{
 			name: "path",
@@ -961,12 +958,6 @@
 }
 
 func TestPathForModuleSrc(t *testing.T) {
-	buildDir, err := ioutil.TempDir("", "soong_path_for_module_src_test")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer os.RemoveAll(buildDir)
-
 	tests := []pathForModuleSrcTestCase{
 		{
 			name: "path",
@@ -1034,12 +1025,6 @@
 }
 
 func TestPathsForModuleSrc_AllowMissingDependencies(t *testing.T) {
-	buildDir, err := ioutil.TempDir("", "soong_paths_for_module_src_allow_missing_dependencies_test")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer os.RemoveAll(buildDir)
-
 	config := TestConfig(buildDir, nil)
 	config.TestProductVariables.Allow_missing_dependencies = proptools.BoolPtr(true)
 
diff --git a/android/prebuilt_etc_test.go b/android/prebuilt_etc_test.go
index d977c30..0a2c7a4 100644
--- a/android/prebuilt_etc_test.go
+++ b/android/prebuilt_etc_test.go
@@ -15,16 +15,13 @@
 package android
 
 import (
-	"io/ioutil"
-	"os"
 	"path/filepath"
 	"reflect"
 	"testing"
 )
 
 func testPrebuiltEtc(t *testing.T, bp string) (*TestContext, Config) {
-	config, buildDir := setUp(t)
-	defer tearDown(buildDir)
+	config := TestArchConfig(buildDir, nil)
 	ctx := NewTestArchContext()
 	ctx.RegisterModuleType("prebuilt_etc", ModuleFactoryAdaptor(PrebuiltEtcFactory))
 	ctx.RegisterModuleType("prebuilt_etc_host", ModuleFactoryAdaptor(PrebuiltEtcHostFactory))
@@ -51,20 +48,6 @@
 	return ctx, config
 }
 
-func setUp(t *testing.T) (config Config, buildDir string) {
-	buildDir, err := ioutil.TempDir("", "soong_prebuilt_etc_test")
-	if err != nil {
-		t.Fatal(err)
-	}
-
-	config = TestArchConfig(buildDir, nil)
-	return
-}
-
-func tearDown(buildDir string) {
-	os.RemoveAll(buildDir)
-}
-
 func TestPrebuiltEtcVariants(t *testing.T) {
 	ctx, _ := testPrebuiltEtc(t, `
 		prebuilt_etc {
diff --git a/android/prebuilt_test.go b/android/prebuilt_test.go
index a5b85c8..0a18e2c 100644
--- a/android/prebuilt_test.go
+++ b/android/prebuilt_test.go
@@ -16,8 +16,6 @@
 
 import (
 	"fmt"
-	"io/ioutil"
-	"os"
 	"testing"
 
 	"github.com/google/blueprint"
@@ -127,12 +125,6 @@
 }
 
 func TestPrebuilts(t *testing.T) {
-	buildDir, err := ioutil.TempDir("", "soong_prebuilt_test")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer os.RemoveAll(buildDir)
-
 	config := TestConfig(buildDir, nil)
 
 	for _, test := range prebuiltsTests {
diff --git a/android/rule_builder.go b/android/rule_builder.go
index 4a3b022..8d7e74b 100644
--- a/android/rule_builder.go
+++ b/android/rule_builder.go
@@ -525,6 +525,15 @@
 	return c
 }
 
+// OutputDir adds the output directory to the command line. This is only available when used with RuleBuilder.Sbox,
+// and will be the temporary output directory managed by sbox, not the final one.
+func (c *RuleBuilderCommand) OutputDir() *RuleBuilderCommand {
+	if !c.sbox {
+		panic("OutputDir only valid with Sbox")
+	}
+	return c.Text("__SBOX_OUT_DIR__")
+}
+
 // DepFile adds the specified depfile path to the paths returned by RuleBuilder.DepFiles and adds it to the command
 // line, and causes RuleBuilder.Build file to set the depfile flag for ninja.  If multiple depfiles are added to
 // commands in a single RuleBuilder then RuleBuilder.Build will add an extra command to merge the depfiles together.
diff --git a/android/rule_builder_test.go b/android/rule_builder_test.go
index df0f256..cfbc2ab 100644
--- a/android/rule_builder_test.go
+++ b/android/rule_builder_test.go
@@ -16,8 +16,6 @@
 
 import (
 	"fmt"
-	"io/ioutil"
-	"os"
 	"path/filepath"
 	"reflect"
 	"strings"
@@ -418,12 +416,6 @@
 }
 
 func TestRuleBuilder_Build(t *testing.T) {
-	buildDir, err := ioutil.TempDir("", "soong_test_rule_builder")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer os.RemoveAll(buildDir)
-
 	bp := `
 		rule_builder_test {
 			name: "foo",
diff --git a/android/sh_binary_test.go b/android/sh_binary_test.go
index becb35a..c99e18c 100644
--- a/android/sh_binary_test.go
+++ b/android/sh_binary_test.go
@@ -1,19 +1,11 @@
 package android
 
 import (
-	"io/ioutil"
-	"os"
 	"reflect"
 	"testing"
 )
 
 func testShBinary(t *testing.T, bp string) (*TestContext, Config) {
-	buildDir, err := ioutil.TempDir("", "soong_sh_binary_test")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer os.RemoveAll(buildDir)
-
 	config := TestArchConfig(buildDir, nil)
 
 	ctx := NewTestArchContext()
diff --git a/android/testing.go b/android/testing.go
index c0db75e..44bee4b 100644
--- a/android/testing.go
+++ b/android/testing.go
@@ -179,7 +179,7 @@
 
 func maybeBuildParamsFromDescription(provider testBuildProvider, desc string) TestingBuildParams {
 	for _, p := range provider.BuildParamsForTests() {
-		if p.Description == desc {
+		if strings.Contains(p.Description, desc) {
 			return newTestingBuildParams(provider, p)
 		}
 	}
diff --git a/android/visibility_test.go b/android/visibility_test.go
index 09c5b1b..1a51495 100644
--- a/android/visibility_test.go
+++ b/android/visibility_test.go
@@ -1,8 +1,6 @@
 package android
 
 import (
-	"io/ioutil"
-	"os"
 	"testing"
 
 	"github.com/google/blueprint"
@@ -663,12 +661,6 @@
 }
 
 func TestVisibility(t *testing.T) {
-	buildDir, err := ioutil.TempDir("", "soong_neverallow_test")
-	if err != nil {
-		t.Fatal(err)
-	}
-	defer os.RemoveAll(buildDir)
-
 	for _, test := range visibilityTests {
 		t.Run(test.name, func(t *testing.T) {
 			_, errs := testVisibility(buildDir, test.fs)
@@ -759,6 +751,3 @@
 	InitDefaultsModule(m)
 	return m
 }
-
-func (*mockDefaults) GenerateAndroidBuildActions(ctx ModuleContext) {
-}
diff --git a/android/vts_config_test.go b/android/vts_config_test.go
index 7d4c9b1..142b2f5 100644
--- a/android/vts_config_test.go
+++ b/android/vts_config_test.go
@@ -15,19 +15,11 @@
 package android
 
 import (
-	"io/ioutil"
-	"os"
 	"testing"
 )
 
 func testVtsConfig(test *testing.T, bpFileContents string) *TestContext {
-	buildDir, err := ioutil.TempDir("", "soong_vts_config_test")
-	if err != nil {
-		test.Fatal(err)
-	}
-
 	config := TestArchConfig(buildDir, nil)
-	defer func() { os.RemoveAll(buildDir) }()
 
 	ctx := NewTestArchContext()
 	ctx.RegisterModuleType("vts_config", ModuleFactoryAdaptor(VtsConfigFactory))
diff --git a/apex/apex.go b/apex/apex.go
index 41a21c9..84e5497 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -61,7 +61,7 @@
 			`--key ${key} ${opt_flags} ${image_dir} ${out} `,
 		CommandDeps: []string{"${apexer}", "${avbtool}", "${e2fsdroid}", "${merge_zips}",
 			"${mke2fs}", "${resize2fs}", "${sefcontext_compile}",
-			"${soong_zip}", "${zipalign}", "${aapt2}"},
+			"${soong_zip}", "${zipalign}", "${aapt2}", "prebuilts/sdk/current/public/android.jar"},
 		Description: "APEX ${image_dir} => ${out}",
 	}, "tool_path", "image_dir", "copy_commands", "manifest", "file_contexts", "canned_fs_config", "key", "opt_flags")
 
@@ -1062,6 +1062,10 @@
 		Description: "signapk",
 		Output:      a.outputFiles[apexType],
 		Input:       unsignedOutputFile,
+		Implicits: []android.Path{
+			a.container_certificate_file,
+			a.container_private_key_file,
+		},
 		Args: map[string]string{
 			"certificates": a.container_certificate_file.String() + " " + a.container_private_key_file.String(),
 			"flags":        "-a 4096", //alignment
@@ -1295,9 +1299,6 @@
 	android.DefaultsModuleBase
 }
 
-func (*Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-}
-
 func defaultsFactory() android.Module {
 	return DefaultsFactory()
 }
diff --git a/cc/binary.go b/cc/binary.go
index 941f131..1757f1c 100644
--- a/cc/binary.go
+++ b/cc/binary.go
@@ -106,13 +106,17 @@
 
 }
 
-func (binary *binaryDecorator) getStem(ctx BaseModuleContext) string {
+func (binary *binaryDecorator) getStemWithoutSuffix(ctx BaseModuleContext) string {
 	stem := ctx.baseModuleName()
 	if String(binary.Properties.Stem) != "" {
 		stem = String(binary.Properties.Stem)
 	}
 
-	return stem + String(binary.Properties.Suffix)
+	return stem
+}
+
+func (binary *binaryDecorator) getStem(ctx BaseModuleContext) string {
+	return binary.getStemWithoutSuffix(ctx) + String(binary.Properties.Suffix)
 }
 
 func (binary *binaryDecorator) linkerDeps(ctx DepsContext, deps Deps) Deps {
@@ -388,7 +392,7 @@
 
 	objs.coverageFiles = append(objs.coverageFiles, deps.StaticLibObjs.coverageFiles...)
 	objs.coverageFiles = append(objs.coverageFiles, deps.WholeStaticLibObjs.coverageFiles...)
-	binary.coverageOutputFile = TransformCoverageFilesToLib(ctx, objs, builderFlags, binary.getStem(ctx))
+	binary.coverageOutputFile = TransformCoverageFilesToZip(ctx, objs, binary.getStem(ctx))
 
 	// Need to determine symlinks early since some targets (ie APEX) need this
 	// information but will not call 'install'
@@ -398,11 +402,11 @@
 	}
 
 	if Bool(binary.Properties.Symlink_preferred_arch) {
-		if String(binary.Properties.Stem) == "" && String(binary.Properties.Suffix) == "" {
-			ctx.PropertyErrorf("symlink_preferred_arch", "must also specify stem or suffix")
+		if String(binary.Properties.Suffix) == "" {
+			ctx.PropertyErrorf("symlink_preferred_arch", "must also specify suffix")
 		}
 		if ctx.TargetPrimary() {
-			binary.symlinks = append(binary.symlinks, ctx.baseModuleName())
+			binary.symlinks = append(binary.symlinks, binary.getStemWithoutSuffix(ctx))
 		}
 	}
 
diff --git a/cc/builder.go b/cc/builder.go
index 7cf5c29..1e12361 100644
--- a/cc/builder.go
+++ b/cc/builder.go
@@ -22,7 +22,6 @@
 	"fmt"
 	"path/filepath"
 	"runtime"
-	"strconv"
 	"strings"
 
 	"github.com/google/blueprint"
@@ -93,20 +92,6 @@
 		},
 		"arCmd", "arFlags")
 
-	darwinAr = pctx.AndroidStaticRule("darwinAr",
-		blueprint.RuleParams{
-			Command:     "rm -f ${out} && ${config.MacArPath} $arFlags $out $in",
-			CommandDeps: []string{"${config.MacArPath}"},
-		},
-		"arFlags")
-
-	darwinAppendAr = pctx.AndroidStaticRule("darwinAppendAr",
-		blueprint.RuleParams{
-			Command:     "cp -f ${inAr} ${out}.tmp && ${config.MacArPath} $arFlags ${out}.tmp $in && mv ${out}.tmp ${out}",
-			CommandDeps: []string{"${config.MacArPath}", "${inAr}"},
-		},
-		"arFlags", "inAr")
-
 	darwinStrip = pctx.AndroidStaticRule("darwinStrip",
 		blueprint.RuleParams{
 			Command:     "${config.MacStripPath} -u -r -o $out $in",
@@ -228,6 +213,14 @@
 		blueprint.RuleParams{
 			Command: "gunzip -c $in > $out",
 		})
+
+	zip = pctx.AndroidStaticRule("zip",
+		blueprint.RuleParams{
+			Command:        "cat $out.rsp | tr ' ' '\\n' | tr -d \\' | sort -u > ${out}.tmp && ${SoongZipCmd} -o ${out} -C $$OUT_DIR -l ${out}.tmp",
+			CommandDeps:    []string{"${SoongZipCmd}"},
+			Rspfile:        "$out.rsp",
+			RspfileContent: "$in",
+		})
 )
 
 func init() {
@@ -240,6 +233,8 @@
 		// Darwin doesn't have /proc
 		pctx.StaticVariable("relPwd", "")
 	}
+
+	pctx.HostBinToolVariable("SoongZipCmd", "soong_zip")
 }
 
 type builderFlags struct {
@@ -505,11 +500,6 @@
 func TransformObjToStaticLib(ctx android.ModuleContext, objFiles android.Paths,
 	flags builderFlags, outputFile android.ModuleOutPath, deps android.Paths) {
 
-	if ctx.Darwin() {
-		transformDarwinObjToStaticLib(ctx, objFiles, flags, outputFile, deps)
-		return
-	}
-
 	arCmd := "${config.ClangBin}/llvm-ar"
 	arFlags := "crsD"
 	if !ctx.Darwin() {
@@ -532,82 +522,6 @@
 	})
 }
 
-// Generate a rule for compiling multiple .o files to a static library (.a) on
-// darwin.  The darwin ar tool doesn't support @file for list files, and has a
-// very small command line length limit, so we have to split the ar into multiple
-// steps, each appending to the previous one.
-func transformDarwinObjToStaticLib(ctx android.ModuleContext, objFiles android.Paths,
-	flags builderFlags, outputFile android.ModuleOutPath, deps android.Paths) {
-
-	arFlags := "cqs"
-
-	if len(objFiles) == 0 {
-		dummy := android.PathForModuleOut(ctx, "dummy"+objectExtension)
-		dummyAr := android.PathForModuleOut(ctx, "dummy"+staticLibraryExtension)
-
-		ctx.Build(pctx, android.BuildParams{
-			Rule:        emptyFile,
-			Description: "empty object file",
-			Output:      dummy,
-			Implicits:   deps,
-		})
-
-		ctx.Build(pctx, android.BuildParams{
-			Rule:        darwinAr,
-			Description: "empty static archive",
-			Output:      dummyAr,
-			Input:       dummy,
-			Args: map[string]string{
-				"arFlags": arFlags,
-			},
-		})
-
-		ctx.Build(pctx, android.BuildParams{
-			Rule:        darwinAppendAr,
-			Description: "static link " + outputFile.Base(),
-			Output:      outputFile,
-			Input:       dummy,
-			Args: map[string]string{
-				"arFlags": "d",
-				"inAr":    dummyAr.String(),
-			},
-		})
-
-		return
-	}
-
-	// ARG_MAX on darwin is 262144, use half that to be safe
-	objFilesLists, err := splitListForSize(objFiles, 131072)
-	if err != nil {
-		ctx.ModuleErrorf("%s", err.Error())
-	}
-
-	var in, out android.WritablePath
-	for i, l := range objFilesLists {
-		in = out
-		out = outputFile
-		if i != len(objFilesLists)-1 {
-			out = android.PathForModuleOut(ctx, outputFile.Base()+strconv.Itoa(i))
-		}
-
-		build := android.BuildParams{
-			Rule:        darwinAr,
-			Description: "static link " + out.Base(),
-			Output:      out,
-			Inputs:      l,
-			Implicits:   deps,
-			Args: map[string]string{
-				"arFlags": arFlags,
-			},
-		}
-		if i != 0 {
-			build.Rule = darwinAppendAr
-			build.Args["inAr"] = in.String()
-		}
-		ctx.Build(pctx, build)
-	}
-}
-
 // Generate a rule for compiling multiple .o files, plus static libraries, whole static libraries,
 // and shared libraries, to a shared library (.so) or dynamic executable
 func TransformObjToDynamicBinary(ctx android.ModuleContext,
@@ -883,13 +797,18 @@
 	})
 }
 
-func TransformCoverageFilesToLib(ctx android.ModuleContext,
-	inputs Objects, flags builderFlags, baseName string) android.OptionalPath {
+func TransformCoverageFilesToZip(ctx android.ModuleContext,
+	inputs Objects, baseName string) android.OptionalPath {
 
 	if len(inputs.coverageFiles) > 0 {
-		outputFile := android.PathForModuleOut(ctx, baseName+".gcnodir")
+		outputFile := android.PathForModuleOut(ctx, baseName+".zip")
 
-		TransformObjToStaticLib(ctx, inputs.coverageFiles, flags, outputFile, nil)
+		ctx.Build(pctx, android.BuildParams{
+			Rule:        zip,
+			Description: "zip " + outputFile.Base(),
+			Inputs:      inputs.coverageFiles,
+			Output:      outputFile,
+		})
 
 		return android.OptionalPathForPath(outputFile)
 	}
diff --git a/cc/cc.go b/cc/cc.go
index 26d3d98..53ec899 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -2060,9 +2060,6 @@
 	android.ApexModuleBase
 }
 
-func (*Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-}
-
 // cc_defaults provides a set of properties that can be inherited by other cc
 // modules. A module can use the properties from a cc_defaults using
 // `defaults: ["<:default_module_name>"]`. Properties of both modules are
diff --git a/cc/gen.go b/cc/gen.go
index 57eb929..1d30dab 100644
--- a/cc/gen.go
+++ b/cc/gen.go
@@ -16,6 +16,7 @@
 
 import (
 	"path/filepath"
+	"strings"
 
 	"github.com/google/blueprint"
 
@@ -36,15 +37,6 @@
 			CommandDeps: []string{"$lexCmd"},
 		})
 
-	aidl = pctx.AndroidStaticRule("aidl",
-		blueprint.RuleParams{
-			Command:     "$aidlCmd -d${out}.d --ninja $aidlFlags $in $outDir $out",
-			CommandDeps: []string{"$aidlCmd"},
-			Depfile:     "${out}.d",
-			Deps:        blueprint.DepsGCC,
-		},
-		"aidlFlags", "outDir")
-
 	sysprop = pctx.AndroidStaticRule("sysprop",
 		blueprint.RuleParams{
 			Command: "$syspropCmd --header-dir=$headerOutDir --public-header-dir=$publicOutDir " +
@@ -114,20 +106,37 @@
 	return ret
 }
 
-func genAidl(ctx android.ModuleContext, aidlFile android.Path, outFile android.ModuleGenPath, aidlFlags string) android.Paths {
-	ctx.Build(pctx, android.BuildParams{
-		Rule:        aidl,
-		Description: "aidl " + aidlFile.Rel(),
-		Output:      outFile,
-		Input:       aidlFile,
-		Args: map[string]string{
-			"aidlFlags": aidlFlags,
-			"outDir":    android.PathForModuleGen(ctx, "aidl").String(),
-		},
-	})
+func genAidl(ctx android.ModuleContext, rule *android.RuleBuilder, aidlFile android.Path,
+	outFile, depFile android.ModuleGenPath, aidlFlags string) android.Paths {
 
-	// TODO: This should return the generated headers, not the source file.
-	return android.Paths{outFile}
+	aidlPackage := strings.TrimSuffix(aidlFile.Rel(), aidlFile.Base())
+	baseName := strings.TrimSuffix(aidlFile.Base(), aidlFile.Ext())
+	shortName := strings.TrimPrefix(baseName, "I")
+
+	outDir := android.PathForModuleGen(ctx, "aidl")
+	headerI := outDir.Join(ctx, aidlPackage, baseName+".h")
+	headerBn := outDir.Join(ctx, aidlPackage, "Bn"+shortName+".h")
+	headerBp := outDir.Join(ctx, aidlPackage, "Bp"+shortName+".h")
+
+	cmd := rule.Command()
+	cmd.Tool(ctx.Config().HostToolPath(ctx, "aidl-cpp")).
+		FlagWithDepFile("-d", depFile).
+		Flag("--ninja").
+		Flag(aidlFlags).
+		Input(aidlFile).
+		OutputDir().
+		Output(outFile).
+		ImplicitOutputs(android.WritablePaths{
+			headerI,
+			headerBn,
+			headerBp,
+		})
+
+	return android.Paths{
+		headerI,
+		headerBn,
+		headerBp,
+	}
 }
 
 func genLex(ctx android.ModuleContext, lexFile android.Path, outFile android.ModuleGenPath) {
@@ -187,6 +196,8 @@
 	var deps android.Paths
 	var rsFiles android.Paths
 
+	var aidlRule *android.RuleBuilder
+
 	var yaccRule_ *android.RuleBuilder
 	yaccRule := func() *android.RuleBuilder {
 		if yaccRule_ == nil {
@@ -218,9 +229,13 @@
 			srcFiles[i] = ccFile
 			deps = append(deps, headerFile)
 		case ".aidl":
+			if aidlRule == nil {
+				aidlRule = android.NewRuleBuilder().Sbox(android.PathForModuleGen(ctx, "aidl"))
+			}
 			cppFile := android.GenPathWithExt(ctx, "aidl", srcFile, "cpp")
+			depFile := android.GenPathWithExt(ctx, "aidl", srcFile, "cpp.d")
 			srcFiles[i] = cppFile
-			deps = append(deps, genAidl(ctx, srcFile, cppFile, buildFlags.aidlFlags)...)
+			deps = append(deps, genAidl(ctx, aidlRule, srcFile, cppFile, depFile, buildFlags.aidlFlags)...)
 		case ".rs", ".fs":
 			cppFile := rsGeneratedCppFile(ctx, srcFile)
 			rsFiles = append(rsFiles, srcFiles[i])
@@ -236,6 +251,10 @@
 		}
 	}
 
+	if aidlRule != nil {
+		aidlRule.Build(pctx, ctx, "aidl", "gen aidl")
+	}
+
 	if yaccRule_ != nil {
 		yaccRule_.Build(pctx, ctx, "yacc", "gen yacc")
 	}
diff --git a/cc/gen_test.go b/cc/gen_test.go
index a0f7308..e4219d9 100644
--- a/cc/gen_test.go
+++ b/cc/gen_test.go
@@ -15,6 +15,7 @@
 package cc
 
 import (
+	"path/filepath"
 	"testing"
 )
 
@@ -32,7 +33,7 @@
 		aidl := ctx.ModuleForTests("libfoo", "android_arm_armv7-a-neon_core_shared").Rule("aidl")
 		libfoo := ctx.ModuleForTests("libfoo", "android_arm_armv7-a-neon_core_shared").Module().(*Module)
 
-		if !inList("-I"+aidl.Args["outDir"], libfoo.flags.GlobalFlags) {
+		if !inList("-I"+filepath.Dir(aidl.Output.String()), libfoo.flags.GlobalFlags) {
 			t.Errorf("missing aidl includes in global flags")
 		}
 	})
@@ -55,7 +56,7 @@
 		aidl := ctx.ModuleForTests("libfoo", "android_arm_armv7-a-neon_core_shared").Rule("aidl")
 		libfoo := ctx.ModuleForTests("libfoo", "android_arm_armv7-a-neon_core_shared").Module().(*Module)
 
-		if !inList("-I"+aidl.Args["outDir"], libfoo.flags.GlobalFlags) {
+		if !inList("-I"+filepath.Dir(aidl.Output.String()), libfoo.flags.GlobalFlags) {
 			t.Errorf("missing aidl includes in global flags")
 		}
 	})
diff --git a/cc/genrule.go b/cc/genrule.go
index decf6ea..e594f4b 100644
--- a/cc/genrule.go
+++ b/cc/genrule.go
@@ -42,5 +42,7 @@
 
 	android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibBoth)
 
+	android.InitApexModule(module)
+
 	return module
 }
diff --git a/cc/library.go b/cc/library.go
index be5661c..f98cd36 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -651,7 +651,7 @@
 
 	TransformObjToStaticLib(ctx, library.objects.objFiles, builderFlags, outputFile, objs.tidyFiles)
 
-	library.coverageOutputFile = TransformCoverageFilesToLib(ctx, library.objects, builderFlags,
+	library.coverageOutputFile = TransformCoverageFilesToZip(ctx, library.objects,
 		ctx.ModuleName()+library.MutatedProperties.VariantName)
 
 	library.wholeStaticMissingDeps = ctx.GetMissingDependencies()
@@ -771,7 +771,7 @@
 	objs.sAbiDumpFiles = append(objs.sAbiDumpFiles, deps.StaticLibObjs.sAbiDumpFiles...)
 	objs.sAbiDumpFiles = append(objs.sAbiDumpFiles, deps.WholeStaticLibObjs.sAbiDumpFiles...)
 
-	library.coverageOutputFile = TransformCoverageFilesToLib(ctx, objs, builderFlags, library.getLibName(ctx))
+	library.coverageOutputFile = TransformCoverageFilesToZip(ctx, objs, library.getLibName(ctx))
 	library.linkSAbiDumpFiles(ctx, objs, fileName, ret)
 
 	return ret
diff --git a/cc/pgo.go b/cc/pgo.go
index 7334ea2..4e915ff 100644
--- a/cc/pgo.go
+++ b/cc/pgo.go
@@ -27,10 +27,9 @@
 
 var (
 	// Add flags to ignore warnings that profiles are old or missing for
-	// some functions, and turn on the experimental new pass manager.
+	// some functions.
 	profileUseOtherFlags = []string{
 		"-Wno-backend-plugin",
-		"-fexperimental-new-pass-manager",
 	}
 
 	globalPgoProfileProjects = []string{
diff --git a/cc/rs.go b/cc/rs.go
index 5421b92..fbc6bfb 100644
--- a/cc/rs.go
+++ b/cc/rs.go
@@ -72,11 +72,12 @@
 	stampFile := android.PathForModuleGen(ctx, "rs", "rs.stamp")
 	depFiles := make(android.WritablePaths, 0, len(rsFiles))
 	genFiles := make(android.WritablePaths, 0, 2*len(rsFiles))
+	headers := make(android.Paths, 0, len(rsFiles))
 	for _, rsFile := range rsFiles {
 		depFiles = append(depFiles, rsGeneratedDepFile(ctx, rsFile))
-		genFiles = append(genFiles,
-			rsGeneratedCppFile(ctx, rsFile),
-			rsGeneratedHFile(ctx, rsFile))
+		headerFile := rsGeneratedHFile(ctx, rsFile)
+		genFiles = append(genFiles, rsGeneratedCppFile(ctx, rsFile), headerFile)
+		headers = append(headers, headerFile)
 	}
 
 	ctx.Build(pctx, android.BuildParams{
@@ -92,7 +93,7 @@
 		},
 	})
 
-	return android.Paths{stampFile}
+	return headers
 }
 
 func rsFlags(ctx ModuleContext, flags Flags, properties *BaseCompilerProperties) Flags {
diff --git a/cc/sanitize.go b/cc/sanitize.go
index fdda7be..0af0659 100644
--- a/cc/sanitize.go
+++ b/cc/sanitize.go
@@ -40,7 +40,8 @@
 	hwasanCflags = []string{"-fno-omit-frame-pointer", "-Wno-frame-larger-than=",
 		"-mllvm", "-hwasan-create-frame-descriptions=0",
 		"-mllvm", "-hwasan-allow-ifunc",
-		"-fsanitize-hwaddress-abi=platform"}
+		"-fsanitize-hwaddress-abi=platform",
+		"-fno-experimental-new-pass-manager"}
 
 	cfiCflags = []string{"-flto", "-fsanitize-cfi-cross-dso",
 		"-fsanitize-blacklist=external/compiler-rt/lib/cfi/cfi_blacklist.txt"}
diff --git a/cc/test.go b/cc/test.go
index dae2a37..c735fd9 100644
--- a/cc/test.go
+++ b/cc/test.go
@@ -64,6 +64,10 @@
 
 	// Test options.
 	Test_options TestOptions
+
+	// Add RootTargetPreparer to auto generated test config. This guarantees the test to run
+	// with root permission.
+	Require_root *bool
 }
 
 func init() {
@@ -273,18 +277,19 @@
 
 func (test *testBinary) install(ctx ModuleContext, file android.Path) {
 	test.data = android.PathsForModuleSrc(ctx, test.Properties.Data)
-	optionsMap := map[string]string{}
-	if Bool(test.testDecorator.Properties.Isolated) {
-		optionsMap["not-shardable"] = "true"
+	var configs []tradefed.Config
+	if Bool(test.Properties.Require_root) {
+		configs = append(configs, tradefed.Preparer{"com.android.tradefed.targetprep.RootTargetPreparer"})
 	}
-
+	if Bool(test.testDecorator.Properties.Isolated) {
+		configs = append(configs, tradefed.Option{"not-shardable", "true"})
+	}
 	if test.Properties.Test_options.Run_test_as != nil {
-		optionsMap["run-test-as"] = String(test.Properties.Test_options.Run_test_as)
+		configs = append(configs, tradefed.Option{"run-test-as", String(test.Properties.Test_options.Run_test_as)})
 	}
 
 	test.testConfig = tradefed.AutoGenNativeTestConfig(ctx, test.Properties.Test_config,
-		test.Properties.Test_config_template,
-		test.Properties.Test_suites, optionsMap)
+		test.Properties.Test_config_template, test.Properties.Test_suites, configs)
 
 	test.binaryDecorator.baseInstaller.dir = "nativetest"
 	test.binaryDecorator.baseInstaller.dir64 = "nativetest64"
@@ -371,6 +376,10 @@
 	// the name of the test configuration template (for example "AndroidTestTemplate.xml") that
 	// should be installed with the module.
 	Test_config_template *string `android:"path,arch_variant"`
+
+	// Add RootTargetPreparer to auto generated test config. This guarantees the test to run
+	// with root permission.
+	Require_root *bool
 }
 
 type benchmarkDecorator struct {
@@ -403,8 +412,12 @@
 
 func (benchmark *benchmarkDecorator) install(ctx ModuleContext, file android.Path) {
 	benchmark.data = android.PathsForModuleSrc(ctx, benchmark.Properties.Data)
+	var configs []tradefed.Config
+	if Bool(benchmark.Properties.Require_root) {
+		configs = append(configs, tradefed.Preparer{"com.android.tradefed.targetprep.RootTargetPreparer"})
+	}
 	benchmark.testConfig = tradefed.AutoGenNativeBenchmarkTestConfig(ctx, benchmark.Properties.Test_config,
-		benchmark.Properties.Test_config_template, benchmark.Properties.Test_suites)
+		benchmark.Properties.Test_config_template, benchmark.Properties.Test_suites, configs)
 
 	benchmark.binaryDecorator.baseInstaller.dir = filepath.Join("benchmarktest", ctx.ModuleName())
 	benchmark.binaryDecorator.baseInstaller.dir64 = filepath.Join("benchmarktest64", ctx.ModuleName())
diff --git a/cmd/multiproduct_kati/main.go b/cmd/multiproduct_kati/main.go
index 330c5dd..1171a65 100644
--- a/cmd/multiproduct_kati/main.go
+++ b/cmd/multiproduct_kati/main.go
@@ -156,10 +156,12 @@
 }
 
 func main() {
-	writer := terminal.NewWriter(terminal.StdioImpl{})
-	defer writer.Finish()
+	stdio := terminal.StdioImpl{}
 
-	log := logger.New(writer)
+	output := terminal.NewStatusOutput(stdio.Stdout(), "",
+		build.OsEnvironment().IsEnvTrue("ANDROID_QUIET_BUILD"))
+
+	log := logger.New(output)
 	defer log.Cleanup()
 
 	flag.Parse()
@@ -172,8 +174,7 @@
 
 	stat := &status.Status{}
 	defer stat.Finish()
-	stat.AddOutput(terminal.NewStatusOutput(writer, "",
-		build.OsEnvironment().IsEnvTrue("ANDROID_QUIET_BUILD")))
+	stat.AddOutput(output)
 
 	var failures failureCount
 	stat.AddOutput(&failures)
@@ -188,7 +189,7 @@
 		Context: ctx,
 		Logger:  log,
 		Tracer:  trace,
-		Writer:  writer,
+		Writer:  output,
 		Status:  stat,
 	}}
 
@@ -341,7 +342,7 @@
 	} else if failures > 1 {
 		log.Fatalf("%d failures", failures)
 	} else {
-		writer.Print("Success")
+		fmt.Fprintln(output, "Success")
 	}
 }
 
@@ -386,7 +387,7 @@
 		Context: mpctx.Context,
 		Logger:  log,
 		Tracer:  mpctx.Tracer,
-		Writer:  terminal.NewWriter(terminal.NewCustomStdio(nil, f, f)),
+		Writer:  f,
 		Thread:  mpctx.Tracer.NewThread(product),
 		Status:  &status.Status{},
 	}}
@@ -466,3 +467,8 @@
 }
 
 func (f *failureCount) Flush() {}
+
+func (f *failureCount) Write(p []byte) (int, error) {
+	// discard writes
+	return len(p), nil
+}
diff --git a/cmd/soong_ui/main.go b/cmd/soong_ui/main.go
index 5f9bd01..f5276c3 100644
--- a/cmd/soong_ui/main.go
+++ b/cmd/soong_ui/main.go
@@ -109,10 +109,10 @@
 		os.Exit(1)
 	}
 
-	writer := terminal.NewWriter(c.stdio())
-	defer writer.Finish()
+	output := terminal.NewStatusOutput(c.stdio().Stdout(), os.Getenv("NINJA_STATUS"),
+		build.OsEnvironment().IsEnvTrue("ANDROID_QUIET_BUILD"))
 
-	log := logger.New(writer)
+	log := logger.New(output)
 	defer log.Cleanup()
 
 	ctx, cancel := context.WithCancel(context.Background())
@@ -125,8 +125,7 @@
 
 	stat := &status.Status{}
 	defer stat.Finish()
-	stat.AddOutput(terminal.NewStatusOutput(writer, os.Getenv("NINJA_STATUS"),
-		build.OsEnvironment().IsEnvTrue("ANDROID_QUIET_BUILD")))
+	stat.AddOutput(output)
 	stat.AddOutput(trace.StatusTracer())
 
 	build.SetupSignals(log, cancel, func() {
@@ -140,7 +139,7 @@
 		Logger:  log,
 		Metrics: met,
 		Tracer:  trace,
-		Writer:  writer,
+		Writer:  output,
 		Status:  stat,
 	}}
 
@@ -312,13 +311,13 @@
 func make(ctx build.Context, config build.Config, _ []string, logsDir string) {
 	if config.IsVerbose() {
 		writer := ctx.Writer
-		writer.Print("! The argument `showcommands` is no longer supported.")
-		writer.Print("! Instead, the verbose log is always written to a compressed file in the output dir:")
-		writer.Print("!")
-		writer.Print(fmt.Sprintf("!   gzip -cd %s/verbose.log.gz | less -R", logsDir))
-		writer.Print("!")
-		writer.Print("! Older versions are saved in verbose.log.#.gz files")
-		writer.Print("")
+		fmt.Fprintln(writer, "! The argument `showcommands` is no longer supported.")
+		fmt.Fprintln(writer, "! Instead, the verbose log is always written to a compressed file in the output dir:")
+		fmt.Fprintln(writer, "!")
+		fmt.Fprintf(writer, "!   gzip -cd %s/verbose.log.gz | less -R\n", logsDir)
+		fmt.Fprintln(writer, "!")
+		fmt.Fprintln(writer, "! Older versions are saved in verbose.log.#.gz files")
+		fmt.Fprintln(writer, "")
 		time.Sleep(5 * time.Second)
 	}
 
diff --git a/genrule/genrule.go b/genrule/genrule.go
index 87e6747..b0657ff 100644
--- a/genrule/genrule.go
+++ b/genrule/genrule.go
@@ -101,6 +101,7 @@
 type Module struct {
 	android.ModuleBase
 	android.DefaultableModuleBase
+	android.ApexModuleBase
 
 	// For other packages to make their own genrules with extra
 	// properties
@@ -582,9 +583,6 @@
 	android.DefaultsModuleBase
 }
 
-func (*Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-}
-
 func defaultsFactory() android.Module {
 	return DefaultsFactory()
 }
diff --git a/java/aar.go b/java/aar.go
index 1e8e6d8..adea87f 100644
--- a/java/aar.go
+++ b/java/aar.go
@@ -188,8 +188,7 @@
 	return linkFlags, linkDeps, resDirs, overlayDirs, rroDirs, resourceZips
 }
 
-func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkContext sdkContext) {
-	sdkDep := decodeSdkDep(ctx, sdkContext)
+func (a *aapt) deps(ctx android.BottomUpMutatorContext, sdkDep sdkDep) {
 	if sdkDep.frameworkResModule != "" {
 		ctx.AddVariationDependencies(nil, frameworkResTag, sdkDep.frameworkResModule)
 	}
@@ -401,8 +400,9 @@
 
 func (a *AndroidLibrary) DepsMutator(ctx android.BottomUpMutatorContext) {
 	a.Module.deps(ctx)
-	if !Bool(a.properties.No_framework_libs) && !Bool(a.properties.No_standard_libs) {
-		a.aapt.deps(ctx, sdkContext(a))
+	sdkDep := decodeSdkDep(ctx, sdkContext(a))
+	if sdkDep.hasFrameworkLibs() {
+		a.aapt.deps(ctx, sdkDep)
 	}
 }
 
@@ -513,6 +513,14 @@
 	return a.sdkVersion()
 }
 
+func (a *AARImport) noFrameworkLibs() bool {
+	return false
+}
+
+func (a *AARImport) noStandardLibs() bool {
+	return false
+}
+
 var _ AndroidLibraryDependency = (*AARImport)(nil)
 
 func (a *AARImport) ExportPackage() android.Path {
diff --git a/java/app.go b/java/app.go
index cf9354f..cab97de 100644
--- a/java/app.go
+++ b/java/app.go
@@ -159,8 +159,9 @@
 		ctx.PropertyErrorf("stl", "sdk_version must be set in order to use c++_shared")
 	}
 
-	if !Bool(a.properties.No_framework_libs) && !Bool(a.properties.No_standard_libs) {
-		a.aapt.deps(ctx, sdkContext(a))
+	sdkDep := decodeSdkDep(ctx, sdkContext(a))
+	if sdkDep.hasFrameworkLibs() {
+		a.aapt.deps(ctx, sdkDep)
 	}
 
 	embedJni := a.shouldEmbedJnis(ctx)
@@ -180,7 +181,7 @@
 		}
 	}
 
-	a.usesLibrary.deps(ctx, Bool(a.properties.No_framework_libs))
+	a.usesLibrary.deps(ctx, sdkDep.hasFrameworkLibs())
 }
 
 func (a *AndroidApp) OverridablePropertiesDepsMutator(ctx android.BottomUpMutatorContext) {
@@ -783,7 +784,7 @@
 		ctx.AddDependency(ctx.Module(), certificateTag, cert)
 	}
 
-	a.usesLibrary.deps(ctx, false)
+	a.usesLibrary.deps(ctx, true)
 }
 
 func (a *AndroidAppImport) uncompressEmbeddedJniLibs(
@@ -937,17 +938,22 @@
 	usesLibraryProperties UsesLibraryProperties
 }
 
-func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, noFrameworkLibs bool) {
-	ctx.AddVariationDependencies(nil, usesLibTag, u.usesLibraryProperties.Uses_libs...)
-	ctx.AddVariationDependencies(nil, usesLibTag, u.presentOptionalUsesLibs(ctx)...)
-	if !noFrameworkLibs {
-		// dexpreopt/dexpreopt.go needs the paths to the dex jars of these libraries in case construct_context.sh needs
-		// to pass them to dex2oat.  Add them as a dependency so we can determine the path to the dex jar of each
-		// library to dexpreopt.
-		ctx.AddVariationDependencies(nil, usesLibTag,
-			"org.apache.http.legacy",
-			"android.hidl.base-V1.0-java",
-			"android.hidl.manager-V1.0-java")
+func (u *usesLibrary) deps(ctx android.BottomUpMutatorContext, hasFrameworkLibs bool) {
+	if !ctx.Config().UnbundledBuild() {
+		ctx.AddVariationDependencies(nil, usesLibTag, u.usesLibraryProperties.Uses_libs...)
+		ctx.AddVariationDependencies(nil, usesLibTag, u.presentOptionalUsesLibs(ctx)...)
+		// Only add these extra dependencies if the module depends on framework libs. This avoids
+		// creating a cyclic dependency:
+		//     e.g. framework-res -> org.apache.http.legacy -> ... -> framework-res.
+		if hasFrameworkLibs {
+			// dexpreopt/dexpreopt.go needs the paths to the dex jars of these libraries in case construct_context.sh needs
+			// to pass them to dex2oat.  Add them as a dependency so we can determine the path to the dex jar of each
+			// library to dexpreopt.
+			ctx.AddVariationDependencies(nil, usesLibTag,
+				"org.apache.http.legacy",
+				"android.hidl.base-V1.0-java",
+				"android.hidl.manager-V1.0-java")
+		}
 	}
 }
 
diff --git a/java/app_builder.go b/java/app_builder.go
index fa77bbf..348c8b4 100644
--- a/java/app_builder.go
+++ b/java/app_builder.go
@@ -31,7 +31,7 @@
 var (
 	Signapk = pctx.AndroidStaticRule("signapk",
 		blueprint.RuleParams{
-			Command: `${config.JavaCmd} -Djava.library.path=$$(dirname $signapkJniLibrary) ` +
+			Command: `${config.JavaCmd} ${config.JavaVmFlags} -Djava.library.path=$$(dirname $signapkJniLibrary) ` +
 				`-jar $signapkCmd $flags $certificates $in $out`,
 			CommandDeps: []string{"$signapkCmd", "$signapkJniLibrary"},
 		},
diff --git a/java/builder.go b/java/builder.go
index d257d1d..e1a912b 100644
--- a/java/builder.go
+++ b/java/builder.go
@@ -43,7 +43,8 @@
 			Command: `rm -rf "$outDir" "$annoDir" "$srcJarDir" && mkdir -p "$outDir" "$annoDir" "$srcJarDir" && ` +
 				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
 				`(if [ -s $srcJarDir/list ] || [ -s $out.rsp ] ; then ` +
-				`${config.SoongJavacWrapper} ${config.JavacWrapper}${config.JavacCmd} ${config.JavacHeapFlags} ${config.CommonJdkFlags} ` +
+				`${config.SoongJavacWrapper} ${config.JavacWrapper}${config.JavacCmd} ` +
+				`${config.JavacHeapFlags} ${config.JavacVmFlags} ${config.CommonJdkFlags} ` +
 				`$processorpath $processor $javacFlags $bootClasspath $classpath ` +
 				`-source $javaVersion -target $javaVersion ` +
 				`-d $outDir -s $annoDir @$out.rsp @$srcJarDir/list ; fi ) && ` +
@@ -64,7 +65,7 @@
 	turbine = pctx.AndroidStaticRule("turbine",
 		blueprint.RuleParams{
 			Command: `rm -rf "$outDir" && mkdir -p "$outDir" && ` +
-				`${config.JavaCmd} -jar ${config.TurbineJar} --output $out.tmp ` +
+				`${config.JavaCmd} ${config.JavaVmFlags} -jar ${config.TurbineJar} --output $out.tmp ` +
 				`--temp_dir "$outDir" --sources @$out.rsp  --source_jars $srcJars ` +
 				`--javacopts ${config.CommonJdkFlags} ` +
 				`$javacFlags -source $javaVersion -target $javaVersion -- $bootClasspath $classpath && ` +
@@ -108,7 +109,7 @@
 
 	jarjar = pctx.AndroidStaticRule("jarjar",
 		blueprint.RuleParams{
-			Command:     "${config.JavaCmd} -jar ${config.JarjarCmd} process $rulesFile $in $out",
+			Command:     "${config.JavaCmd} ${config.JavaVmFlags} -jar ${config.JarjarCmd} process $rulesFile $in $out",
 			CommandDeps: []string{"${config.JavaCmd}", "${config.JarjarCmd}", "$rulesFile"},
 		},
 		"rulesFile")
@@ -124,7 +125,7 @@
 
 	jetifier = pctx.AndroidStaticRule("jetifier",
 		blueprint.RuleParams{
-			Command:     "${config.JavaCmd} -jar ${config.JetifierJar} -l error -o $out -i $in",
+			Command:     "${config.JavaCmd}  ${config.JavaVmFlags} -jar ${config.JetifierJar} -l error -o $out -i $in",
 			CommandDeps: []string{"${config.JavaCmd}", "${config.JetifierJar}"},
 		},
 	)
diff --git a/java/config/config.go b/java/config/config.go
index f9552d5..6ade649 100644
--- a/java/config/config.go
+++ b/java/config/config.go
@@ -69,6 +69,8 @@
 		// b/65004097: prevent using java.lang.invoke.StringConcatFactory when using -target 1.9
 		`-XDstringConcat=inline`,
 	}, " "))
+	pctx.StaticVariable("JavaVmFlags", "-XX:OnError=\"cat hs_err_pid%p.log\" -XX:CICompilerCount=6 -XX:+UseDynamicNumberOfGCThreads")
+	pctx.StaticVariable("JavacVmFlags", "-J-XX:OnError=\"cat hs_err_pid%p.log\" -J-XX:CICompilerCount=6 -J-XX:+UseDynamicNumberOfGCThreads")
 
 	pctx.VariableConfigMethod("hostPrebuiltTag", android.Config.PrebuiltOS)
 
diff --git a/java/config/kotlin.go b/java/config/kotlin.go
index 7cea042..fd8e3db 100644
--- a/java/config/kotlin.go
+++ b/java/config/kotlin.go
@@ -32,6 +32,7 @@
 	pctx.SourcePathVariable("KotlinScriptRuntimeJar", "external/kotlinc/lib/kotlin-script-runtime.jar")
 	pctx.SourcePathVariable("KotlinTrove4jJar", "external/kotlinc/lib/trove4j.jar")
 	pctx.SourcePathVariable("KotlinKaptJar", "external/kotlinc/lib/kotlin-annotation-processing.jar")
+	pctx.SourcePathVariable("KotlinAnnotationJar", "external/kotlinc/lib/annotations-13.0.jar")
 	pctx.SourcePathVariable("KotlinStdlibJar", KotlinStdlibJar)
 
 	// These flags silence "Illegal reflective access" warnings when running kotlinc in OpenJDK9
diff --git a/java/config/makevars.go b/java/config/makevars.go
index 9c78511..ead298a 100644
--- a/java/config/makevars.go
+++ b/java/config/makevars.go
@@ -39,8 +39,8 @@
 	ctx.Strict("ANDROID_JAVA8_HOME", "prebuilts/jdk/jdk8/${hostPrebuiltTag}")
 	ctx.Strict("ANDROID_JAVA9_HOME", "prebuilts/jdk/jdk9/${hostPrebuiltTag}")
 	ctx.Strict("ANDROID_JAVA_TOOLCHAIN", "${JavaToolchain}")
-	ctx.Strict("JAVA", "${JavaCmd}")
-	ctx.Strict("JAVAC", "${JavacCmd}")
+	ctx.Strict("JAVA", "${JavaCmd} ${JavaVmFlags}")
+	ctx.Strict("JAVAC", "${JavacCmd} ${JavacVmFlags}")
 	ctx.Strict("JAR", "${JarCmd}")
 	ctx.Strict("JAR_ARGS", "${JarArgsCmd}")
 	ctx.Strict("JAVADOC", "${JavadocCmd}")
@@ -58,8 +58,8 @@
 		ctx.Strict("ERROR_PRONE_CHECKS", "${ErrorProneChecks}")
 	}
 
-	ctx.Strict("TARGET_JAVAC", "${JavacCmd} ${CommonJdkFlags}")
-	ctx.Strict("HOST_JAVAC", "${JavacCmd} ${CommonJdkFlags}")
+	ctx.Strict("TARGET_JAVAC", "${JavacCmd}  ${JavacVmFlags} ${CommonJdkFlags}")
+	ctx.Strict("HOST_JAVAC", "${JavacCmd}  ${JavacVmFlags} ${CommonJdkFlags}")
 
 	ctx.Strict("JLINK", "${JlinkCmd}")
 	ctx.Strict("JMOD", "${JmodCmd}")
diff --git a/java/droiddoc.go b/java/droiddoc.go
index 0ec7799..e1476a2 100644
--- a/java/droiddoc.go
+++ b/java/droiddoc.go
@@ -73,7 +73,7 @@
 			Command: `rm -rf "$outDir" "$srcJarDir" "$stubsDir" && ` +
 				`mkdir -p "$outDir" "$srcJarDir" "$stubsDir" && ` +
 				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
-				`${config.JavaCmd} -jar ${config.MetalavaJar} -encoding UTF-8 -source $javaVersion @$out.rsp @$srcJarDir/list ` +
+				`${config.JavaCmd}  ${config.JavaVmFlags} -jar ${config.MetalavaJar} -encoding UTF-8 -source $javaVersion @$out.rsp @$srcJarDir/list ` +
 				`$bootclasspathArgs $classpathArgs $sourcepathArgs --no-banner --color --quiet --format=v2 ` +
 				`$opts && ` +
 				`${config.SoongZipCmd} -write_if_changed -jar -o $out -C $stubsDir -D $stubsDir && ` +
@@ -95,7 +95,7 @@
 		blueprint.RuleParams{
 			Command: `( rm -rf "$srcJarDir" && mkdir -p "$srcJarDir" && ` +
 				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
-				`${config.JavaCmd} -jar ${config.MetalavaJar} -encoding UTF-8 -source $javaVersion @$out.rsp @$srcJarDir/list ` +
+				`${config.JavaCmd}  ${config.JavaVmFlags} -jar ${config.MetalavaJar} -encoding UTF-8 -source $javaVersion @$out.rsp @$srcJarDir/list ` +
 				`$bootclasspathArgs $classpathArgs $sourcepathArgs --no-banner --color --quiet --format=v2 ` +
 				`$opts && touch $out && rm -rf "$srcJarDir") || ` +
 				`( echo -e "$msg" ; exit 38 )`,
@@ -120,7 +120,7 @@
 			Command: `rm -rf "$outDir" "$srcJarDir" "$stubsDir" && ` +
 				`mkdir -p "$outDir" "$srcJarDir" "$stubsDir" && ` +
 				`${config.ZipSyncCmd} -d $srcJarDir -l $srcJarDir/list -f "*.java" $srcJars && ` +
-				`${config.JavaCmd} -jar ${config.DokkaJar} $srcJarDir ` +
+				`${config.JavaCmd} ${config.JavaVmFlags} -jar ${config.DokkaJar} $srcJarDir ` +
 				`$classpathArgs -format dac -dacRoot /reference/kotlin -output $outDir $opts && ` +
 				`${config.SoongZipCmd} -write_if_changed -d -o $docZip -C $outDir -D $outDir && ` +
 				`${config.SoongZipCmd} -write_if_changed -jar -o $out -C $stubsDir -D $stubsDir && ` +
@@ -538,16 +538,24 @@
 	return j.sdkVersion()
 }
 
+func (j *Javadoc) noFrameworkLibs() bool {
+	return Bool(j.properties.No_framework_libs)
+}
+
+func (j *Javadoc) noStandardLibs() bool {
+	return Bool(j.properties.No_standard_libs)
+}
+
 func (j *Javadoc) addDeps(ctx android.BottomUpMutatorContext) {
 	if ctx.Device() {
-		if !Bool(j.properties.No_standard_libs) {
-			sdkDep := decodeSdkDep(ctx, sdkContext(j))
+		sdkDep := decodeSdkDep(ctx, sdkContext(j))
+		if sdkDep.hasStandardLibs() {
 			if sdkDep.useDefaultLibs {
 				ctx.AddVariationDependencies(nil, bootClasspathTag, config.DefaultBootclasspathLibraries...)
 				if ctx.Config().TargetOpenJDK9() {
 					ctx.AddVariationDependencies(nil, systemModulesTag, config.DefaultSystemModules)
 				}
-				if !Bool(j.properties.No_framework_libs) {
+				if sdkDep.hasFrameworkLibs() {
 					ctx.AddVariationDependencies(nil, libTag, config.DefaultLibraries...)
 				}
 			} else if sdkDep.useModule {
@@ -1751,7 +1759,7 @@
 		jdiff := android.PathForOutput(ctx, "host", ctx.Config().PrebuiltOS(), "framework", "jdiff.jar")
 		jdiffImplicits = append(jdiffImplicits, android.Paths{jdiff, d.apiXmlFile, d.lastReleasedApiXmlFile}...)
 
-		opts := " -encoding UTF-8 -source 1.8 -J-Xmx1600m -XDignore.symbol.file " +
+		opts := " -source 1.8 -J-Xmx1600m -XDignore.symbol.file " +
 			"-doclet jdiff.JDiff -docletpath " + jdiff.String() + " -quiet " +
 			"-newapi " + strings.TrimSuffix(d.apiXmlFile.Base(), d.apiXmlFile.Ext()) +
 			" -newapidir " + filepath.Dir(d.apiXmlFile.String()) +
@@ -1808,9 +1816,6 @@
 	android.DefaultsModuleBase
 }
 
-func (*DocDefaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-}
-
 func DocDefaultsFactory() android.Module {
 	module := &DocDefaults{}
 
diff --git a/java/hiddenapi_singleton.go b/java/hiddenapi_singleton.go
index b1ddab4..cf9f492 100644
--- a/java/hiddenapi_singleton.go
+++ b/java/hiddenapi_singleton.go
@@ -15,11 +15,14 @@
 package java
 
 import (
+	"fmt"
+
 	"android/soong/android"
 )
 
 func init() {
 	android.RegisterSingletonType("hiddenapi", hiddenAPISingletonFactory)
+	android.RegisterModuleType("hiddenapi_flags", hiddenAPIFlagsFactory)
 }
 
 type hiddenAPISingletonPathsStruct struct {
@@ -307,3 +310,48 @@
 		Text("fi").
 		Text(")")
 }
+
+type hiddenAPIFlagsProperties struct {
+	// name of the file into which the flags will be copied.
+	Filename *string
+}
+
+type hiddenAPIFlags struct {
+	android.ModuleBase
+
+	properties hiddenAPIFlagsProperties
+
+	outputFilePath android.OutputPath
+}
+
+func (h *hiddenAPIFlags) GenerateAndroidBuildActions(ctx android.ModuleContext) {
+	filename := String(h.properties.Filename)
+
+	inputPath := hiddenAPISingletonPaths(ctx).flags
+	h.outputFilePath = android.PathForModuleOut(ctx, filename).OutputPath
+
+	// This ensures that outputFilePath has the correct name for others to
+	// use, as the source file may have a different name.
+	ctx.Build(pctx, android.BuildParams{
+		Rule:   android.Cp,
+		Output: h.outputFilePath,
+		Input:  inputPath,
+	})
+}
+
+func (h *hiddenAPIFlags) OutputFiles(tag string) (android.Paths, error) {
+	switch tag {
+	case "":
+		return android.Paths{h.outputFilePath}, nil
+	default:
+		return nil, fmt.Errorf("unsupported module reference tag %q", tag)
+	}
+}
+
+// hiddenapi-flags provides access to the hiddenapi-flags.csv file generated during the build.
+func hiddenAPIFlagsFactory() android.Module {
+	module := &hiddenAPIFlags{}
+	module.AddProperties(&module.properties)
+	android.InitAndroidArchModule(module, android.HostAndDeviceSupported, android.MultilibCommon)
+	return module
+}
diff --git a/java/jacoco.go b/java/jacoco.go
index 8b6d4ac..bce9822 100644
--- a/java/jacoco.go
+++ b/java/jacoco.go
@@ -31,7 +31,7 @@
 	jacoco = pctx.AndroidStaticRule("jacoco", blueprint.RuleParams{
 		Command: `rm -rf $tmpDir && mkdir -p $tmpDir && ` +
 			`${config.Zip2ZipCmd} -i $in -o $strippedJar $stripSpec && ` +
-			`${config.JavaCmd} -jar ${config.JacocoCLIJar} ` +
+			`${config.JavaCmd} ${config.JavaVmFlags} -jar ${config.JacocoCLIJar} ` +
 			`  instrument --quiet --dest $tmpDir $strippedJar && ` +
 			`${config.Ziptime} $tmpJar && ` +
 			`${config.MergeZipsCmd} --ignore-duplicates -j $out $tmpJar $in`,
diff --git a/java/java.go b/java/java.go
index fee262d..c42ca28 100644
--- a/java/java.go
+++ b/java/java.go
@@ -440,6 +440,16 @@
 
 	jars android.Paths
 	aidl android.OptionalPath
+
+	noStandardLibs, noFrameworksLibs bool
+}
+
+func (s sdkDep) hasStandardLibs() bool {
+	return !s.noStandardLibs
+}
+
+func (s sdkDep) hasFrameworkLibs() bool {
+	return !s.noStandardLibs && !s.noFrameworksLibs
 }
 
 type jniLib struct {
@@ -476,14 +486,22 @@
 	return j.sdkVersion()
 }
 
+func (j *Module) noFrameworkLibs() bool {
+	return Bool(j.properties.No_framework_libs)
+}
+
+func (j *Module) noStandardLibs() bool {
+	return Bool(j.properties.No_standard_libs)
+}
+
 func (j *Module) deps(ctx android.BottomUpMutatorContext) {
 	if ctx.Device() {
-		if !Bool(j.properties.No_standard_libs) {
-			sdkDep := decodeSdkDep(ctx, sdkContext(j))
+		sdkDep := decodeSdkDep(ctx, sdkContext(j))
+		if sdkDep.hasStandardLibs() {
 			if sdkDep.useDefaultLibs {
 				ctx.AddVariationDependencies(nil, bootClasspathTag, config.DefaultBootclasspathLibraries...)
 				ctx.AddVariationDependencies(nil, systemModulesTag, config.DefaultSystemModules)
-				if !Bool(j.properties.No_framework_libs) {
+				if sdkDep.hasFrameworkLibs() {
 					ctx.AddVariationDependencies(nil, libTag, config.DefaultLibraries...)
 				}
 			} else if sdkDep.useModule {
@@ -664,7 +682,7 @@
 		return javaSdk, true
 	case ver == "current":
 		return javaSdk, false
-	case ver == "":
+	case ver == "" || ver == "none":
 		return javaPlatform, false
 	default:
 		if _, err := strconv.Atoi(ver); err != nil {
@@ -842,7 +860,7 @@
 	var ret string
 	v := sdkContext.sdkVersion()
 	// For PDK builds, use the latest SDK version instead of "current"
-	if ctx.Config().IsPdkBuild() && (v == "" || v == "current") {
+	if ctx.Config().IsPdkBuild() && (v == "" || v == "none" || v == "current") {
 		sdkVersions := ctx.Config().Get(sdkVersionsKey).([]int)
 		latestSdkVersion := 0
 		if len(sdkVersions) > 0 {
@@ -861,7 +879,7 @@
 		ret = "1.7"
 	} else if ctx.Device() && sdk <= 29 || !ctx.Config().TargetOpenJDK9() {
 		ret = "1.8"
-	} else if ctx.Device() && sdkContext.sdkVersion() != "" && sdk == android.FutureApiLevel {
+	} else if ctx.Device() && sdkContext.sdkVersion() != "" && sdkContext.sdkVersion() != "none" && sdk == android.FutureApiLevel {
 		// TODO(ccross): once we generate stubs we should be able to use 1.9 for sdk_version: "current"
 		ret = "1.8"
 	} else {
@@ -913,7 +931,7 @@
 	flags.processor = strings.Join(deps.processorClasses, ",")
 
 	if len(flags.bootClasspath) == 0 && ctx.Host() && flags.javaVersion != "1.9" &&
-		!Bool(j.properties.No_standard_libs) &&
+		decodeSdkDep(ctx, sdkContext(j)).hasStandardLibs() &&
 		inList(flags.javaVersion, []string{"1.6", "1.7", "1.8"}) {
 		// Give host-side tools a version of OpenJDK's standard libraries
 		// close to what they're targeting. As of Dec 2017, AOSP is only
@@ -2131,9 +2149,6 @@
 	android.DefaultsModuleBase
 }
 
-func (*Defaults) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-}
-
 // java_defaults provides a set of properties that can be inherited by other java or android modules.
 //
 // A module can use the properties from a java_defaults module using `defaults: ["defaults_module_name"]`.  Each
diff --git a/java/java_test.go b/java/java_test.go
index 4d161c5..cecc8da 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -212,7 +212,7 @@
 	setDexpreoptTestGlobalConfig(config, dexpreopt.GlobalConfigForTests(pathCtx))
 
 	ctx.Register()
-	_, errs := ctx.ParseFileList(".", []string{"Android.bp", "prebuilts/sdk/Android.bp"})
+	_, errs := ctx.ParseBlueprintsFiles("Android.bp")
 	android.FailIfErrored(t, errs)
 	_, errs = ctx.PrepareBuildActions(config)
 	android.FailIfErrored(t, errs)
@@ -842,6 +842,19 @@
 	}
 }
 
+func TestJavaLibrary(t *testing.T) {
+	config := testConfig(nil)
+	ctx := testContext(config, "", map[string][]byte{
+		"libcore/Android.bp": []byte(`
+				java_library {
+						name: "core",
+						sdk_version: "none",
+						system_modules: "none",
+				}`),
+	})
+	run(t, ctx, config)
+}
+
 func TestJavaSdkLibrary(t *testing.T) {
 	ctx := testJava(t, `
 		droiddoc_template {
diff --git a/java/kotlin.go b/java/kotlin.go
index 33167ba..8306907 100644
--- a/java/kotlin.go
+++ b/java/kotlin.go
@@ -44,6 +44,7 @@
 			"${config.KotlinScriptRuntimeJar}",
 			"${config.KotlinStdlibJar}",
 			"${config.KotlinTrove4jJar}",
+			"${config.KotlinAnnotationJar}",
 			"${config.GenKotlinBuildFileCmd}",
 			"${config.SoongZipCmd}",
 			"${config.ZipSyncCmd}",
diff --git a/java/robolectric.go b/java/robolectric.go
index b87ee0d..1de56a5 100644
--- a/java/robolectric.go
+++ b/java/robolectric.go
@@ -17,6 +17,7 @@
 import (
 	"fmt"
 	"io"
+	"strconv"
 	"strings"
 
 	"android/soong/android"
@@ -40,6 +41,9 @@
 	Test_options struct {
 		// Timeout in seconds when running the tests.
 		Timeout *int64
+
+		// Number of shards to use when running the tests.
+		Shards *int64
 	}
 }
 
@@ -48,7 +52,8 @@
 
 	robolectricProperties robolectricProperties
 
-	libs []string
+	libs  []string
+	tests []string
 }
 
 func (r *robolectricTest) DepsMutator(ctx android.BottomUpMutatorContext) {
@@ -69,6 +74,39 @@
 	for _, dep := range ctx.GetDirectDepsWithTag(libTag) {
 		r.libs = append(r.libs, ctx.OtherModuleName(dep))
 	}
+
+	// TODO: this could all be removed if tradefed was used as the test runner, it will find everything
+	// annotated as a test and run it.
+	for _, src := range r.compiledJavaSrcs {
+		s := src.Rel()
+		if !strings.HasSuffix(s, "Test.java") {
+			continue
+		} else if strings.HasSuffix(s, "/BaseRobolectricTest.java") {
+			continue
+		} else if strings.HasPrefix(s, "src/") {
+			s = strings.TrimPrefix(s, "src/")
+		}
+		r.tests = append(r.tests, s)
+	}
+}
+
+func shardTests(paths []string, shards int) [][]string {
+	if shards > len(paths) {
+		shards = len(paths)
+	}
+	if shards == 0 {
+		return nil
+	}
+	ret := make([][]string, 0, shards)
+	shardSize := (len(paths) + shards - 1) / shards
+	for len(paths) > shardSize {
+		ret = append(ret, paths[0:shardSize])
+		paths = paths[shardSize:]
+	}
+	if len(paths) > 0 {
+		ret = append(ret, paths)
+	}
+	return ret
 }
 
 func (r *robolectricTest) AndroidMk() android.AndroidMkData {
@@ -77,24 +115,50 @@
 	data.Custom = func(w io.Writer, name, prefix, moduleDir string, data android.AndroidMkData) {
 		android.WriteAndroidMkData(w, data)
 
-		fmt.Fprintln(w, "")
-		fmt.Fprintln(w, "include $(CLEAR_VARS)")
-		fmt.Fprintln(w, "LOCAL_MODULE := Run"+name)
-		fmt.Fprintln(w, "LOCAL_JAVA_LIBRARIES :=", name)
-		fmt.Fprintln(w, "LOCAL_JAVA_LIBRARIES += ", strings.Join(r.libs, " "))
-		fmt.Fprintln(w, "LOCAL_TEST_PACKAGE :=", String(r.robolectricProperties.Instrumentation_for))
-		if t := r.robolectricProperties.Test_options.Timeout; t != nil {
-			fmt.Fprintln(w, "LOCAL_ROBOTEST_TIMEOUT :=", *t)
+		if s := r.robolectricProperties.Test_options.Shards; s != nil && *s > 1 {
+			shards := shardTests(r.tests, int(*s))
+			for i, shard := range shards {
+				r.writeTestRunner(w, name, "Run"+name+strconv.Itoa(i), shard)
+			}
+
+			// TODO: add rules to dist the outputs of the individual tests, or combine them together?
+			fmt.Fprintln(w, "")
+			fmt.Fprintln(w, ".PHONY:", "Run"+name)
+			fmt.Fprintln(w, "Run"+name, ": \\")
+			for i := range shards {
+				fmt.Fprintln(w, "   ", "Run"+name+strconv.Itoa(i), "\\")
+			}
+			fmt.Fprintln(w, "")
+		} else {
+			r.writeTestRunner(w, name, "Run"+name, r.tests)
 		}
-		fmt.Fprintln(w, "-include external/robolectric-shadows/run_robotests.mk")
 	}
 
 	return data
 }
 
+func (r *robolectricTest) writeTestRunner(w io.Writer, module, name string, tests []string) {
+	fmt.Fprintln(w, "")
+	fmt.Fprintln(w, "include $(CLEAR_VARS)")
+	fmt.Fprintln(w, "LOCAL_MODULE :=", name)
+	fmt.Fprintln(w, "LOCAL_JAVA_LIBRARIES :=", module)
+	fmt.Fprintln(w, "LOCAL_JAVA_LIBRARIES += ", strings.Join(r.libs, " "))
+	fmt.Fprintln(w, "LOCAL_TEST_PACKAGE :=", String(r.robolectricProperties.Instrumentation_for))
+	fmt.Fprintln(w, "LOCAL_ROBOTEST_FILES :=", strings.Join(tests, " "))
+	if t := r.robolectricProperties.Test_options.Timeout; t != nil {
+		fmt.Fprintln(w, "LOCAL_ROBOTEST_TIMEOUT :=", *t)
+	}
+	fmt.Fprintln(w, "-include external/robolectric-shadows/run_robotests.mk")
+
+}
+
 // An android_robolectric_test module compiles tests against the Robolectric framework that can run on the local host
 // instead of on a device.  It also generates a rule with the name of the module prefixed with "Run" that can be
 // used to run the tests.  Running the tests with build rule will eventually be deprecated and replaced with atest.
+//
+// The test runner considers any file listed in srcs whose name ends with Test.java to be a test class, unless
+// it is named BaseRobolectricTest.java.  The path to the each source file must exactly match the package
+// name, or match the package name when the prefix "src/" is removed.
 func RobolectricTestFactory() android.Module {
 	module := &robolectricTest{}
 
diff --git a/java/robolectric_test.go b/java/robolectric_test.go
new file mode 100644
index 0000000..e89c6e7
--- /dev/null
+++ b/java/robolectric_test.go
@@ -0,0 +1,88 @@
+// Copyright 2019 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package java
+
+import (
+	"reflect"
+	"testing"
+)
+
+func Test_shardTests(t *testing.T) {
+	type args struct {
+		paths  []string
+		shards int
+	}
+	tests := []struct {
+		name string
+		args args
+		want [][]string
+	}{
+		{
+			name: "empty",
+			args: args{
+				paths:  nil,
+				shards: 1,
+			},
+			want: [][]string(nil),
+		},
+		{
+			name: "too many shards",
+			args: args{
+				paths:  []string{"a", "b"},
+				shards: 3,
+			},
+			want: [][]string{{"a"}, {"b"}},
+		},
+		{
+			name: "single shard",
+			args: args{
+				paths:  []string{"a", "b"},
+				shards: 1,
+			},
+			want: [][]string{{"a", "b"}},
+		},
+		{
+			name: "shard per input",
+			args: args{
+				paths:  []string{"a", "b", "c"},
+				shards: 3,
+			},
+			want: [][]string{{"a"}, {"b"}, {"c"}},
+		},
+		{
+			name: "balanced shards",
+			args: args{
+				paths:  []string{"a", "b", "c", "d"},
+				shards: 2,
+			},
+			want: [][]string{{"a", "b"}, {"c", "d"}},
+		},
+		{
+			name: "unbalanced shards",
+			args: args{
+				paths:  []string{"a", "b", "c"},
+				shards: 2,
+			},
+			want: [][]string{{"a", "b"}, {"c"}},
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := shardTests(tt.args.paths, tt.args.shards); !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("shardTests() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
diff --git a/java/sdk.go b/java/sdk.go
index 90b8fac..9dfb38b 100644
--- a/java/sdk.go
+++ b/java/sdk.go
@@ -38,17 +38,23 @@
 var apiFingerprintPathKey = android.NewOnceKey("apiFingerprintPathKey")
 
 type sdkContext interface {
-	// sdkVersion eturns the sdk_version property of the current module, or an empty string if it is not set.
+	// sdkVersion returns the sdk_version property of the current module, or an empty string if it is not set.
 	sdkVersion() string
 	// minSdkVersion returns the min_sdk_version property of the current module, or sdkVersion() if it is not set.
 	minSdkVersion() string
 	// targetSdkVersion returns the target_sdk_version property of the current module, or sdkVersion() if it is not set.
 	targetSdkVersion() string
+
+	// Temporarily provide access to the no_standard_libs property (where present).
+	noStandardLibs() bool
+
+	// Temporarily provide access to the no_frameworks_libs property (where present).
+	noFrameworkLibs() bool
 }
 
 func sdkVersionOrDefault(ctx android.BaseModuleContext, v string) string {
 	switch v {
-	case "", "current", "system_current", "test_current", "core_current":
+	case "", "none", "current", "system_current", "test_current", "core_current":
 		return ctx.Config().DefaultAppTargetSdk()
 	default:
 		return v
@@ -59,7 +65,7 @@
 // it returns android.FutureApiLevel (10000).
 func sdkVersionToNumber(ctx android.BaseModuleContext, v string) (int, error) {
 	switch v {
-	case "", "current", "test_current", "system_current", "core_current":
+	case "", "none", "current", "test_current", "system_current", "core_current":
 		return ctx.Config().DefaultAppTargetSdkInt(), nil
 	default:
 		n := android.GetNumericSdkVersion(v)
@@ -138,6 +144,10 @@
 			useFiles: true,
 			jars:     android.Paths{jarPath.Path(), lambdaStubsPath},
 			aidl:     android.OptionalPathForPath(aidlPath.Path()),
+
+			// Pass values straight through for now to match previous behavior.
+			noStandardLibs:   sdkContext.noStandardLibs(),
+			noFrameworksLibs: sdkContext.noFrameworkLibs(),
 		}
 	}
 
@@ -148,6 +158,10 @@
 			systemModules:      m + "_system_modules",
 			frameworkResModule: r,
 			aidl:               android.OptionalPathForPath(aidl),
+
+			// Pass values straight through for now to match previous behavior.
+			noStandardLibs:   sdkContext.noStandardLibs(),
+			noFrameworksLibs: sdkContext.noFrameworkLibs(),
 		}
 
 		if m == "core.current.stubs" {
@@ -173,7 +187,7 @@
 		}
 	}
 
-	if ctx.Config().UnbundledBuildUsePrebuiltSdks() && v != "" {
+	if ctx.Config().UnbundledBuildUsePrebuiltSdks() && v != "" && v != "none" {
 		return toPrebuilt(v)
 	}
 
@@ -182,6 +196,14 @@
 		return sdkDep{
 			useDefaultLibs:     true,
 			frameworkResModule: "framework-res",
+
+			// Pass values straight through for now to match previous behavior.
+			noStandardLibs:   sdkContext.noStandardLibs(),
+			noFrameworksLibs: sdkContext.noFrameworkLibs(),
+		}
+	case "none":
+		return sdkDep{
+			noStandardLibs: true,
 		}
 	case "current":
 		return toModule("android_stubs_current", "framework-res", sdkFrameworkAidlPath(ctx))
diff --git a/java/sdk_library.go b/java/sdk_library.go
index e383533..01531c5 100644
--- a/java/sdk_library.go
+++ b/java/sdk_library.go
@@ -159,7 +159,8 @@
 	ctx.AddVariationDependencies(nil, publicApiStubsTag, module.stubsName(apiScopePublic))
 	ctx.AddVariationDependencies(nil, publicApiFileTag, module.docsName(apiScopePublic))
 
-	if !Bool(module.properties.No_standard_libs) {
+	sdkDep := decodeSdkDep(ctx, sdkContext(&module.Library))
+	if sdkDep.hasStandardLibs() {
 		ctx.AddVariationDependencies(nil, systemApiStubsTag, module.stubsName(apiScopeSystem))
 		ctx.AddVariationDependencies(nil, systemApiFileTag, module.docsName(apiScopeSystem))
 		ctx.AddVariationDependencies(nil, testApiFileTag, module.docsName(apiScopeTest))
@@ -401,17 +402,22 @@
 		}
 	}{}
 
+	sdkVersion := module.sdkVersion(apiScope)
+	sdkDep := decodeSdkDep(mctx, sdkContext(&module.Library))
+	if !sdkDep.hasStandardLibs() {
+		sdkVersion = "none"
+	}
+
 	props.Name = proptools.StringPtr(module.stubsName(apiScope))
 	// sources are generated from the droiddoc
 	props.Srcs = []string{":" + module.docsName(apiScope)}
-	props.Sdk_version = proptools.StringPtr(module.sdkVersion(apiScope))
+	props.Sdk_version = proptools.StringPtr(sdkVersion)
 	props.Libs = module.sdkLibraryProperties.Stub_only_libs
 	// Unbundled apps will use the prebult one from /prebuilts/sdk
 	if mctx.Config().UnbundledBuildUsePrebuiltSdks() {
 		props.Product_variables.Unbundled_build.Enabled = proptools.BoolPtr(false)
 	}
 	props.Product_variables.Pdk.Enabled = proptools.BoolPtr(false)
-	props.No_standard_libs = module.Library.Module.properties.No_standard_libs
 	props.System_modules = module.Library.Module.deviceProperties.System_modules
 	props.Openjdk9.Srcs = module.Library.Module.properties.Openjdk9.Srcs
 	props.Openjdk9.Javacflags = module.Library.Module.properties.Openjdk9.Javacflags
@@ -441,13 +447,13 @@
 		Srcs_lib                         *string
 		Srcs_lib_whitelist_dirs          []string
 		Srcs_lib_whitelist_pkgs          []string
+		Sdk_version                      *string
 		Libs                             []string
 		Arg_files                        []string
 		Args                             *string
 		Api_tag_name                     *string
 		Api_filename                     *string
 		Removed_api_filename             *string
-		No_standard_libs                 *bool
 		Java_version                     *string
 		Merge_annotations_dirs           []string
 		Merge_inclusion_annotations_dirs []string
@@ -462,9 +468,16 @@
 		}
 	}{}
 
+	sdkDep := decodeSdkDep(mctx, sdkContext(&module.Library))
+	sdkVersion := ""
+	if !sdkDep.hasStandardLibs() {
+		sdkVersion = "none"
+	}
+
 	props.Name = proptools.StringPtr(module.docsName(apiScope))
 	props.Srcs = append(props.Srcs, module.Library.Module.properties.Srcs...)
 	props.Srcs = append(props.Srcs, module.sdkLibraryProperties.Api_srcs...)
+	props.Sdk_version = proptools.StringPtr(sdkVersion)
 	props.Installable = proptools.BoolPtr(false)
 	// A droiddoc module has only one Libs property and doesn't distinguish between
 	// shared libs and static libs. So we need to add both of these libs to Libs property.
@@ -472,7 +485,6 @@
 	props.Libs = append(props.Libs, module.Library.Module.properties.Static_libs...)
 	props.Aidl.Include_dirs = module.Library.Module.deviceProperties.Aidl.Include_dirs
 	props.Aidl.Local_include_dirs = module.Library.Module.deviceProperties.Aidl.Local_include_dirs
-	props.No_standard_libs = module.Library.Module.properties.No_standard_libs
 	props.Java_version = module.Library.Module.properties.Java_version
 
 	props.Merge_annotations_dirs = module.sdkLibraryProperties.Merge_annotations_dirs
@@ -593,7 +605,7 @@
 
 func (module *SdkLibrary) PrebuiltJars(ctx android.BaseModuleContext, sdkVersion string) android.Paths {
 	var api, v string
-	if sdkVersion == "" {
+	if sdkVersion == "" || sdkVersion == "none" {
 		api = "system"
 		v = "current"
 	} else if strings.Contains(sdkVersion, "_") {
@@ -701,7 +713,8 @@
 	module.createStubsLibrary(mctx, apiScopePublic)
 	module.createDocs(mctx, apiScopePublic)
 
-	if !Bool(module.properties.No_standard_libs) {
+	sdkDep := decodeSdkDep(mctx, sdkContext(&module.Library))
+	if sdkDep.hasStandardLibs() {
 		// for system API stubs
 		module.createStubsLibrary(mctx, apiScopeSystem)
 		module.createDocs(mctx, apiScopeSystem)
diff --git a/java/sdk_test.go b/java/sdk_test.go
index cc4da2e..1efe83b 100644
--- a/java/sdk_test.go
+++ b/java/sdk_test.go
@@ -47,6 +47,14 @@
 			aidl:          "-Iframework/aidl",
 		},
 		{
+			name:          "no_framework_libs:true",
+			properties:    `no_framework_libs:true`,
+			bootclasspath: config.DefaultBootclasspathLibraries,
+			system:        config.DefaultSystemModules,
+			classpath:     []string{},
+			aidl:          "",
+		},
+		{
 			name:          "blank sdk version",
 			properties:    `sdk_version: "",`,
 			bootclasspath: config.DefaultBootclasspathLibraries,
@@ -105,7 +113,7 @@
 		},
 		{
 
-			name:          "nostdlib",
+			name:          "nostdlib - no_standard_libs: true",
 			properties:    `no_standard_libs: true, system_modules: "none"`,
 			system:        "none",
 			bootclasspath: []string{`""`},
@@ -113,7 +121,15 @@
 		},
 		{
 
-			name:          "nostdlib system_modules",
+			name:          "nostdlib",
+			properties:    `sdk_version: "none", system_modules: "none"`,
+			system:        "none",
+			bootclasspath: []string{`""`},
+			classpath:     []string{},
+		},
+		{
+
+			name:          "nostdlib system_modules - no_standard_libs: true",
 			properties:    `no_standard_libs: true, system_modules: "core-platform-api-stubs-system-modules"`,
 			system:        "core-platform-api-stubs-system-modules",
 			bootclasspath: []string{`""`},
@@ -121,6 +137,14 @@
 		},
 		{
 
+			name:          "nostdlib system_modules",
+			properties:    `sdk_version: "none", system_modules: "core-platform-api-stubs-system-modules"`,
+			system:        "core-platform-api-stubs-system-modules",
+			bootclasspath: []string{`""`},
+			classpath:     []string{},
+		},
+		{
+
 			name:          "host default",
 			moduleType:    "java_library_host",
 			properties:    ``,
@@ -129,13 +153,6 @@
 			classpath:     []string{},
 		},
 		{
-			name:       "host nostdlib",
-			moduleType: "java_library_host",
-			host:       android.Host,
-			properties: `no_standard_libs: true`,
-			classpath:  []string{},
-		},
-		{
 
 			name:          "host supported default",
 			host:          android.Host,
@@ -144,12 +161,18 @@
 			bootclasspath: []string{"jdk8/jre/lib/jce.jar", "jdk8/jre/lib/rt.jar"},
 		},
 		{
-			name:       "host supported nostdlib",
+			name:       "host supported nostdlib - no_standard_libs: true",
 			host:       android.Host,
 			properties: `host_supported: true, no_standard_libs: true, system_modules: "none"`,
 			classpath:  []string{},
 		},
 		{
+			name:       "host supported nostdlib",
+			host:       android.Host,
+			properties: `host_supported: true, sdk_version: "none", system_modules: "none"`,
+			classpath:  []string{},
+		},
+		{
 
 			name:          "unbundled sdk v25",
 			unbundled:     true,
diff --git a/java/testing.go b/java/testing.go
index e1b06a0..7cd1871 100644
--- a/java/testing.go
+++ b/java/testing.go
@@ -54,8 +54,7 @@
 			java_library {
 				name: "%s",
 				srcs: ["a.java"],
-				no_standard_libs: true,
-				sdk_version: "core_current",
+				sdk_version: "none",
 				system_modules: "core-platform-api-stubs-system-modules",
 			}
 		`, extra)
@@ -66,7 +65,6 @@
 			name: "framework",
 			srcs: ["a.java"],
 			no_standard_libs: true,
-			sdk_version: "core_current",
 			system_modules: "core-platform-api-stubs-system-modules",
 			aidl: {
 				export_include_dirs: ["framework/aidl"],
@@ -82,7 +80,6 @@
 			name: "android.hidl.base-V1.0-java",
 			srcs: ["a.java"],
 			no_standard_libs: true,
-			sdk_version: "core_current",
 			system_modules: "core-platform-api-stubs-system-modules",
 			installable: true,
 		}
@@ -91,7 +88,6 @@
 			name: "android.hidl.manager-V1.0-java",
 			srcs: ["a.java"],
 			no_standard_libs: true,
-			sdk_version: "core_current",
 			system_modules: "core-platform-api-stubs-system-modules",
 			installable: true,
 		}
@@ -100,7 +96,6 @@
 			name: "org.apache.http.legacy",
 			srcs: ["a.java"],
 			no_standard_libs: true,
-			sdk_version: "core_current",
 			system_modules: "core-platform-api-stubs-system-modules",
 			installable: true,
 		}
diff --git a/tradefed/autogen.go b/tradefed/autogen.go
index da5dabe..952b022 100644
--- a/tradefed/autogen.go
+++ b/tradefed/autogen.go
@@ -16,7 +16,6 @@
 
 import (
 	"fmt"
-	"sort"
 	"strings"
 
 	"github.com/google/blueprint"
@@ -39,9 +38,9 @@
 }
 
 var autogenTestConfig = pctx.StaticRule("autogenTestConfig", blueprint.RuleParams{
-	Command:     "sed 's&{MODULE}&${name}&g;s&{EXTRA_OPTIONS}&'${extraOptions}'&g' $template > $out",
+	Command:     "sed 's&{MODULE}&${name}&g;s&{EXTRA_CONFIGS}&'${extraConfigs}'&g' $template > $out",
 	CommandDeps: []string{"$template"},
-}, "name", "template", "extraOptions")
+}, "name", "template", "extraConfigs")
 
 func testConfigPath(ctx android.ModuleContext, prop *string, testSuites []string) (path android.Path, autogenPath android.WritablePath) {
 	if p := getTestConfig(ctx, prop); p != nil {
@@ -57,17 +56,38 @@
 	}
 }
 
-func autogenTemplate(ctx android.ModuleContext, output android.WritablePath, template string, optionsMap map[string]string) {
-	// If no test option found, delete {EXTRA_OPTIONS} line.
-	var options []string
-	for optionName, value := range optionsMap {
-		if value != "" {
-			options = append(options, fmt.Sprintf(`<option name="%s" value="%s" />`, optionName, value))
-		}
+type Config interface {
+	Config() string
+}
+
+type Option struct {
+	Name  string
+	Value string
+}
+
+var _ Config = Option{}
+
+func (o Option) Config() string {
+	return fmt.Sprintf(`<option name="%s" value="%s" />`, o.Name, o.Value)
+}
+
+type Preparer struct {
+	Class string
+}
+
+var _ Config = Preparer{}
+
+func (p Preparer) Config() string {
+	return fmt.Sprintf(`<target_preparer class="%s" />`, p.Class)
+}
+
+func autogenTemplate(ctx android.ModuleContext, output android.WritablePath, template string, configs []Config) {
+	var configStrings []string
+	for _, config := range configs {
+		configStrings = append(configStrings, config.Config())
 	}
-	sort.Strings(options)
-	extraOptions := strings.Join(options, "\n        ")
-	extraOptions = proptools.NinjaAndShellEscape(extraOptions)
+	extraConfigs := strings.Join(configStrings, "\n        ")
+	extraConfigs = proptools.NinjaAndShellEscape(extraConfigs)
 
 	ctx.Build(pctx, android.BuildParams{
 		Rule:        autogenTestConfig,
@@ -76,26 +96,23 @@
 		Args: map[string]string{
 			"name":         ctx.ModuleName(),
 			"template":     template,
-			"extraOptions": extraOptions,
+			"extraConfigs": extraConfigs,
 		},
 	})
 }
 
 func AutoGenNativeTestConfig(ctx android.ModuleContext, testConfigProp *string,
-	testConfigTemplateProp *string, testSuites []string,
-	optionsMap map[string]string) android.Path {
+	testConfigTemplateProp *string, testSuites []string, config []Config) android.Path {
 	path, autogenPath := testConfigPath(ctx, testConfigProp, testSuites)
 	if autogenPath != nil {
 		templatePath := getTestConfigTemplate(ctx, testConfigTemplateProp)
 		if templatePath.Valid() {
-			autogenTemplate(ctx, autogenPath, templatePath.String(), optionsMap)
+			autogenTemplate(ctx, autogenPath, templatePath.String(), config)
 		} else {
 			if ctx.Device() {
-				autogenTemplate(ctx, autogenPath, "${NativeTestConfigTemplate}",
-					optionsMap)
+				autogenTemplate(ctx, autogenPath, "${NativeTestConfigTemplate}", config)
 			} else {
-				autogenTemplate(ctx, autogenPath, "${NativeHostTestConfigTemplate}",
-					optionsMap)
+				autogenTemplate(ctx, autogenPath, "${NativeHostTestConfigTemplate}", config)
 			}
 		}
 		return autogenPath
@@ -104,14 +121,14 @@
 }
 
 func AutoGenNativeBenchmarkTestConfig(ctx android.ModuleContext, testConfigProp *string,
-	testConfigTemplateProp *string, testSuites []string) android.Path {
+	testConfigTemplateProp *string, testSuites []string, configs []Config) android.Path {
 	path, autogenPath := testConfigPath(ctx, testConfigProp, testSuites)
 	if autogenPath != nil {
 		templatePath := getTestConfigTemplate(ctx, testConfigTemplateProp)
 		if templatePath.Valid() {
-			autogenTemplate(ctx, autogenPath, templatePath.String(), nil)
+			autogenTemplate(ctx, autogenPath, templatePath.String(), configs)
 		} else {
-			autogenTemplate(ctx, autogenPath, "${NativeBenchmarkTestConfigTemplate}", nil)
+			autogenTemplate(ctx, autogenPath, "${NativeBenchmarkTestConfigTemplate}", configs)
 		}
 		return autogenPath
 	}
diff --git a/ui/build/config.go b/ui/build/config.go
index c298f00..6df9529 100644
--- a/ui/build/config.go
+++ b/ui/build/config.go
@@ -61,6 +61,28 @@
 
 const srcDirFileCheck = "build/soong/root.bp"
 
+type BuildAction uint
+
+const (
+	// Builds all of the modules and their dependencies of a specified directory, relative to the root
+	// directory of the source tree.
+	BUILD_MODULES_IN_A_DIRECTORY BuildAction = iota
+
+	// Builds all of the modules and their dependencies of a list of specified directories. All specified
+	// directories are relative to the root directory of the source tree.
+	BUILD_MODULES_IN_DIRECTORIES
+)
+
+// checkTopDir validates that the current directory is at the root directory of the source tree.
+func checkTopDir(ctx Context) {
+	if _, err := os.Stat(srcDirFileCheck); err != nil {
+		if os.IsNotExist(err) {
+			ctx.Fatalf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
+		}
+		ctx.Fatalln("Error verifying tree state:", err)
+	}
+}
+
 func NewConfig(ctx Context, args ...string) Config {
 	ret := &configImpl{
 		environ: OsEnvironment(),
@@ -154,12 +176,7 @@
 	ret.environ.Set("TMPDIR", absPath(ctx, ret.TempDir()))
 
 	// Precondition: the current directory is the top of the source tree
-	if _, err := os.Stat(srcDirFileCheck); err != nil {
-		if os.IsNotExist(err) {
-			log.Fatalf("Current working directory must be the source tree. %q not found", srcDirFileCheck)
-		}
-		log.Fatalln("Error verifying tree state:", err)
-	}
+	checkTopDir(ctx)
 
 	if srcDir := absPath(ctx, "."); strings.ContainsRune(srcDir, ' ') {
 		log.Println("You are building in a directory whose absolute path contains a space character:")
@@ -229,6 +246,203 @@
 	return Config{ret}
 }
 
+// NewBuildActionConfig returns a build configuration based on the build action. The arguments are
+// processed based on the build action and extracts any arguments that belongs to the build action.
+func NewBuildActionConfig(action BuildAction, dir string, buildDependencies bool, ctx Context, args ...string) Config {
+	return NewConfig(ctx, getConfigArgs(action, dir, buildDependencies, ctx, args)...)
+}
+
+// getConfigArgs processes the command arguments based on the build action and creates a set of new
+// arguments to be accepted by Config.
+func getConfigArgs(action BuildAction, dir string, buildDependencies bool, ctx Context, args []string) []string {
+	// The next block of code verifies that the current directory is the root directory of the source
+	// tree. It then finds the relative path of dir based on the root directory of the source tree
+	// and verify that dir is inside of the source tree.
+	checkTopDir(ctx)
+	topDir, err := os.Getwd()
+	if err != nil {
+		ctx.Fatalf("Error retrieving top directory: %v", err)
+	}
+	dir, err = filepath.Abs(dir)
+	if err != nil {
+		ctx.Fatalf("Unable to find absolute path %s: %v", dir, err)
+	}
+	relDir, err := filepath.Rel(topDir, dir)
+	if err != nil {
+		ctx.Fatalf("Unable to find relative path %s of %s: %v", relDir, topDir, err)
+	}
+	// If there are ".." in the path, it's not in the source tree.
+	if strings.Contains(relDir, "..") {
+		ctx.Fatalf("Directory %s is not under the source tree %s", dir, topDir)
+	}
+
+	configArgs := args[:]
+
+	// If the arguments contains GET-INSTALL-PATH, change the target name prefix from MODULES-IN- to
+	// GET-INSTALL-PATH-IN- to extract the installation path instead of building the modules.
+	targetNamePrefix := "MODULES-IN-"
+	if inList("GET-INSTALL-PATH", configArgs) {
+		targetNamePrefix = "GET-INSTALL-PATH-IN-"
+		configArgs = removeFromList("GET-INSTALL-PATH", configArgs)
+	}
+
+	var buildFiles []string
+	var targets []string
+
+	switch action {
+	case BUILD_MODULES_IN_A_DIRECTORY:
+		// If dir is the root source tree, all the modules are built of the source tree are built so
+		// no need to find the build file.
+		if topDir == dir {
+			break
+		}
+		// Find the build file from the directory where the build action was triggered by traversing up
+		// the source tree. If a blank build filename is returned, simply use the directory where the build
+		// action was invoked.
+		buildFile := findBuildFile(ctx, relDir)
+		if buildFile == "" {
+			buildFile = filepath.Join(relDir, "Android.mk")
+		}
+		buildFiles = []string{buildFile}
+		targets = []string{convertToTarget(filepath.Dir(buildFile), targetNamePrefix)}
+	case BUILD_MODULES_IN_DIRECTORIES:
+		newConfigArgs, dirs := splitArgs(configArgs)
+		configArgs = newConfigArgs
+		targets, buildFiles = getTargetsFromDirs(ctx, relDir, dirs, targetNamePrefix)
+	}
+
+	// This is to support building modules without building their dependencies. Soon, this will be
+	// deprecated.
+	if !buildDependencies && len(buildFiles) > 0 {
+		if err := os.Setenv("ONE_SHOT_MAKEFILE", strings.Join(buildFiles, " ")); err != nil {
+			ctx.Fatalf("Unable to set ONE_SHOT_MAKEFILE environment variable: %v", err)
+		}
+	}
+
+	// Tidy only override all other specified targets.
+	tidyOnly := os.Getenv("WITH_TIDY_ONLY")
+	if tidyOnly == "true" || tidyOnly == "1" {
+		configArgs = append(configArgs, "tidy_only")
+	} else {
+		configArgs = append(configArgs, targets...)
+	}
+
+	return configArgs
+}
+
+// convertToTarget replaces "/" to "-" in dir and pre-append the targetNamePrefix to the target name.
+func convertToTarget(dir string, targetNamePrefix string) string {
+	return targetNamePrefix + strings.ReplaceAll(dir, "/", "-")
+}
+
+// findBuildFile finds a build file (makefile or blueprint file) by looking at dir first. If not
+// found, go up one level and repeat again until one is found and the path of that build file
+// relative to the root directory of the source tree is returned. The returned filename of build
+// file is "Android.mk". If one was not found, a blank string is returned.
+func findBuildFile(ctx Context, dir string) string {
+	// If the string is empty, assume it is top directory of the source tree.
+	if dir == "" {
+		return ""
+	}
+
+	for ; dir != "."; dir = filepath.Dir(dir) {
+		for _, buildFile := range []string{"Android.bp", "Android.mk"} {
+			_, err := os.Stat(filepath.Join(dir, buildFile))
+			if err == nil {
+				// Returning the filename Android.mk as it might be used for ONE_SHOT_MAKEFILE variable.
+				return filepath.Join(dir, "Android.mk")
+			}
+			if !os.IsNotExist(err) {
+				ctx.Fatalf("Error retrieving the build file stats: %v", err)
+			}
+		}
+	}
+
+	return ""
+}
+
+// splitArgs iterates over the arguments list and splits into two lists: arguments and directories.
+func splitArgs(args []string) (newArgs []string, dirs []string) {
+	specialArgs := map[string]bool{
+		"showcommands": true,
+		"snod":         true,
+		"dist":         true,
+		"checkbuild":   true,
+	}
+
+	newArgs = []string{}
+	dirs = []string{}
+
+	for _, arg := range args {
+		// It's a dash argument if it starts with "-" or it's a key=value pair, it's not a directory.
+		if strings.IndexRune(arg, '-') == 0 || strings.IndexRune(arg, '=') != -1 {
+			newArgs = append(newArgs, arg)
+			continue
+		}
+
+		if _, ok := specialArgs[arg]; ok {
+			newArgs = append(newArgs, arg)
+			continue
+		}
+
+		dirs = append(dirs, arg)
+	}
+
+	return newArgs, dirs
+}
+
+// getTargetsFromDirs iterates over the dirs list and creates a list of targets to build. If a
+// directory from the dirs list does not exist, a fatal error is raised. relDir is related to the
+// source root tree where the build action command was invoked. Each directory is validated if the
+// build file can be found and follows the format "dir1:target1,target2,...". Target is optional.
+func getTargetsFromDirs(ctx Context, relDir string, dirs []string, targetNamePrefix string) (targets []string, buildFiles []string) {
+	for _, dir := range dirs {
+		// The directory may have specified specific modules to build. ":" is the separator to separate
+		// the directory and the list of modules.
+		s := strings.Split(dir, ":")
+		l := len(s)
+		if l > 2 { // more than one ":" was specified.
+			ctx.Fatalf("%s not in proper directory:target1,target2,... format (\":\" was specified more than once)", dir)
+		}
+
+		dir = filepath.Join(relDir, s[0])
+		if _, err := os.Stat(dir); err != nil {
+			ctx.Fatalf("couldn't find directory %s", dir)
+		}
+
+		// Verify that if there are any targets specified after ":". Each target is separated by ",".
+		var newTargets []string
+		if l == 2 && s[1] != "" {
+			newTargets = strings.Split(s[1], ",")
+			if inList("", newTargets) {
+				ctx.Fatalf("%s not in proper directory:target1,target2,... format", dir)
+			}
+		}
+
+		buildFile := findBuildFile(ctx, dir)
+		if buildFile == "" {
+			ctx.Fatalf("Build file not found for %s directory", dir)
+		}
+		buildFileDir := filepath.Dir(buildFile)
+
+		// If there are specified targets, find the build file in the directory. If dir does not
+		// contain the build file, bail out as it is required for one shot build. If there are no
+		// target specified, build all the modules in dir (or the closest one in the dir path).
+		if len(newTargets) > 0 {
+			if buildFileDir != dir {
+				ctx.Fatalf("Couldn't locate a build file from %s directory", dir)
+			}
+		} else {
+			newTargets = []string{convertToTarget(buildFileDir, targetNamePrefix)}
+		}
+
+		buildFiles = append(buildFiles, buildFile)
+		targets = append(targets, newTargets...)
+	}
+
+	return targets, buildFiles
+}
+
 func (c *configImpl) parseArgs(ctx Context, args []string) {
 	for i := 0; i < len(args); i++ {
 		arg := strings.TrimSpace(args[i])
diff --git a/ui/build/config_test.go b/ui/build/config_test.go
index 242e3af..1ef5456 100644
--- a/ui/build/config_test.go
+++ b/ui/build/config_test.go
@@ -17,19 +17,22 @@
 import (
 	"bytes"
 	"context"
+	"fmt"
+	"io/ioutil"
+	"os"
+	"path/filepath"
 	"reflect"
 	"strings"
 	"testing"
 
 	"android/soong/ui/logger"
-	"android/soong/ui/terminal"
 )
 
 func testContext() Context {
 	return Context{&ContextImpl{
 		Context: context.Background(),
 		Logger:  logger.New(&bytes.Buffer{}),
-		Writer:  terminal.NewWriter(terminal.NewCustomStdio(&bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{})),
+		Writer:  &bytes.Buffer{},
 	}}
 }
 
@@ -173,3 +176,877 @@
 		})
 	}
 }
+
+func TestConfigCheckTopDir(t *testing.T) {
+	ctx := testContext()
+	buildRootDir := filepath.Dir(srcDirFileCheck)
+	expectedErrStr := fmt.Sprintf("Current working directory must be the source tree. %q not found.", srcDirFileCheck)
+
+	tests := []struct {
+		// ********* Setup *********
+		// Test description.
+		description string
+
+		// ********* Action *********
+		// If set to true, the build root file is created.
+		rootBuildFile bool
+
+		// The current path where Soong is being executed.
+		path string
+
+		// ********* Validation *********
+		// Expecting error and validate the error string against expectedErrStr.
+		wantErr bool
+	}{{
+		description:   "current directory is the root source tree",
+		rootBuildFile: true,
+		path:          ".",
+		wantErr:       false,
+	}, {
+		description:   "one level deep in the source tree",
+		rootBuildFile: true,
+		path:          "1",
+		wantErr:       true,
+	}, {
+		description:   "very deep in the source tree",
+		rootBuildFile: true,
+		path:          "1/2/3/4/5/6/7/8/9/1/2/3/4/5/6/7/8/9/1/2/3/4/5/6/7/8/9/1/2/3/4/5/6/7",
+		wantErr:       true,
+	}, {
+		description:   "outside of source tree",
+		rootBuildFile: false,
+		path:          "1/2/3/4/5",
+		wantErr:       true,
+	}}
+
+	for _, tt := range tests {
+		t.Run(tt.description, func(t *testing.T) {
+			defer logger.Recover(func(err error) {
+				if !tt.wantErr {
+					t.Fatalf("Got unexpected error: %v", err)
+				}
+				if expectedErrStr != err.Error() {
+					t.Fatalf("expected %s, got %s", expectedErrStr, err.Error())
+				}
+			})
+
+			// Create the root source tree.
+			rootDir, err := ioutil.TempDir("", "")
+			if err != nil {
+				t.Fatal(err)
+			}
+			defer os.RemoveAll(rootDir)
+
+			// Create the build root file. This is to test if topDir returns an error if the build root
+			// file does not exist.
+			if tt.rootBuildFile {
+				dir := filepath.Join(rootDir, buildRootDir)
+				if err := os.MkdirAll(dir, 0755); err != nil {
+					t.Errorf("failed to create %s directory: %v", dir, err)
+				}
+				f := filepath.Join(rootDir, srcDirFileCheck)
+				if err := ioutil.WriteFile(f, []byte{}, 0644); err != nil {
+					t.Errorf("failed to create file %s: %v", f, err)
+				}
+			}
+
+			// Next block of code is to set the current directory.
+			dir := rootDir
+			if tt.path != "" {
+				dir = filepath.Join(dir, tt.path)
+				if err := os.MkdirAll(dir, 0755); err != nil {
+					t.Errorf("failed to create %s directory: %v", dir, err)
+				}
+			}
+			curDir, err := os.Getwd()
+			if err != nil {
+				t.Fatalf("failed to get the current directory: %v", err)
+			}
+			defer func() { os.Chdir(curDir) }()
+
+			if err := os.Chdir(dir); err != nil {
+				t.Fatalf("failed to change directory to %s: %v", dir, err)
+			}
+
+			checkTopDir(ctx)
+		})
+	}
+}
+
+func TestConfigConvertToTarget(t *testing.T) {
+	tests := []struct {
+		// ********* Setup *********
+		// Test description.
+		description string
+
+		// ********* Action *********
+		// The current directory where Soong is being executed.
+		dir string
+
+		// The current prefix string to be pre-appended to the target.
+		prefix string
+
+		// ********* Validation *********
+		// The expected target to be invoked in ninja.
+		expectedTarget string
+	}{{
+		description:    "one level directory in source tree",
+		dir:            "test1",
+		prefix:         "MODULES-IN-",
+		expectedTarget: "MODULES-IN-test1",
+	}, {
+		description:    "multiple level directories in source tree",
+		dir:            "test1/test2/test3/test4",
+		prefix:         "GET-INSTALL-PATH-IN-",
+		expectedTarget: "GET-INSTALL-PATH-IN-test1-test2-test3-test4",
+	}}
+	for _, tt := range tests {
+		t.Run(tt.description, func(t *testing.T) {
+			target := convertToTarget(tt.dir, tt.prefix)
+			if target != tt.expectedTarget {
+				t.Errorf("expected %s, got %s for target", tt.expectedTarget, target)
+			}
+		})
+	}
+}
+
+func setTop(t *testing.T, dir string) func() {
+	curDir, err := os.Getwd()
+	if err != nil {
+		t.Fatalf("failed to get current directory: %v", err)
+	}
+	if err := os.Chdir(dir); err != nil {
+		t.Fatalf("failed to change directory to top dir %s: %v", dir, err)
+	}
+	return func() { os.Chdir(curDir) }
+}
+
+func createBuildFiles(t *testing.T, topDir string, buildFiles []string) {
+	for _, buildFile := range buildFiles {
+		buildFile = filepath.Join(topDir, buildFile)
+		if err := ioutil.WriteFile(buildFile, []byte{}, 0644); err != nil {
+			t.Errorf("failed to create file %s: %v", buildFile, err)
+		}
+	}
+}
+
+func createDirectories(t *testing.T, topDir string, dirs []string) {
+	for _, dir := range dirs {
+		dir = filepath.Join(topDir, dir)
+		if err := os.MkdirAll(dir, 0755); err != nil {
+			t.Errorf("failed to create %s directory: %v", dir, err)
+		}
+	}
+}
+
+func TestConfigGetTargets(t *testing.T) {
+	ctx := testContext()
+	tests := []struct {
+		// ********* Setup *********
+		// Test description.
+		description string
+
+		// Directories that exist in the source tree.
+		dirsInTrees []string
+
+		// Build files that exists in the source tree.
+		buildFiles []string
+
+		// ********* Action *********
+		// Directories passed in to soong_ui.
+		dirs []string
+
+		// Current directory that the user executed the build action command.
+		curDir string
+
+		// ********* Validation *********
+		// Expected targets from the function.
+		expectedTargets []string
+
+		// Expected build from the build system.
+		expectedBuildFiles []string
+
+		// Expecting error from running test case.
+		errStr string
+	}{{
+		description:        "one target dir specified",
+		dirsInTrees:        []string{"0/1/2/3"},
+		buildFiles:         []string{"0/1/2/3/Android.bp"},
+		dirs:               []string{"1/2/3"},
+		curDir:             "0",
+		expectedTargets:    []string{"MODULES-IN-0-1-2-3"},
+		expectedBuildFiles: []string{"0/1/2/3/Android.mk"},
+	}, {
+		description: "one target dir specified, build file does not exist",
+		dirsInTrees: []string{"0/1/2/3"},
+		buildFiles:  []string{},
+		dirs:        []string{"1/2/3"},
+		curDir:      "0",
+		errStr:      "Build file not found for 0/1/2/3 directory",
+	}, {
+		description: "one target dir specified, invalid targets specified",
+		dirsInTrees: []string{"0/1/2/3"},
+		buildFiles:  []string{},
+		dirs:        []string{"1/2/3:t1:t2"},
+		curDir:      "0",
+		errStr:      "1/2/3:t1:t2 not in proper directory:target1,target2,... format (\":\" was specified more than once)",
+	}, {
+		description:        "one target dir specified, no targets specified but has colon",
+		dirsInTrees:        []string{"0/1/2/3"},
+		buildFiles:         []string{"0/1/2/3/Android.bp"},
+		dirs:               []string{"1/2/3:"},
+		curDir:             "0",
+		expectedTargets:    []string{"MODULES-IN-0-1-2-3"},
+		expectedBuildFiles: []string{"0/1/2/3/Android.mk"},
+	}, {
+		description:        "one target dir specified, two targets specified",
+		dirsInTrees:        []string{"0/1/2/3"},
+		buildFiles:         []string{"0/1/2/3/Android.bp"},
+		dirs:               []string{"1/2/3:t1,t2"},
+		curDir:             "0",
+		expectedTargets:    []string{"t1", "t2"},
+		expectedBuildFiles: []string{"0/1/2/3/Android.mk"},
+	}, {
+		description: "one target dir specified, no targets and has a comma",
+		dirsInTrees: []string{"0/1/2/3"},
+		buildFiles:  []string{"0/1/2/3/Android.bp"},
+		dirs:        []string{"1/2/3:,"},
+		curDir:      "0",
+		errStr:      "0/1/2/3 not in proper directory:target1,target2,... format",
+	}, {
+		description: "one target dir specified, improper targets defined",
+		dirsInTrees: []string{"0/1/2/3"},
+		buildFiles:  []string{"0/1/2/3/Android.bp"},
+		dirs:        []string{"1/2/3:,t1"},
+		curDir:      "0",
+		errStr:      "0/1/2/3 not in proper directory:target1,target2,... format",
+	}, {
+		description: "one target dir specified, blank target",
+		dirsInTrees: []string{"0/1/2/3"},
+		buildFiles:  []string{"0/1/2/3/Android.bp"},
+		dirs:        []string{"1/2/3:t1,"},
+		curDir:      "0",
+		errStr:      "0/1/2/3 not in proper directory:target1,target2,... format",
+	}, {
+		description:        "one target dir specified, many targets specified",
+		dirsInTrees:        []string{"0/1/2/3"},
+		buildFiles:         []string{"0/1/2/3/Android.bp"},
+		dirs:               []string{"1/2/3:t1,t2,t3,t4,t5,t6,t7,t8,t9,t10"},
+		curDir:             "0",
+		expectedTargets:    []string{"t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "t10"},
+		expectedBuildFiles: []string{"0/1/2/3/Android.mk"},
+	}, {
+		description: "one target dir specified, one target specified, build file does not exist",
+		dirsInTrees: []string{"0/1/2/3"},
+		buildFiles:  []string{},
+		dirs:        []string{"1/2/3:t1"},
+		curDir:      "0",
+		errStr:      "Build file not found for 0/1/2/3 directory",
+	}, {
+		description: "one target dir specified, one target specified, build file not in target dir",
+		dirsInTrees: []string{"0/1/2/3"},
+		buildFiles:  []string{"0/1/2/Android.mk"},
+		dirs:        []string{"1/2/3:t1"},
+		curDir:      "0",
+		errStr:      "Couldn't locate a build file from 0/1/2/3 directory",
+	}, {
+		description:        "one target dir specified, build file not in target dir",
+		dirsInTrees:        []string{"0/1/2/3"},
+		buildFiles:         []string{"0/1/2/Android.mk"},
+		dirs:               []string{"1/2/3"},
+		curDir:             "0",
+		expectedTargets:    []string{"MODULES-IN-0-1-2"},
+		expectedBuildFiles: []string{"0/1/2/Android.mk"},
+	}, {
+		description:        "multiple targets dir specified, targets specified",
+		dirsInTrees:        []string{"0/1/2/3", "0/3/4"},
+		buildFiles:         []string{"0/1/2/3/Android.bp", "0/3/4/Android.mk"},
+		dirs:               []string{"1/2/3:t1,t2", "3/4:t3,t4,t5"},
+		curDir:             "0",
+		expectedTargets:    []string{"t1", "t2", "t3", "t4", "t5"},
+		expectedBuildFiles: []string{"0/1/2/3/Android.mk", "0/3/4/Android.mk"},
+	}, {
+		description:        "multiple targets dir specified, one directory has targets specified",
+		dirsInTrees:        []string{"0/1/2/3", "0/3/4"},
+		buildFiles:         []string{"0/1/2/3/Android.bp", "0/3/4/Android.mk"},
+		dirs:               []string{"1/2/3:t1,t2", "3/4"},
+		curDir:             "0",
+		expectedTargets:    []string{"t1", "t2", "MODULES-IN-0-3-4"},
+		expectedBuildFiles: []string{"0/1/2/3/Android.mk", "0/3/4/Android.mk"},
+	}, {
+		description: "two dirs specified, only one dir exist",
+		dirsInTrees: []string{"0/1/2/3"},
+		buildFiles:  []string{"0/1/2/3/Android.mk"},
+		dirs:        []string{"1/2/3:t1", "3/4"},
+		curDir:      "0",
+		errStr:      "couldn't find directory 0/3/4",
+	}, {
+		description:        "multiple targets dirs specified at root source tree",
+		dirsInTrees:        []string{"0/1/2/3", "0/3/4"},
+		buildFiles:         []string{"0/1/2/3/Android.bp", "0/3/4/Android.mk"},
+		dirs:               []string{"0/1/2/3:t1,t2", "0/3/4"},
+		curDir:             ".",
+		expectedTargets:    []string{"t1", "t2", "MODULES-IN-0-3-4"},
+		expectedBuildFiles: []string{"0/1/2/3/Android.mk", "0/3/4/Android.mk"},
+	}, {
+		description: "no directories specified",
+		dirsInTrees: []string{"0/1/2/3", "0/3/4"},
+		buildFiles:  []string{"0/1/2/3/Android.bp", "0/3/4/Android.mk"},
+		dirs:        []string{},
+		curDir:      ".",
+	}}
+	for _, tt := range tests {
+		t.Run(tt.description, func(t *testing.T) {
+			defer logger.Recover(func(err error) {
+				if tt.errStr == "" {
+					t.Fatalf("Got unexpected error: %v", err)
+				}
+				if tt.errStr != err.Error() {
+					t.Errorf("expected %s, got %s", tt.errStr, err.Error())
+				}
+			})
+
+			// Create the root source tree.
+			topDir, err := ioutil.TempDir("", "")
+			if err != nil {
+				t.Fatalf("failed to create temp dir: %v", err)
+			}
+			defer os.RemoveAll(topDir)
+
+			createDirectories(t, topDir, tt.dirsInTrees)
+			createBuildFiles(t, topDir, tt.buildFiles)
+			r := setTop(t, topDir)
+			defer r()
+
+			targets, buildFiles := getTargetsFromDirs(ctx, tt.curDir, tt.dirs, "MODULES-IN-")
+			if !reflect.DeepEqual(targets, tt.expectedTargets) {
+				t.Errorf("expected %v, got %v for targets", tt.expectedTargets, targets)
+			}
+			if !reflect.DeepEqual(buildFiles, tt.expectedBuildFiles) {
+				t.Errorf("expected %v, got %v for build files", tt.expectedBuildFiles, buildFiles)
+			}
+
+			// If the execution reached here and there was an expected error code, the unit test case failed.
+			if tt.errStr != "" {
+				t.Errorf("expecting error %s", tt.errStr)
+			}
+		})
+	}
+}
+
+func TestConfigFindBuildFile(t *testing.T) {
+	ctx := testContext()
+
+	tests := []struct {
+		// ********* Setup *********
+		// Test description.
+		description string
+
+		// Array of build files to create in dir.
+		buildFiles []string
+
+		// ********* Action *********
+		// Directory to create, also the base directory is where findBuildFile is invoked.
+		dir string
+
+		// ********* Validation *********
+		// Expected build file path to find.
+		expectedBuildFile string
+	}{{
+		description:       "build file exists at leaf directory",
+		buildFiles:        []string{"1/2/3/Android.bp"},
+		dir:               "1/2/3",
+		expectedBuildFile: "1/2/3/Android.mk",
+	}, {
+		description:       "build file exists in all directory paths",
+		buildFiles:        []string{"1/Android.mk", "1/2/Android.mk", "1/2/3/Android.mk"},
+		dir:               "1/2/3",
+		expectedBuildFile: "1/2/3/Android.mk",
+	}, {
+		description:       "build file does not exist in all directory paths",
+		buildFiles:        []string{},
+		dir:               "1/2/3",
+		expectedBuildFile: "",
+	}, {
+		description:       "build file exists only at top directory",
+		buildFiles:        []string{"Android.bp"},
+		dir:               "1/2/3",
+		expectedBuildFile: "",
+	}, {
+		description:       "build file exist in a subdirectory",
+		buildFiles:        []string{"1/2/Android.bp"},
+		dir:               "1/2/3",
+		expectedBuildFile: "1/2/Android.mk",
+	}, {
+		description:       "build file exists in a subdirectory",
+		buildFiles:        []string{"1/Android.mk"},
+		dir:               "1/2/3",
+		expectedBuildFile: "1/Android.mk",
+	}, {
+		description:       "top directory",
+		buildFiles:        []string{"Android.bp"},
+		dir:               ".",
+		expectedBuildFile: "",
+	}}
+
+	for _, tt := range tests {
+		t.Run(tt.description, func(t *testing.T) {
+			defer logger.Recover(func(err error) {
+				t.Fatalf("Got unexpected error: %v", err)
+			})
+
+			topDir, err := ioutil.TempDir("", "")
+			if err != nil {
+				t.Fatalf("failed to create temp dir: %v", err)
+			}
+			defer os.RemoveAll(topDir)
+
+			if tt.dir != "" {
+				createDirectories(t, topDir, []string{tt.dir})
+			}
+
+			createBuildFiles(t, topDir, tt.buildFiles)
+
+			curDir, err := os.Getwd()
+			if err != nil {
+				t.Fatalf("Could not get working directory: %v", err)
+			}
+			defer func() { os.Chdir(curDir) }()
+			if err := os.Chdir(topDir); err != nil {
+				t.Fatalf("Could not change top dir to %s: %v", topDir, err)
+			}
+
+			buildFile := findBuildFile(ctx, tt.dir)
+			if buildFile != tt.expectedBuildFile {
+				t.Errorf("expected %q, got %q for build file", tt.expectedBuildFile, buildFile)
+			}
+		})
+	}
+}
+
+func TestConfigSplitArgs(t *testing.T) {
+	tests := []struct {
+		// ********* Setup *********
+		// Test description.
+		description string
+
+		// ********* Action *********
+		// Arguments passed in to soong_ui.
+		args []string
+
+		// ********* Validation *********
+		// Expected newArgs list after extracting the directories.
+		expectedNewArgs []string
+
+		// Expected directories
+		expectedDirs []string
+	}{{
+		description:     "flags but no directories specified",
+		args:            []string{"showcommands", "-j", "-k"},
+		expectedNewArgs: []string{"showcommands", "-j", "-k"},
+		expectedDirs:    []string{},
+	}, {
+		description:     "flags and one directory specified",
+		args:            []string{"snod", "-j", "dir:target1,target2"},
+		expectedNewArgs: []string{"snod", "-j"},
+		expectedDirs:    []string{"dir:target1,target2"},
+	}, {
+		description:     "flags and directories specified",
+		args:            []string{"dist", "-k", "dir1", "dir2:target1,target2"},
+		expectedNewArgs: []string{"dist", "-k"},
+		expectedDirs:    []string{"dir1", "dir2:target1,target2"},
+	}, {
+		description:     "only directories specified",
+		args:            []string{"dir1", "dir2", "dir3:target1,target2"},
+		expectedNewArgs: []string{},
+		expectedDirs:    []string{"dir1", "dir2", "dir3:target1,target2"},
+	}}
+	for _, tt := range tests {
+		t.Run(tt.description, func(t *testing.T) {
+			args, dirs := splitArgs(tt.args)
+			if !reflect.DeepEqual(tt.expectedNewArgs, args) {
+				t.Errorf("expected %v, got %v for arguments", tt.expectedNewArgs, args)
+			}
+			if !reflect.DeepEqual(tt.expectedDirs, dirs) {
+				t.Errorf("expected %v, got %v for directories", tt.expectedDirs, dirs)
+			}
+		})
+	}
+}
+
+type envVar struct {
+	name  string
+	value string
+}
+
+type buildActionTestCase struct {
+	// ********* Setup *********
+	// Test description.
+	description string
+
+	// Directories that exist in the source tree.
+	dirsInTrees []string
+
+	// Build files that exists in the source tree.
+	buildFiles []string
+
+	// ********* Action *********
+	// Arguments passed in to soong_ui.
+	args []string
+
+	// Directory where the build action was invoked.
+	curDir string
+
+	// WITH_TIDY_ONLY environment variable specified.
+	tidyOnly string
+
+	// ********* Validation *********
+	// Expected arguments to be in Config instance.
+	expectedArgs []string
+
+	// Expected environment variables to be set.
+	expectedEnvVars []envVar
+}
+
+func testGetConfigArgs(t *testing.T, tt buildActionTestCase, action BuildAction, buildDependencies bool) {
+	ctx := testContext()
+
+	// Environment variables to set it to blank on every test case run.
+	resetEnvVars := []string{
+		"ONE_SHOT_MAKEFILE",
+		"WITH_TIDY_ONLY",
+	}
+
+	for _, name := range resetEnvVars {
+		if err := os.Unsetenv(name); err != nil {
+			t.Fatalf("failed to unset environment variable %s: %v", name, err)
+		}
+	}
+	if tt.tidyOnly != "" {
+		if err := os.Setenv("WITH_TIDY_ONLY", tt.tidyOnly); err != nil {
+			t.Errorf("failed to set WITH_TIDY_ONLY to %s: %v", tt.tidyOnly, err)
+		}
+	}
+
+	// Create the root source tree.
+	topDir, err := ioutil.TempDir("", "")
+	if err != nil {
+		t.Fatalf("failed to create temp dir: %v", err)
+	}
+	defer os.RemoveAll(topDir)
+
+	createDirectories(t, topDir, tt.dirsInTrees)
+	createBuildFiles(t, topDir, tt.buildFiles)
+
+	r := setTop(t, topDir)
+	defer r()
+
+	// The next block is to create the root build file.
+	rootBuildFileDir := filepath.Dir(srcDirFileCheck)
+	if err := os.MkdirAll(rootBuildFileDir, 0755); err != nil {
+		t.Fatalf("Failed to create %s directory: %v", rootBuildFileDir, err)
+	}
+
+	if err := ioutil.WriteFile(srcDirFileCheck, []byte{}, 0644); err != nil {
+		t.Fatalf("failed to create %s file: %v", srcDirFileCheck, err)
+	}
+
+	args := getConfigArgs(action, tt.curDir, buildDependencies, ctx, tt.args)
+	if !reflect.DeepEqual(tt.expectedArgs, args) {
+		t.Fatalf("expected %v, got %v for config arguments", tt.expectedArgs, args)
+	}
+
+	for _, env := range tt.expectedEnvVars {
+		if val := os.Getenv(env.name); val != env.value {
+			t.Errorf("expecting %s, got %s for environment variable %s", env.value, val, env.name)
+		}
+	}
+}
+
+// TODO: Remove this test case once mm shell build command has been deprecated.
+func TestGetConfigArgsBuildModulesInDirecotoryNoDeps(t *testing.T) {
+	tests := []buildActionTestCase{{
+		description:  "normal execution in a directory",
+		dirsInTrees:  []string{"0/1/2"},
+		buildFiles:   []string{"0/1/2/Android.mk"},
+		args:         []string{"-j", "-k", "showcommands", "fake-module"},
+		curDir:       "0/1/2",
+		tidyOnly:     "",
+		expectedArgs: []string{"-j", "-k", "showcommands", "fake-module", "MODULES-IN-0-1-2"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/2/Android.mk"}},
+	}, {
+		description:  "makefile in parent directory",
+		dirsInTrees:  []string{"0/1/2"},
+		buildFiles:   []string{"0/1/Android.mk"},
+		args:         []string{},
+		curDir:       "0/1/2",
+		tidyOnly:     "",
+		expectedArgs: []string{"MODULES-IN-0-1"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/Android.mk"}},
+	}, {
+		description:  "build file not found",
+		dirsInTrees:  []string{"0/1/2"},
+		buildFiles:   []string{},
+		args:         []string{},
+		curDir:       "0/1/2",
+		tidyOnly:     "",
+		expectedArgs: []string{"MODULES-IN-0-1-2"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/2/Android.mk"}},
+	}, {
+		description:  "build action executed at root directory",
+		dirsInTrees:  []string{},
+		buildFiles:   []string{},
+		args:         []string{},
+		curDir:       ".",
+		tidyOnly:     "",
+		expectedArgs: []string{},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: ""}},
+	}, {
+		description:  "GET-INSTALL-PATH specified,",
+		dirsInTrees:  []string{"0/1/2"},
+		buildFiles:   []string{"0/1/Android.mk"},
+		args:         []string{"GET-INSTALL-PATH"},
+		curDir:       "0/1/2",
+		tidyOnly:     "",
+		expectedArgs: []string{"GET-INSTALL-PATH-IN-0-1"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/Android.mk"}},
+	}, {
+		description:  "tidy only environment variable specified,",
+		dirsInTrees:  []string{"0/1/2"},
+		buildFiles:   []string{"0/1/Android.mk"},
+		args:         []string{"GET-INSTALL-PATH"},
+		curDir:       "0/1/2",
+		tidyOnly:     "true",
+		expectedArgs: []string{"tidy_only"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/Android.mk"}},
+	}}
+	for _, tt := range tests {
+		t.Run("build action BUILD_MODULES_IN_DIR without their dependencies, "+tt.description, func(t *testing.T) {
+			testGetConfigArgs(t, tt, BUILD_MODULES_IN_A_DIRECTORY, false)
+		})
+	}
+}
+
+func TestGetConfigArgsBuildModulesInDirectory(t *testing.T) {
+	tests := []buildActionTestCase{{
+		description:     "normal execution in a directory",
+		dirsInTrees:     []string{"0/1/2"},
+		buildFiles:      []string{"0/1/2/Android.mk"},
+		args:            []string{"fake-module"},
+		curDir:          "0/1/2",
+		tidyOnly:        "",
+		expectedArgs:    []string{"fake-module", "MODULES-IN-0-1-2"},
+		expectedEnvVars: []envVar{},
+	}, {
+		description:     "build file in parent directory",
+		dirsInTrees:     []string{"0/1/2"},
+		buildFiles:      []string{"0/1/Android.mk"},
+		args:            []string{},
+		curDir:          "0/1/2",
+		tidyOnly:        "",
+		expectedArgs:    []string{"MODULES-IN-0-1"},
+		expectedEnvVars: []envVar{},
+	},
+		{
+			description:     "build file in parent directory, multiple module names passed in",
+			dirsInTrees:     []string{"0/1/2"},
+			buildFiles:      []string{"0/1/Android.mk"},
+			args:            []string{"fake-module1", "fake-module2", "fake-module3"},
+			curDir:          "0/1/2",
+			tidyOnly:        "",
+			expectedArgs:    []string{"fake-module1", "fake-module2", "fake-module3", "MODULES-IN-0-1"},
+			expectedEnvVars: []envVar{},
+		}, {
+			description:     "build file in 2nd level parent directory",
+			dirsInTrees:     []string{"0/1/2"},
+			buildFiles:      []string{"0/Android.bp"},
+			args:            []string{},
+			curDir:          "0/1/2",
+			tidyOnly:        "",
+			expectedArgs:    []string{"MODULES-IN-0"},
+			expectedEnvVars: []envVar{},
+		}, {
+			description:     "build action executed at root directory",
+			dirsInTrees:     []string{},
+			buildFiles:      []string{},
+			args:            []string{},
+			curDir:          ".",
+			tidyOnly:        "",
+			expectedArgs:    []string{},
+			expectedEnvVars: []envVar{},
+		}, {
+			description:     "build file not found - no error is expected to return",
+			dirsInTrees:     []string{"0/1/2"},
+			buildFiles:      []string{},
+			args:            []string{},
+			curDir:          "0/1/2",
+			tidyOnly:        "",
+			expectedArgs:    []string{"MODULES-IN-0-1-2"},
+			expectedEnvVars: []envVar{},
+		}, {
+			description:     "GET-INSTALL-PATH specified,",
+			dirsInTrees:     []string{"0/1/2"},
+			buildFiles:      []string{"0/1/Android.mk"},
+			args:            []string{"GET-INSTALL-PATH", "-j", "-k", "GET-INSTALL-PATH"},
+			curDir:          "0/1/2",
+			tidyOnly:        "",
+			expectedArgs:    []string{"-j", "-k", "GET-INSTALL-PATH-IN-0-1"},
+			expectedEnvVars: []envVar{},
+		}, {
+			description:     "tidy only environment variable specified,",
+			dirsInTrees:     []string{"0/1/2"},
+			buildFiles:      []string{"0/1/Android.mk"},
+			args:            []string{"GET-INSTALL-PATH"},
+			curDir:          "0/1/2",
+			tidyOnly:        "true",
+			expectedArgs:    []string{"tidy_only"},
+			expectedEnvVars: []envVar{},
+		}, {
+			description:     "normal execution in root directory with args",
+			dirsInTrees:     []string{},
+			buildFiles:      []string{},
+			args:            []string{"-j", "-k", "fake_module"},
+			curDir:          "",
+			tidyOnly:        "",
+			expectedArgs:    []string{"-j", "-k", "fake_module"},
+			expectedEnvVars: []envVar{},
+		}}
+	for _, tt := range tests {
+		t.Run("build action BUILD_MODULES_IN_DIR, "+tt.description, func(t *testing.T) {
+			testGetConfigArgs(t, tt, BUILD_MODULES_IN_A_DIRECTORY, true)
+		})
+	}
+}
+
+// TODO: Remove this test case once mmm shell build command has been deprecated.
+func TestGetConfigArgsBuildModulesInDirectoriesNoDeps(t *testing.T) {
+	tests := []buildActionTestCase{{
+		description:  "normal execution in a directory",
+		dirsInTrees:  []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/2/3.3"},
+		buildFiles:   []string{"0/1/2/3.1/Android.bp", "0/1/2/3.2/Android.bp", "0/1/2/3.3/Android.bp"},
+		args:         []string{"3.1/:t1,t2", "3.2/:t3,t4", "3.3/:t5,t6"},
+		curDir:       "0/1/2",
+		tidyOnly:     "",
+		expectedArgs: []string{"t1", "t2", "t3", "t4", "t5", "t6"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/2/3.1/Android.mk 0/1/2/3.2/Android.mk 0/1/2/3.3/Android.mk"}},
+	}, {
+		description:  "GET-INSTALL-PATH specified",
+		dirsInTrees:  []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/2/3.3"},
+		buildFiles:   []string{"0/1/2/3.1/Android.bp", "0/1/2/3.2/Android.bp", "0/1/2/3.3/Android.bp"},
+		args:         []string{"GET-INSTALL-PATH", "3.1/", "3.2/", "3.3/:t6"},
+		curDir:       "0/1/2",
+		tidyOnly:     "",
+		expectedArgs: []string{"GET-INSTALL-PATH-IN-0-1-2-3.1", "GET-INSTALL-PATH-IN-0-1-2-3.2", "t6"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/2/3.1/Android.mk 0/1/2/3.2/Android.mk 0/1/2/3.3/Android.mk"}},
+	}, {
+		description:  "tidy only environment variable specified",
+		dirsInTrees:  []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/2/3.3"},
+		buildFiles:   []string{"0/1/2/3.1/Android.bp", "0/1/2/3.2/Android.bp", "0/1/2/3.3/Android.bp"},
+		args:         []string{"GET-INSTALL-PATH", "3.1/", "3.2/", "3.3/:t6"},
+		curDir:       "0/1/2",
+		tidyOnly:     "1",
+		expectedArgs: []string{"tidy_only"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/2/3.1/Android.mk 0/1/2/3.2/Android.mk 0/1/2/3.3/Android.mk"}},
+	}, {
+		description:  "normal execution from top dir directory",
+		dirsInTrees:  []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/2/3.3"},
+		buildFiles:   []string{"0/1/2/3.1/Android.bp", "0/1/2/3.2/Android.bp", "0/1/2/3.3/Android.bp"},
+		args:         []string{"0/1/2/3.1", "0/1/2/3.2/:t3,t4", "0/1/2/3.3/:t5,t6"},
+		curDir:       ".",
+		tidyOnly:     "",
+		expectedArgs: []string{"MODULES-IN-0-1-2-3.1", "t3", "t4", "t5", "t6"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: "0/1/2/3.1/Android.mk 0/1/2/3.2/Android.mk 0/1/2/3.3/Android.mk"}},
+	}}
+	for _, tt := range tests {
+		t.Run("build action BUILD_MODULES_IN_DIRS_NO_DEPS, "+tt.description, func(t *testing.T) {
+			testGetConfigArgs(t, tt, BUILD_MODULES_IN_DIRECTORIES, false)
+		})
+	}
+}
+
+func TestGetConfigArgsBuildModulesInDirectories(t *testing.T) {
+	tests := []buildActionTestCase{{
+		description:  "normal execution in a directory",
+		dirsInTrees:  []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/2/3.3"},
+		buildFiles:   []string{"0/1/2/3.1/Android.bp", "0/1/2/3.2/Android.bp", "0/1/2/3.3/Android.bp"},
+		args:         []string{"3.1/", "3.2/", "3.3/"},
+		curDir:       "0/1/2",
+		tidyOnly:     "",
+		expectedArgs: []string{"MODULES-IN-0-1-2-3.1", "MODULES-IN-0-1-2-3.2", "MODULES-IN-0-1-2-3.3"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: ""}},
+	}, {
+		description:  "GET-INSTALL-PATH specified",
+		dirsInTrees:  []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/3"},
+		buildFiles:   []string{"0/1/2/3.1/Android.bp", "0/1/2/3.2/Android.bp", "0/1/Android.bp"},
+		args:         []string{"GET-INSTALL-PATH", "2/3.1/", "2/3.2", "3"},
+		curDir:       "0/1",
+		tidyOnly:     "",
+		expectedArgs: []string{"GET-INSTALL-PATH-IN-0-1-2-3.1", "GET-INSTALL-PATH-IN-0-1-2-3.2", "GET-INSTALL-PATH-IN-0-1"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: ""}},
+	}, {
+		description:  "tidy only environment variable specified",
+		dirsInTrees:  []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/2/3.3"},
+		buildFiles:   []string{"0/1/2/3.1/Android.bp", "0/1/2/3.2/Android.bp", "0/1/2/3.3/Android.bp"},
+		args:         []string{"GET-INSTALL-PATH", "3.1/", "3.2/", "3.3"},
+		curDir:       "0/1/2",
+		tidyOnly:     "1",
+		expectedArgs: []string{"tidy_only"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: ""}},
+	}, {
+		description:  "normal execution from top dir directory",
+		dirsInTrees:  []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/3", "0/2"},
+		buildFiles:   []string{"0/1/2/3.1/Android.bp", "0/1/2/3.2/Android.bp", "0/1/3/Android.bp", "0/2/Android.bp"},
+		args:         []string{"0/1/2/3.1", "0/1/2/3.2", "0/1/3", "0/2"},
+		curDir:       ".",
+		tidyOnly:     "",
+		expectedArgs: []string{"MODULES-IN-0-1-2-3.1", "MODULES-IN-0-1-2-3.2", "MODULES-IN-0-1-3", "MODULES-IN-0-2"},
+		expectedEnvVars: []envVar{
+			envVar{
+				name:  "ONE_SHOT_MAKEFILE",
+				value: ""}},
+	}}
+	for _, tt := range tests {
+		t.Run("build action BUILD_MODULES_IN_DIRS, "+tt.description, func(t *testing.T) {
+			testGetConfigArgs(t, tt, BUILD_MODULES_IN_DIRECTORIES, true)
+		})
+	}
+}
diff --git a/ui/build/context.go b/ui/build/context.go
index 249e898..7ff98ef 100644
--- a/ui/build/context.go
+++ b/ui/build/context.go
@@ -16,12 +16,12 @@
 
 import (
 	"context"
+	"io"
 
 	"android/soong/ui/logger"
 	"android/soong/ui/metrics"
 	"android/soong/ui/metrics/metrics_proto"
 	"android/soong/ui/status"
-	"android/soong/ui/terminal"
 	"android/soong/ui/tracer"
 )
 
@@ -35,7 +35,7 @@
 
 	Metrics *metrics.Metrics
 
-	Writer terminal.Writer
+	Writer io.Writer
 	Status *status.Status
 
 	Thread tracer.Thread
diff --git a/ui/build/dumpvars.go b/ui/build/dumpvars.go
index 4335667..266130f 100644
--- a/ui/build/dumpvars.go
+++ b/ui/build/dumpvars.go
@@ -249,7 +249,7 @@
 	env := config.Environment()
 	// Print the banner like make does
 	if !env.IsEnvTrue("ANDROID_QUIET_BUILD") {
-		ctx.Writer.Print(Banner(make_vars))
+		fmt.Fprintln(ctx.Writer, Banner(make_vars))
 	}
 
 	// Populate the environment
diff --git a/ui/build/paths/config.go b/ui/build/paths/config.go
index 54006d2..a50a880 100644
--- a/ui/build/paths/config.go
+++ b/ui/build/paths/config.go
@@ -79,7 +79,6 @@
 	// We need bzip2 here even though we provide a bzip2 binary because
 	// GNU tar seems to avoid calling ours.
 	"bzip2":    Allowed,
-	"date":     Allowed,
 	"dd":       Allowed,
 	"diff":     Allowed,
 	"egrep":    Allowed,
@@ -132,6 +131,7 @@
 	"cp":        LinuxOnlyPrebuilt,
 	"comm":      LinuxOnlyPrebuilt,
 	"cut":       LinuxOnlyPrebuilt,
+	"date":      LinuxOnlyPrebuilt,
 	"dirname":   LinuxOnlyPrebuilt,
 	"du":        LinuxOnlyPrebuilt,
 	"echo":      LinuxOnlyPrebuilt,
diff --git a/ui/build/util.go b/ui/build/util.go
index 0676a86..75e6753 100644
--- a/ui/build/util.go
+++ b/ui/build/util.go
@@ -44,6 +44,17 @@
 	return indexList(s, list) != -1
 }
 
+// removeFromlist removes all occurrences of the string in list.
+func removeFromList(s string, list []string) []string {
+	filteredList := make([]string, 0, len(list))
+	for _, ls := range list {
+		if s != ls {
+			filteredList = append(filteredList, ls)
+		}
+	}
+	return filteredList
+}
+
 // ensureDirectoriesExist is a shortcut to os.MkdirAll, sending errors to the ctx logger.
 func ensureDirectoriesExist(ctx Context, dirs ...string) {
 	for _, dir := range dirs {
diff --git a/ui/status/log.go b/ui/status/log.go
index 921aa44..7badac7 100644
--- a/ui/status/log.go
+++ b/ui/status/log.go
@@ -71,6 +71,11 @@
 	fmt.Fprintf(v.w, "%s%s\n", level.Prefix(), message)
 }
 
+func (v *verboseLog) Write(p []byte) (int, error) {
+	fmt.Fprint(v.w, string(p))
+	return len(p), nil
+}
+
 type errorLog struct {
 	w io.WriteCloser
 
@@ -134,3 +139,8 @@
 
 	fmt.Fprintf(e.w, "error: %s\n", message)
 }
+
+func (e *errorLog) Write(p []byte) (int, error) {
+	fmt.Fprint(e.w, string(p))
+	return len(p), nil
+}
diff --git a/ui/status/status.go b/ui/status/status.go
index 46ec72e..3d8cd7a 100644
--- a/ui/status/status.go
+++ b/ui/status/status.go
@@ -173,6 +173,9 @@
 	// Flush is called when your outputs should be flushed / closed. No
 	// output is expected after this call.
 	Flush()
+
+	// Write lets StatusOutput implement io.Writer
+	Write(p []byte) (n int, err error)
 }
 
 // Status is the multiplexer / accumulator between ToolStatus instances (via
diff --git a/ui/status/status_test.go b/ui/status/status_test.go
index e62785f..9494582 100644
--- a/ui/status/status_test.go
+++ b/ui/status/status_test.go
@@ -27,6 +27,11 @@
 func (c counterOutput) Message(level MsgLevel, msg string) {}
 func (c counterOutput) Flush()                             {}
 
+func (c counterOutput) Write(p []byte) (int, error) {
+	// Discard writes
+	return len(p), nil
+}
+
 func (c counterOutput) Expect(t *testing.T, counts Counts) {
 	if Counts(c) == counts {
 		return
diff --git a/ui/terminal/Android.bp b/ui/terminal/Android.bp
index 7104a50..b533b0d 100644
--- a/ui/terminal/Android.bp
+++ b/ui/terminal/Android.bp
@@ -17,11 +17,15 @@
     pkgPath: "android/soong/ui/terminal",
     deps: ["soong-ui-status"],
     srcs: [
+        "dumb_status.go",
+        "format.go",
+        "smart_status.go",
         "status.go",
-        "writer.go",
+        "stdio.go",
         "util.go",
     ],
     testSrcs: [
+        "status_test.go",
         "util_test.go",
     ],
     darwin: {
diff --git a/ui/terminal/dumb_status.go b/ui/terminal/dumb_status.go
new file mode 100644
index 0000000..201770f
--- /dev/null
+++ b/ui/terminal/dumb_status.go
@@ -0,0 +1,71 @@
+// Copyright 2019 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+	"fmt"
+	"io"
+
+	"android/soong/ui/status"
+)
+
+type dumbStatusOutput struct {
+	writer    io.Writer
+	formatter formatter
+}
+
+// NewDumbStatusOutput returns a StatusOutput that represents the
+// current build status similarly to Ninja's built-in terminal
+// output.
+func NewDumbStatusOutput(w io.Writer, formatter formatter) status.StatusOutput {
+	return &dumbStatusOutput{
+		writer:    w,
+		formatter: formatter,
+	}
+}
+
+func (s *dumbStatusOutput) Message(level status.MsgLevel, message string) {
+	if level >= status.StatusLvl {
+		fmt.Fprintln(s.writer, s.formatter.message(level, message))
+	}
+}
+
+func (s *dumbStatusOutput) StartAction(action *status.Action, counts status.Counts) {
+}
+
+func (s *dumbStatusOutput) FinishAction(result status.ActionResult, counts status.Counts) {
+	str := result.Description
+	if str == "" {
+		str = result.Command
+	}
+
+	progress := s.formatter.progress(counts) + str
+
+	output := s.formatter.result(result)
+	output = string(stripAnsiEscapes([]byte(output)))
+
+	if output != "" {
+		fmt.Fprint(s.writer, progress, "\n", output)
+	} else {
+		fmt.Fprintln(s.writer, progress)
+	}
+}
+
+func (s *dumbStatusOutput) Flush() {}
+
+func (s *dumbStatusOutput) Write(p []byte) (int, error) {
+	fmt.Fprint(s.writer, string(p))
+	return len(p), nil
+}
diff --git a/ui/terminal/format.go b/ui/terminal/format.go
new file mode 100644
index 0000000..4205bdc
--- /dev/null
+++ b/ui/terminal/format.go
@@ -0,0 +1,123 @@
+// Copyright 2019 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+	"fmt"
+	"strings"
+	"time"
+
+	"android/soong/ui/status"
+)
+
+type formatter struct {
+	format string
+	quiet  bool
+	start  time.Time
+}
+
+// newFormatter returns a formatter for formatting output to
+// the terminal in a format similar to Ninja.
+// format takes nearly all the same options as NINJA_STATUS.
+// %c is currently unsupported.
+func newFormatter(format string, quiet bool) formatter {
+	return formatter{
+		format: format,
+		quiet:  quiet,
+		start:  time.Now(),
+	}
+}
+
+func (s formatter) message(level status.MsgLevel, message string) string {
+	if level >= status.ErrorLvl {
+		return fmt.Sprintf("FAILED: %s", message)
+	} else if level > status.StatusLvl {
+		return fmt.Sprintf("%s%s", level.Prefix(), message)
+	} else if level == status.StatusLvl {
+		return message
+	}
+	return ""
+}
+
+func (s formatter) progress(counts status.Counts) string {
+	if s.format == "" {
+		return fmt.Sprintf("[%3d%% %d/%d] ", 100*counts.FinishedActions/counts.TotalActions, counts.FinishedActions, counts.TotalActions)
+	}
+
+	buf := &strings.Builder{}
+	for i := 0; i < len(s.format); i++ {
+		c := s.format[i]
+		if c != '%' {
+			buf.WriteByte(c)
+			continue
+		}
+
+		i = i + 1
+		if i == len(s.format) {
+			buf.WriteByte(c)
+			break
+		}
+
+		c = s.format[i]
+		switch c {
+		case '%':
+			buf.WriteByte(c)
+		case 's':
+			fmt.Fprintf(buf, "%d", counts.StartedActions)
+		case 't':
+			fmt.Fprintf(buf, "%d", counts.TotalActions)
+		case 'r':
+			fmt.Fprintf(buf, "%d", counts.RunningActions)
+		case 'u':
+			fmt.Fprintf(buf, "%d", counts.TotalActions-counts.StartedActions)
+		case 'f':
+			fmt.Fprintf(buf, "%d", counts.FinishedActions)
+		case 'o':
+			fmt.Fprintf(buf, "%.1f", float64(counts.FinishedActions)/time.Since(s.start).Seconds())
+		case 'c':
+			// TODO: implement?
+			buf.WriteRune('?')
+		case 'p':
+			fmt.Fprintf(buf, "%3d%%", 100*counts.FinishedActions/counts.TotalActions)
+		case 'e':
+			fmt.Fprintf(buf, "%.3f", time.Since(s.start).Seconds())
+		default:
+			buf.WriteString("unknown placeholder '")
+			buf.WriteByte(c)
+			buf.WriteString("'")
+		}
+	}
+	return buf.String()
+}
+
+func (s formatter) result(result status.ActionResult) string {
+	var ret string
+	if result.Error != nil {
+		targets := strings.Join(result.Outputs, " ")
+		if s.quiet || result.Command == "" {
+			ret = fmt.Sprintf("FAILED: %s\n%s", targets, result.Output)
+		} else {
+			ret = fmt.Sprintf("FAILED: %s\n%s\n%s", targets, result.Command, result.Output)
+		}
+	} else if result.Output != "" {
+		ret = result.Output
+	}
+
+	if len(ret) > 0 && ret[len(ret)-1] != '\n' {
+		ret += "\n"
+	}
+
+	return ret
+}
diff --git a/ui/terminal/smart_status.go b/ui/terminal/smart_status.go
new file mode 100644
index 0000000..8fa9eff
--- /dev/null
+++ b/ui/terminal/smart_status.go
@@ -0,0 +1,158 @@
+// Copyright 2019 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+	"fmt"
+	"io"
+	"strings"
+	"sync"
+
+	"android/soong/ui/status"
+)
+
+type smartStatusOutput struct {
+	writer    io.Writer
+	formatter formatter
+
+	lock sync.Mutex
+
+	haveBlankLine 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{
+		writer:    w,
+		formatter: formatter,
+
+		haveBlankLine: true,
+	}
+}
+
+func (s *smartStatusOutput) Message(level status.MsgLevel, message string) {
+	if level < status.StatusLvl {
+		return
+	}
+
+	str := s.formatter.message(level, message)
+
+	s.lock.Lock()
+	defer s.lock.Unlock()
+
+	if level > status.StatusLvl {
+		s.print(str)
+	} else {
+		s.statusLine(str)
+	}
+}
+
+func (s *smartStatusOutput) StartAction(action *status.Action, counts status.Counts) {
+	str := action.Description
+	if str == "" {
+		str = action.Command
+	}
+
+	progress := s.formatter.progress(counts)
+
+	s.lock.Lock()
+	defer s.lock.Unlock()
+
+	s.statusLine(progress + str)
+}
+
+func (s *smartStatusOutput) FinishAction(result status.ActionResult, counts status.Counts) {
+	str := result.Description
+	if str == "" {
+		str = result.Command
+	}
+
+	progress := s.formatter.progress(counts) + str
+
+	output := s.formatter.result(result)
+
+	s.lock.Lock()
+	defer s.lock.Unlock()
+
+	if output != "" {
+		s.statusLine(progress)
+		s.requestLine()
+		s.print(output)
+	} else {
+		s.statusLine(progress)
+	}
+}
+
+func (s *smartStatusOutput) Flush() {
+	s.lock.Lock()
+	defer s.lock.Unlock()
+
+	s.requestLine()
+}
+
+func (s *smartStatusOutput) Write(p []byte) (int, error) {
+	s.lock.Lock()
+	defer s.lock.Unlock()
+	s.print(string(p))
+	return len(p), nil
+}
+
+func (s *smartStatusOutput) requestLine() {
+	if !s.haveBlankLine {
+		fmt.Fprintln(s.writer)
+		s.haveBlankLine = true
+	}
+}
+
+func (s *smartStatusOutput) print(str string) {
+	if !s.haveBlankLine {
+		fmt.Fprint(s.writer, "\r", "\x1b[K")
+		s.haveBlankLine = true
+	}
+	fmt.Fprint(s.writer, str)
+	if len(str) == 0 || str[len(str)-1] != '\n' {
+		fmt.Fprint(s.writer, "\n")
+	}
+}
+
+func (s *smartStatusOutput) statusLine(str string) {
+	idx := strings.IndexRune(str, '\n')
+	if idx != -1 {
+		str = str[0:idx]
+	}
+
+	// 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]
+		}
+	}
+
+	// Move to the beginning on the line, turn on bold, print the output,
+	// turn off bold, then clear the rest of the line.
+	start := "\r\x1b[1m"
+	end := "\x1b[0m\x1b[K"
+	fmt.Fprint(s.writer, start, str, end)
+	s.haveBlankLine = false
+}
diff --git a/ui/terminal/status.go b/ui/terminal/status.go
index 2445c5b..69a2a09 100644
--- a/ui/terminal/status.go
+++ b/ui/terminal/status.go
@@ -15,131 +15,23 @@
 package terminal
 
 import (
-	"fmt"
-	"strings"
-	"time"
+	"io"
 
 	"android/soong/ui/status"
 )
 
-type statusOutput struct {
-	writer Writer
-	format string
-
-	start time.Time
-	quiet bool
-}
-
 // NewStatusOutput returns a StatusOutput that represents the
 // current build status similarly to Ninja's built-in terminal
 // output.
 //
 // statusFormat takes nearly all the same options as NINJA_STATUS.
 // %c is currently unsupported.
-func NewStatusOutput(w Writer, statusFormat string, quietBuild bool) status.StatusOutput {
-	return &statusOutput{
-		writer: w,
-		format: statusFormat,
+func NewStatusOutput(w io.Writer, statusFormat string, quietBuild bool) status.StatusOutput {
+	formatter := newFormatter(statusFormat, quietBuild)
 
-		start: time.Now(),
-		quiet: quietBuild,
-	}
-}
-
-func (s *statusOutput) Message(level status.MsgLevel, message string) {
-	if level >= status.ErrorLvl {
-		s.writer.Print(fmt.Sprintf("FAILED: %s", message))
-	} else if level > status.StatusLvl {
-		s.writer.Print(fmt.Sprintf("%s%s", level.Prefix(), message))
-	} else if level == status.StatusLvl {
-		s.writer.StatusLine(message)
-	}
-}
-
-func (s *statusOutput) StartAction(action *status.Action, counts status.Counts) {
-	if !s.writer.isSmartTerminal() {
-		return
-	}
-
-	str := action.Description
-	if str == "" {
-		str = action.Command
-	}
-
-	s.writer.StatusLine(s.progress(counts) + str)
-}
-
-func (s *statusOutput) FinishAction(result status.ActionResult, counts status.Counts) {
-	str := result.Description
-	if str == "" {
-		str = result.Command
-	}
-
-	progress := s.progress(counts) + str
-
-	if result.Error != nil {
-		targets := strings.Join(result.Outputs, " ")
-		if s.quiet || result.Command == "" {
-			s.writer.StatusAndMessage(progress, fmt.Sprintf("FAILED: %s\n%s", targets, result.Output))
-		} else {
-			s.writer.StatusAndMessage(progress, fmt.Sprintf("FAILED: %s\n%s\n%s", targets, result.Command, result.Output))
-		}
-	} else if result.Output != "" {
-		s.writer.StatusAndMessage(progress, result.Output)
+	if isSmartTerminal(w) {
+		return NewSmartStatusOutput(w, formatter)
 	} else {
-		s.writer.StatusLine(progress)
+		return NewDumbStatusOutput(w, formatter)
 	}
 }
-
-func (s *statusOutput) Flush() {}
-
-func (s *statusOutput) progress(counts status.Counts) string {
-	if s.format == "" {
-		return fmt.Sprintf("[%3d%% %d/%d] ", 100*counts.FinishedActions/counts.TotalActions, counts.FinishedActions, counts.TotalActions)
-	}
-
-	buf := &strings.Builder{}
-	for i := 0; i < len(s.format); i++ {
-		c := s.format[i]
-		if c != '%' {
-			buf.WriteByte(c)
-			continue
-		}
-
-		i = i + 1
-		if i == len(s.format) {
-			buf.WriteByte(c)
-			break
-		}
-
-		c = s.format[i]
-		switch c {
-		case '%':
-			buf.WriteByte(c)
-		case 's':
-			fmt.Fprintf(buf, "%d", counts.StartedActions)
-		case 't':
-			fmt.Fprintf(buf, "%d", counts.TotalActions)
-		case 'r':
-			fmt.Fprintf(buf, "%d", counts.RunningActions)
-		case 'u':
-			fmt.Fprintf(buf, "%d", counts.TotalActions-counts.StartedActions)
-		case 'f':
-			fmt.Fprintf(buf, "%d", counts.FinishedActions)
-		case 'o':
-			fmt.Fprintf(buf, "%.1f", float64(counts.FinishedActions)/time.Since(s.start).Seconds())
-		case 'c':
-			// TODO: implement?
-			buf.WriteRune('?')
-		case 'p':
-			fmt.Fprintf(buf, "%3d%%", 100*counts.FinishedActions/counts.TotalActions)
-		case 'e':
-			fmt.Fprintf(buf, "%.3f", time.Since(s.start).Seconds())
-		default:
-			buf.WriteString("unknown placeholder '")
-			buf.WriteByte(c)
-			buf.WriteString("'")
-		}
-	}
-	return buf.String()
-}
diff --git a/ui/terminal/status_test.go b/ui/terminal/status_test.go
new file mode 100644
index 0000000..a87a7f0
--- /dev/null
+++ b/ui/terminal/status_test.go
@@ -0,0 +1,272 @@
+// Copyright 2018 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+	"bytes"
+	"fmt"
+	"testing"
+
+	"android/soong/ui/status"
+)
+
+func TestStatusOutput(t *testing.T) {
+	tests := []struct {
+		name  string
+		calls func(stat status.StatusOutput)
+		smart string
+		dumb  string
+	}{
+		{
+			name:  "two actions",
+			calls: twoActions,
+			smart: "\r\x1b[1m[  0% 0/2] action1\x1b[0m\x1b[K\r\x1b[1m[ 50% 1/2] action1\x1b[0m\x1b[K\r\x1b[1m[ 50% 1/2] action2\x1b[0m\x1b[K\r\x1b[1m[100% 2/2] action2\x1b[0m\x1b[K\n",
+			dumb:  "[ 50% 1/2] action1\n[100% 2/2] action2\n",
+		},
+		{
+			name:  "two parallel actions",
+			calls: twoParallelActions,
+			smart: "\r\x1b[1m[  0% 0/2] action1\x1b[0m\x1b[K\r\x1b[1m[  0% 0/2] action2\x1b[0m\x1b[K\r\x1b[1m[ 50% 1/2] action1\x1b[0m\x1b[K\r\x1b[1m[100% 2/2] action2\x1b[0m\x1b[K\n",
+			dumb:  "[ 50% 1/2] action1\n[100% 2/2] action2\n",
+		},
+		{
+			name:  "action with output",
+			calls: actionsWithOutput,
+			smart: "\r\x1b[1m[  0% 0/3] action1\x1b[0m\x1b[K\r\x1b[1m[ 33% 1/3] action1\x1b[0m\x1b[K\r\x1b[1m[ 33% 1/3] action2\x1b[0m\x1b[K\r\x1b[1m[ 66% 2/3] action2\x1b[0m\x1b[K\noutput1\noutput2\n\r\x1b[1m[ 66% 2/3] action3\x1b[0m\x1b[K\r\x1b[1m[100% 3/3] action3\x1b[0m\x1b[K\n",
+			dumb:  "[ 33% 1/3] action1\n[ 66% 2/3] action2\noutput1\noutput2\n[100% 3/3] action3\n",
+		},
+		{
+			name:  "action with output without newline",
+			calls: actionsWithOutputWithoutNewline,
+			smart: "\r\x1b[1m[  0% 0/3] action1\x1b[0m\x1b[K\r\x1b[1m[ 33% 1/3] action1\x1b[0m\x1b[K\r\x1b[1m[ 33% 1/3] action2\x1b[0m\x1b[K\r\x1b[1m[ 66% 2/3] action2\x1b[0m\x1b[K\noutput1\noutput2\n\r\x1b[1m[ 66% 2/3] action3\x1b[0m\x1b[K\r\x1b[1m[100% 3/3] action3\x1b[0m\x1b[K\n",
+			dumb:  "[ 33% 1/3] action1\n[ 66% 2/3] action2\noutput1\noutput2\n[100% 3/3] action3\n",
+		},
+		{
+			name:  "action with error",
+			calls: actionsWithError,
+			smart: "\r\x1b[1m[  0% 0/3] action1\x1b[0m\x1b[K\r\x1b[1m[ 33% 1/3] action1\x1b[0m\x1b[K\r\x1b[1m[ 33% 1/3] action2\x1b[0m\x1b[K\r\x1b[1m[ 66% 2/3] action2\x1b[0m\x1b[K\nFAILED: f1 f2\ntouch f1 f2\nerror1\nerror2\n\r\x1b[1m[ 66% 2/3] action3\x1b[0m\x1b[K\r\x1b[1m[100% 3/3] action3\x1b[0m\x1b[K\n",
+			dumb:  "[ 33% 1/3] action1\n[ 66% 2/3] action2\nFAILED: f1 f2\ntouch f1 f2\nerror1\nerror2\n[100% 3/3] action3\n",
+		},
+		{
+			name:  "action with empty description",
+			calls: actionWithEmptyDescription,
+			smart: "\r\x1b[1m[  0% 0/1] command1\x1b[0m\x1b[K\r\x1b[1m[100% 1/1] command1\x1b[0m\x1b[K\n",
+			dumb:  "[100% 1/1] command1\n",
+		},
+		{
+			name:  "messages",
+			calls: actionsWithMessages,
+			smart: "\r\x1b[1m[  0% 0/2] action1\x1b[0m\x1b[K\r\x1b[1m[ 50% 1/2] action1\x1b[0m\x1b[K\r\x1b[1mstatus\x1b[0m\x1b[K\r\x1b[Kprint\nFAILED: error\n\r\x1b[1m[ 50% 1/2] action2\x1b[0m\x1b[K\r\x1b[1m[100% 2/2] action2\x1b[0m\x1b[K\n",
+			dumb:  "[ 50% 1/2] action1\nstatus\nprint\nFAILED: error\n[100% 2/2] action2\n",
+		},
+		{
+			name:  "action with long description",
+			calls: actionWithLongDescription,
+			smart: "\r\x1b[1m[  0% 0/2] action with very long descrip\x1b[0m\x1b[K\r\x1b[1m[ 50% 1/2] action with very long descrip\x1b[0m\x1b[K\n",
+			dumb:  "[ 50% 1/2] action with very long description to test eliding\n",
+		},
+		{
+			name:  "action with output with ansi codes",
+			calls: actionWithOuptutWithAnsiCodes,
+			smart: "\r\x1b[1m[  0% 0/1] action1\x1b[0m\x1b[K\r\x1b[1m[100% 1/1] action1\x1b[0m\x1b[K\n\x1b[31mcolor\x1b[0m\n",
+			dumb:  "[100% 1/1] action1\ncolor\n",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			t.Run("smart", func(t *testing.T) {
+				smart := &fakeSmartTerminal{termWidth: 40}
+				stat := NewStatusOutput(smart, "", false)
+				tt.calls(stat)
+				stat.Flush()
+
+				if g, w := smart.String(), tt.smart; g != w {
+					t.Errorf("want:\n%q\ngot:\n%q", w, g)
+				}
+			})
+
+			t.Run("dumb", func(t *testing.T) {
+				dumb := &bytes.Buffer{}
+				stat := NewStatusOutput(dumb, "", false)
+				tt.calls(stat)
+				stat.Flush()
+
+				if g, w := dumb.String(), tt.dumb; g != w {
+					t.Errorf("want:\n%q\ngot:\n%q", w, g)
+				}
+			})
+		})
+	}
+}
+
+type runner struct {
+	counts status.Counts
+	stat   status.StatusOutput
+}
+
+func newRunner(stat status.StatusOutput, totalActions int) *runner {
+	return &runner{
+		counts: status.Counts{TotalActions: totalActions},
+		stat:   stat,
+	}
+}
+
+func (r *runner) startAction(action *status.Action) {
+	r.counts.StartedActions++
+	r.counts.RunningActions++
+	r.stat.StartAction(action, r.counts)
+}
+
+func (r *runner) finishAction(result status.ActionResult) {
+	r.counts.FinishedActions++
+	r.counts.RunningActions--
+	r.stat.FinishAction(result, r.counts)
+}
+
+func (r *runner) finishAndStartAction(result status.ActionResult, action *status.Action) {
+	r.counts.FinishedActions++
+	r.stat.FinishAction(result, r.counts)
+
+	r.counts.StartedActions++
+	r.stat.StartAction(action, r.counts)
+}
+
+var (
+	action1 = &status.Action{Description: "action1"}
+	result1 = status.ActionResult{Action: action1}
+	action2 = &status.Action{Description: "action2"}
+	result2 = status.ActionResult{Action: action2}
+	action3 = &status.Action{Description: "action3"}
+	result3 = status.ActionResult{Action: action3}
+)
+
+func twoActions(stat status.StatusOutput) {
+	runner := newRunner(stat, 2)
+	runner.startAction(action1)
+	runner.finishAction(result1)
+	runner.startAction(action2)
+	runner.finishAction(result2)
+}
+
+func twoParallelActions(stat status.StatusOutput) {
+	runner := newRunner(stat, 2)
+	runner.startAction(action1)
+	runner.startAction(action2)
+	runner.finishAction(result1)
+	runner.finishAction(result2)
+}
+
+func actionsWithOutput(stat status.StatusOutput) {
+	result2WithOutput := status.ActionResult{Action: action2, Output: "output1\noutput2\n"}
+
+	runner := newRunner(stat, 3)
+	runner.startAction(action1)
+	runner.finishAction(result1)
+	runner.startAction(action2)
+	runner.finishAction(result2WithOutput)
+	runner.startAction(action3)
+	runner.finishAction(result3)
+}
+
+func actionsWithOutputWithoutNewline(stat status.StatusOutput) {
+	result2WithOutputWithoutNewline := status.ActionResult{Action: action2, Output: "output1\noutput2"}
+
+	runner := newRunner(stat, 3)
+	runner.startAction(action1)
+	runner.finishAction(result1)
+	runner.startAction(action2)
+	runner.finishAction(result2WithOutputWithoutNewline)
+	runner.startAction(action3)
+	runner.finishAction(result3)
+}
+
+func actionsWithError(stat status.StatusOutput) {
+	action2WithError := &status.Action{Description: "action2", Outputs: []string{"f1", "f2"}, Command: "touch f1 f2"}
+	result2WithError := status.ActionResult{Action: action2WithError, Output: "error1\nerror2\n", Error: fmt.Errorf("error1")}
+
+	runner := newRunner(stat, 3)
+	runner.startAction(action1)
+	runner.finishAction(result1)
+	runner.startAction(action2WithError)
+	runner.finishAction(result2WithError)
+	runner.startAction(action3)
+	runner.finishAction(result3)
+}
+
+func actionWithEmptyDescription(stat status.StatusOutput) {
+	action1 := &status.Action{Command: "command1"}
+	result1 := status.ActionResult{Action: action1}
+
+	runner := newRunner(stat, 1)
+	runner.startAction(action1)
+	runner.finishAction(result1)
+}
+
+func actionsWithMessages(stat status.StatusOutput) {
+	runner := newRunner(stat, 2)
+
+	runner.startAction(action1)
+	runner.finishAction(result1)
+
+	stat.Message(status.VerboseLvl, "verbose")
+	stat.Message(status.StatusLvl, "status")
+	stat.Message(status.PrintLvl, "print")
+	stat.Message(status.ErrorLvl, "error")
+
+	runner.startAction(action2)
+	runner.finishAction(result2)
+}
+
+func actionWithLongDescription(stat status.StatusOutput) {
+	action1 := &status.Action{Description: "action with very long description to test eliding"}
+	result1 := status.ActionResult{Action: action1}
+
+	runner := newRunner(stat, 2)
+
+	runner.startAction(action1)
+
+	runner.finishAction(result1)
+}
+
+func actionWithOuptutWithAnsiCodes(stat status.StatusOutput) {
+	result1WithOutputWithAnsiCodes := status.ActionResult{Action: action1, Output: "\x1b[31mcolor\x1b[0m"}
+
+	runner := newRunner(stat, 1)
+	runner.startAction(action1)
+	runner.finishAction(result1WithOutputWithAnsiCodes)
+}
+
+func TestSmartStatusOutputWidthChange(t *testing.T) {
+	smart := &fakeSmartTerminal{termWidth: 40}
+	stat := NewStatusOutput(smart, "", false)
+
+	runner := newRunner(stat, 2)
+
+	action := &status.Action{Description: "action with very long description to test eliding"}
+	result := status.ActionResult{Action: action}
+
+	runner.startAction(action)
+	smart.termWidth = 30
+	runner.finishAction(result)
+
+	stat.Flush()
+
+	w := "\r\x1b[1m[  0% 0/2] action with very long descrip\x1b[0m\x1b[K\r\x1b[1m[ 50% 1/2] action with very lo\x1b[0m\x1b[K\n"
+
+	if g := smart.String(); g != w {
+		t.Errorf("want:\n%q\ngot:\n%q", w, g)
+	}
+}
diff --git a/ui/terminal/stdio.go b/ui/terminal/stdio.go
new file mode 100644
index 0000000..dec2963
--- /dev/null
+++ b/ui/terminal/stdio.go
@@ -0,0 +1,55 @@
+// Copyright 2018 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package terminal provides a set of interfaces that can be used to interact
+// with the terminal (including falling back when the terminal is detected to
+// be a redirect or other dumb terminal)
+package terminal
+
+import (
+	"io"
+	"os"
+)
+
+// StdioInterface represents a set of stdin/stdout/stderr Reader/Writers
+type StdioInterface interface {
+	Stdin() io.Reader
+	Stdout() io.Writer
+	Stderr() io.Writer
+}
+
+// StdioImpl uses the OS stdin/stdout/stderr to implement StdioInterface
+type StdioImpl struct{}
+
+func (StdioImpl) Stdin() io.Reader  { return os.Stdin }
+func (StdioImpl) Stdout() io.Writer { return os.Stdout }
+func (StdioImpl) Stderr() io.Writer { return os.Stderr }
+
+var _ StdioInterface = StdioImpl{}
+
+type customStdio struct {
+	stdin  io.Reader
+	stdout io.Writer
+	stderr io.Writer
+}
+
+func NewCustomStdio(stdin io.Reader, stdout, stderr io.Writer) StdioInterface {
+	return customStdio{stdin, stdout, stderr}
+}
+
+func (c customStdio) Stdin() io.Reader  { return c.stdin }
+func (c customStdio) Stdout() io.Writer { return c.stdout }
+func (c customStdio) Stderr() io.Writer { return c.stderr }
+
+var _ StdioInterface = customStdio{}
diff --git a/ui/terminal/util.go b/ui/terminal/util.go
index a85a517..3a11b79 100644
--- a/ui/terminal/util.go
+++ b/ui/terminal/util.go
@@ -22,13 +22,15 @@
 	"unsafe"
 )
 
-func isTerminal(w io.Writer) bool {
+func isSmartTerminal(w io.Writer) bool {
 	if f, ok := w.(*os.File); ok {
 		var termios syscall.Termios
 		_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, f.Fd(),
 			ioctlGetTermios, uintptr(unsafe.Pointer(&termios)),
 			0, 0, 0)
 		return err == 0
+	} else if _, ok := w.(*fakeSmartTerminal); ok {
+		return true
 	}
 	return false
 }
@@ -43,6 +45,8 @@
 			syscall.TIOCGWINSZ, uintptr(unsafe.Pointer(&winsize)),
 			0, 0, 0)
 		return int(winsize.ws_column), err == 0
+	} else if f, ok := w.(*fakeSmartTerminal); ok {
+		return f.termWidth, true
 	}
 	return 0, false
 }
@@ -99,3 +103,8 @@
 
 	return input
 }
+
+type fakeSmartTerminal struct {
+	bytes.Buffer
+	termWidth int
+}
diff --git a/ui/terminal/writer.go b/ui/terminal/writer.go
deleted file mode 100644
index ebe4b2a..0000000
--- a/ui/terminal/writer.go
+++ /dev/null
@@ -1,229 +0,0 @@
-// Copyright 2018 Google Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Package terminal provides a set of interfaces that can be used to interact
-// with the terminal (including falling back when the terminal is detected to
-// be a redirect or other dumb terminal)
-package terminal
-
-import (
-	"fmt"
-	"io"
-	"os"
-	"strings"
-	"sync"
-)
-
-// Writer provides an interface to write temporary and permanent messages to
-// the terminal.
-//
-// The terminal is considered to be a dumb terminal if TERM==dumb, or if a
-// terminal isn't detected on stdout/stderr (generally because it's a pipe or
-// file). Dumb terminals will strip out all ANSI escape sequences, including
-// colors.
-type Writer interface {
-	// Print prints the string to the terminal, overwriting any current
-	// status being displayed.
-	//
-	// On a dumb terminal, the status messages will be kept.
-	Print(str string)
-
-	// Status prints the first line of the string to the terminal,
-	// overwriting any previous status line. Strings longer than the width
-	// of the terminal will be cut off.
-	//
-	// On a dumb terminal, previous status messages will remain, and the
-	// entire first line of the string will be printed.
-	StatusLine(str string)
-
-	// StatusAndMessage prints the first line of status to the terminal,
-	// similarly to StatusLine(), then prints the full msg below that. The
-	// status line is retained.
-	//
-	// There is guaranteed to be no other output in between the status and
-	// message.
-	StatusAndMessage(status, msg string)
-
-	// Finish ensures that the output ends with a newline (preserving any
-	// current status line that is current displayed).
-	//
-	// This does nothing on dumb terminals.
-	Finish()
-
-	// Write implements the io.Writer interface. This is primarily so that
-	// the logger can use this interface to print to stderr without
-	// breaking the other semantics of this interface.
-	//
-	// Try to use any of the other functions if possible.
-	Write(p []byte) (n int, err error)
-
-	isSmartTerminal() bool
-}
-
-// NewWriter creates a new Writer based on the stdio and the TERM
-// environment variable.
-func NewWriter(stdio StdioInterface) Writer {
-	w := &writerImpl{
-		stdio: stdio,
-
-		haveBlankLine: true,
-	}
-
-	if term, ok := os.LookupEnv("TERM"); ok && term != "dumb" {
-		w.smartTerminal = isTerminal(stdio.Stdout())
-	}
-	w.stripEscapes = !w.smartTerminal
-
-	return w
-}
-
-type writerImpl struct {
-	stdio StdioInterface
-
-	haveBlankLine bool
-
-	// Protecting the above, we assume that smartTerminal and stripEscapes
-	// does not change after initial setup.
-	lock sync.Mutex
-
-	smartTerminal bool
-	stripEscapes  bool
-}
-
-func (w *writerImpl) isSmartTerminal() bool {
-	return w.smartTerminal
-}
-
-func (w *writerImpl) requestLine() {
-	if !w.haveBlankLine {
-		fmt.Fprintln(w.stdio.Stdout())
-		w.haveBlankLine = true
-	}
-}
-
-func (w *writerImpl) Print(str string) {
-	if w.stripEscapes {
-		str = string(stripAnsiEscapes([]byte(str)))
-	}
-
-	w.lock.Lock()
-	defer w.lock.Unlock()
-	w.print(str)
-}
-
-func (w *writerImpl) print(str string) {
-	if !w.haveBlankLine {
-		fmt.Fprint(w.stdio.Stdout(), "\r", "\x1b[K")
-		w.haveBlankLine = true
-	}
-	fmt.Fprint(w.stdio.Stdout(), str)
-	if len(str) == 0 || str[len(str)-1] != '\n' {
-		fmt.Fprint(w.stdio.Stdout(), "\n")
-	}
-}
-
-func (w *writerImpl) StatusLine(str string) {
-	w.lock.Lock()
-	defer w.lock.Unlock()
-
-	w.statusLine(str)
-}
-
-func (w *writerImpl) statusLine(str string) {
-	if !w.smartTerminal {
-		fmt.Fprintln(w.stdio.Stdout(), str)
-		return
-	}
-
-	idx := strings.IndexRune(str, '\n')
-	if idx != -1 {
-		str = str[0:idx]
-	}
-
-	// 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(w.stdio.Stdout()); 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]
-		}
-	}
-
-	// Move to the beginning on the line, print the output, then clear
-	// the rest of the line.
-	fmt.Fprint(w.stdio.Stdout(), "\r", str, "\x1b[K")
-	w.haveBlankLine = false
-}
-
-func (w *writerImpl) StatusAndMessage(status, msg string) {
-	if w.stripEscapes {
-		msg = string(stripAnsiEscapes([]byte(msg)))
-	}
-
-	w.lock.Lock()
-	defer w.lock.Unlock()
-
-	w.statusLine(status)
-	w.requestLine()
-	w.print(msg)
-}
-
-func (w *writerImpl) Finish() {
-	w.lock.Lock()
-	defer w.lock.Unlock()
-
-	w.requestLine()
-}
-
-func (w *writerImpl) Write(p []byte) (n int, err error) {
-	w.Print(string(p))
-	return len(p), nil
-}
-
-// StdioInterface represents a set of stdin/stdout/stderr Reader/Writers
-type StdioInterface interface {
-	Stdin() io.Reader
-	Stdout() io.Writer
-	Stderr() io.Writer
-}
-
-// StdioImpl uses the OS stdin/stdout/stderr to implement StdioInterface
-type StdioImpl struct{}
-
-func (StdioImpl) Stdin() io.Reader  { return os.Stdin }
-func (StdioImpl) Stdout() io.Writer { return os.Stdout }
-func (StdioImpl) Stderr() io.Writer { return os.Stderr }
-
-var _ StdioInterface = StdioImpl{}
-
-type customStdio struct {
-	stdin  io.Reader
-	stdout io.Writer
-	stderr io.Writer
-}
-
-func NewCustomStdio(stdin io.Reader, stdout, stderr io.Writer) StdioInterface {
-	return customStdio{stdin, stdout, stderr}
-}
-
-func (c customStdio) Stdin() io.Reader  { return c.stdin }
-func (c customStdio) Stdout() io.Writer { return c.stdout }
-func (c customStdio) Stderr() io.Writer { return c.stderr }
-
-var _ StdioInterface = customStdio{}
diff --git a/ui/tracer/status.go b/ui/tracer/status.go
index af50e2d..c831255 100644
--- a/ui/tracer/status.go
+++ b/ui/tracer/status.go
@@ -85,3 +85,8 @@
 
 func (s *statusOutput) Flush()                                        {}
 func (s *statusOutput) Message(level status.MsgLevel, message string) {}
+
+func (s *statusOutput) Write(p []byte) (int, error) {
+	// Discard writes
+	return len(p), nil
+}