Merge "Add all packages under packages/apps to root.bp"
diff --git a/Android.bp b/Android.bp
index d172fd5..9f508d5 100644
--- a/Android.bp
+++ b/Android.bp
@@ -219,10 +219,13 @@
         "soong-android",
     ],
     srcs: [
+        "python/androidmk.go",
         "python/binary.go",
         "python/builder.go",
+        "python/installer.go",
         "python/library.go",
         "python/python.go",
+        "python/test.go",
     ],
     testSrcs: [
         "python/python_test.go",
diff --git a/android/variable.go b/android/variable.go
index ef5b13c..666d729 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -67,6 +67,13 @@
 			Cflags []string
 		}
 
+		// treble is true when a build is a Treble compliant device.  This is automatically set when
+		// a build is shipped with Android O, but can be overriden.  This controls such things as
+		// the sepolicy split and enabling the Treble linker namespaces.
+		Treble struct {
+			Cflags []string
+		}
+
 		// debuggable is true for eng and userdebug builds, and can be used to turn on additional
 		// debugging features that don't significantly impact runtime behavior.  userdebug builds
 		// are used for dogfooding and performance testing, and should be as similar to user builds
@@ -130,6 +137,7 @@
 	Eng                        *bool `json:",omitempty"`
 	EnableCFI                  *bool `json:",omitempty"`
 	Device_uses_hwc2           *bool `json:",omitempty"`
+	Treble                     *bool `json:",omitempty"`
 
 	VendorPath *string `json:",omitempty"`
 
diff --git a/cc/builder.go b/cc/builder.go
index a4fda5b..f8b3e02 100644
--- a/cc/builder.go
+++ b/cc/builder.go
@@ -180,10 +180,10 @@
 	// Abidiff check turned on in advice-only mode. Builds will not fail on abi incompatibilties / extensions.
 	sAbiDiff = pctx.AndroidStaticRule("sAbiDiff",
 		blueprint.RuleParams{
-			Command:     "$sAbiDiffer -advice-only -o ${out} -new $in -old $referenceDump",
+			Command:     "$sAbiDiffer -lib $libName -arch $arch -advice-only -o ${out} -new $in -old $referenceDump",
 			CommandDeps: []string{"$sAbiDiffer"},
 		},
-		"referenceDump")
+		"referenceDump", "libName", "arch")
 )
 
 func init() {
@@ -642,6 +642,8 @@
 		Implicit:    referenceDump,
 		Args: map[string]string{
 			"referenceDump": referenceDump.String(),
+			"libName":       baseName,
+			"arch":          ctx.Arch().ArchType.Name,
 		},
 	})
 	return android.OptionalPathForPath(outputFile)
diff --git a/cc/cc.go b/cc/cc.go
index cff8d85..8069a90 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -1054,6 +1054,9 @@
 		}
 	})
 
+	// Dedup exported flags from dependencies
+	depPaths.Flags = firstUniqueElements(depPaths.Flags)
+
 	return depPaths
 }
 
@@ -1175,6 +1178,23 @@
 	}
 }
 
+// firstUniqueElements returns all unique elements of a slice, keeping the first copy of each
+// modifies the slice contents in place, and returns a subslice of the original slice
+func firstUniqueElements(list []string) []string {
+	k := 0
+outer:
+	for i := 0; i < len(list); i++ {
+		for j := 0; j < k; j++ {
+			if list[i] == list[j] {
+				continue outer
+			}
+		}
+		list[k] = list[i]
+		k++
+	}
+	return list[:k]
+}
+
 // lastUniqueElements returns all unique elements of a slice, keeping the last copy of each
 // modifies the slice contents in place, and returns a subslice of the original slice
 func lastUniqueElements(list []string) []string {
diff --git a/cc/cc_test.go b/cc/cc_test.go
index 6e779e7..92120a5 100644
--- a/cc/cc_test.go
+++ b/cc/cc_test.go
@@ -6,6 +6,56 @@
 	"testing"
 )
 
+var firstUniqueElementsTestCases = []struct {
+	in  []string
+	out []string
+}{
+	{
+		in:  []string{"a"},
+		out: []string{"a"},
+	},
+	{
+		in:  []string{"a", "b"},
+		out: []string{"a", "b"},
+	},
+	{
+		in:  []string{"a", "a"},
+		out: []string{"a"},
+	},
+	{
+		in:  []string{"a", "b", "a"},
+		out: []string{"a", "b"},
+	},
+	{
+		in:  []string{"b", "a", "a"},
+		out: []string{"b", "a"},
+	},
+	{
+		in:  []string{"a", "a", "b"},
+		out: []string{"a", "b"},
+	},
+	{
+		in:  []string{"a", "b", "a", "b"},
+		out: []string{"a", "b"},
+	},
+	{
+		in:  []string{"liblog", "libdl", "libc++", "libdl", "libc", "libm"},
+		out: []string{"liblog", "libdl", "libc++", "libc", "libm"},
+	},
+}
+
+func TestFirstUniqueElements(t *testing.T) {
+	for _, testCase := range firstUniqueElementsTestCases {
+		out := firstUniqueElements(testCase.in)
+		if !reflect.DeepEqual(out, testCase.out) {
+			t.Errorf("incorrect output:")
+			t.Errorf("     input: %#v", testCase.in)
+			t.Errorf("  expected: %#v", testCase.out)
+			t.Errorf("       got: %#v", out)
+		}
+	}
+}
+
 var lastUniqueElementsTestCases = []struct {
 	in  []string
 	out []string
diff --git a/cc/config/arm_device.go b/cc/config/arm_device.go
index ee9e042..6606100 100644
--- a/cc/config/arm_device.go
+++ b/cc/config/arm_device.go
@@ -121,6 +121,7 @@
 		},
 		"cortex-a15": []string{
 			"-mcpu=cortex-a15",
+			"-mfpu=neon-vfpv4",
 			// Fake an ARM compiler flag as these processors support LPAE which GCC/clang
 			// don't advertise.
 			// TODO This is a hack and we need to add it for each processor that supports LPAE until some
diff --git a/cc/config/mips_device.go b/cc/config/mips_device.go
index 9e27f37..ec8f133 100644
--- a/cc/config/mips_device.go
+++ b/cc/config/mips_device.go
@@ -92,7 +92,6 @@
 			"-mfp32",
 			"-modd-spreg",
 			"-mno-fused-madd",
-			"-Wa,-mmxu",
 			"-mno-synci",
 		},
 		"mips32r2dsp-fp": []string{
diff --git a/cc/prebuilt.go b/cc/prebuilt.go
index 08ba145..d064a46 100644
--- a/cc/prebuilt.go
+++ b/cc/prebuilt.go
@@ -66,7 +66,12 @@
 }
 
 func prebuiltSharedLibraryFactory() (blueprint.Module, []interface{}) {
-	module, library := NewLibrary(android.HostAndDeviceSupported)
+	module, _ := NewPrebuiltSharedLibrary(android.HostAndDeviceSupported)
+	return module.Init()
+}
+
+func NewPrebuiltSharedLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) {
+	module, library := NewLibrary(hod)
 	library.BuildOnlyShared()
 	module.compiler = nil
 
@@ -75,11 +80,16 @@
 	}
 	module.linker = prebuilt
 
-	return module.Init()
+	return module, library
 }
 
 func prebuiltStaticLibraryFactory() (blueprint.Module, []interface{}) {
-	module, library := NewLibrary(android.HostAndDeviceSupported)
+	module, _ := NewPrebuiltStaticLibrary(android.HostAndDeviceSupported)
+	return module.Init()
+}
+
+func NewPrebuiltStaticLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) {
+	module, library := NewLibrary(hod)
 	library.BuildOnlyStatic()
 	module.compiler = nil
 
@@ -88,7 +98,7 @@
 	}
 	module.linker = prebuilt
 
-	return module.Init()
+	return module, library
 }
 
 type prebuiltBinaryLinker struct {
@@ -115,7 +125,12 @@
 }
 
 func prebuiltBinaryFactory() (blueprint.Module, []interface{}) {
-	module, binary := NewBinary(android.HostAndDeviceSupported)
+	module, _ := NewPrebuiltBinary(android.HostAndDeviceSupported)
+	return module.Init()
+}
+
+func NewPrebuiltBinary(hod android.HostOrDeviceSupported) (*Module, *binaryDecorator) {
+	module, binary := NewBinary(hod)
 	module.compiler = nil
 
 	prebuilt := &prebuiltBinaryLinker{
@@ -123,5 +138,5 @@
 	}
 	module.linker = prebuilt
 
-	return module.Init()
+	return module, binary
 }
diff --git a/cmd/multiproduct_kati/main.go b/cmd/multiproduct_kati/main.go
index b12628e..fb1c890 100644
--- a/cmd/multiproduct_kati/main.go
+++ b/cmd/multiproduct_kati/main.go
@@ -19,6 +19,7 @@
 	"context"
 	"flag"
 	"fmt"
+	"io/ioutil"
 	"os"
 	"path/filepath"
 	"runtime"
@@ -47,15 +48,20 @@
 var keep = flag.Bool("keep", false, "keep successful output files")
 
 var outDir = flag.String("out", "", "path to store output directories (defaults to tmpdir under $OUT when empty)")
+var alternateResultDir = flag.Bool("dist", false, "write select results to $DIST_DIR (or <out>/dist when empty)")
 
 var onlyConfig = flag.Bool("only-config", false, "Only run product config (not Soong or Kati)")
 var onlySoong = flag.Bool("only-soong", false, "Only run product config and Soong (not Kati)")
 
 var buildVariant = flag.String("variant", "eng", "build variant to use")
 
+const errorLeadingLines = 20
+const errorTrailingLines = 20
+
 type Product struct {
-	ctx    build.Context
-	config build.Config
+	ctx     build.Context
+	config  build.Config
+	logFile string
 }
 
 type Status struct {
@@ -82,7 +88,7 @@
 	s.total = total
 }
 
-func (s *Status) Fail(product string, err error) {
+func (s *Status) Fail(product string, err error, logFile string) {
 	s.Finish(product)
 
 	s.lock.Lock()
@@ -96,7 +102,26 @@
 	s.failed++
 	fmt.Fprintln(s.ctx.Stderr(), "FAILED:", product)
 	s.ctx.Verboseln("FAILED:", product)
-	s.ctx.Println(err)
+
+	if logFile != "" {
+		data, err := ioutil.ReadFile(logFile)
+		if err == nil {
+			lines := strings.Split(strings.TrimSpace(string(data)), "\n")
+			if len(lines) > errorLeadingLines+errorTrailingLines+1 {
+				lines[errorLeadingLines] = fmt.Sprintf("... skipping %d lines ...",
+					len(lines)-errorLeadingLines-errorTrailingLines)
+
+				lines = append(lines[:errorLeadingLines+1],
+					lines[len(lines)-errorTrailingLines:]...)
+			}
+			for _, line := range lines {
+				fmt.Fprintln(s.ctx.Stderr(), "> ", line)
+				s.ctx.Verboseln(line)
+			}
+		}
+	}
+
+	s.ctx.Print(err)
 }
 
 func (s *Status) Finish(product string) {
@@ -163,6 +188,13 @@
 
 		*outDir = filepath.Join(config.OutDir(), name)
 
+		// Ensure the empty files exist in the output directory
+		// containing our output directory too. This is mostly for
+		// safety, but also triggers the ninja_build file so that our
+		// build servers know that they can parse the output as if it
+		// was ninja output.
+		build.SetupOutDir(buildCtx, config)
+
 		if err := os.MkdirAll(*outDir, 0777); err != nil {
 			log.Fatalf("Failed to create tempdir: %v", err)
 		}
@@ -179,8 +211,15 @@
 	log.Println("Output directory:", *outDir)
 
 	build.SetupOutDir(buildCtx, config)
-	log.SetOutput(filepath.Join(config.OutDir(), "soong.log"))
-	trace.SetOutput(filepath.Join(config.OutDir(), "build.trace"))
+	if *alternateResultDir {
+		logsDir := filepath.Join(config.DistDir(), "logs")
+		os.MkdirAll(logsDir, 0777)
+		log.SetOutput(filepath.Join(logsDir, "soong.log"))
+		trace.SetOutput(filepath.Join(logsDir, "build.trace"))
+	} else {
+		log.SetOutput(filepath.Join(config.OutDir(), "soong.log"))
+		trace.SetOutput(filepath.Join(config.OutDir(), "build.trace"))
+	}
 
 	vars, err := build.DumpMakeVars(buildCtx, config, nil, nil, []string{"all_named_products"})
 	if err != nil {
@@ -198,24 +237,34 @@
 	for _, product := range products {
 		wg.Add(1)
 		go func(product string) {
+			var stdLog string
+
 			defer wg.Done()
 			defer logger.Recover(func(err error) {
-				status.Fail(product, err)
+				status.Fail(product, err, stdLog)
 			})
 
 			productOutDir := filepath.Join(config.OutDir(), product)
+			productLogDir := productOutDir
+			if *alternateResultDir {
+				productLogDir = filepath.Join(config.DistDir(), product)
+				if err := os.MkdirAll(productLogDir, 0777); err != nil {
+					log.Fatalf("Error creating log directory: %v", err)
+				}
+			}
 
 			if err := os.MkdirAll(productOutDir, 0777); err != nil {
 				log.Fatalf("Error creating out directory: %v", err)
 			}
 
-			f, err := os.Create(filepath.Join(productOutDir, "std.log"))
+			stdLog = filepath.Join(productLogDir, "std.log")
+			f, err := os.Create(stdLog)
 			if err != nil {
 				log.Fatalf("Error creating std.log: %v", err)
 			}
 
 			productLog := logger.New(&bytes.Buffer{})
-			productLog.SetOutput(filepath.Join(productOutDir, "soong.log"))
+			productLog.SetOutput(filepath.Join(productLogDir, "soong.log"))
 
 			productCtx := build.Context{&build.ContextImpl{
 				Context:        ctx,
@@ -230,7 +279,7 @@
 			productConfig.Lunch(productCtx, product, *buildVariant)
 
 			build.Build(productCtx, productConfig, build.BuildProductConfig)
-			productConfigs <- Product{productCtx, productConfig}
+			productConfigs <- Product{productCtx, productConfig, stdLog}
 		}(product)
 	}
 	go func() {
@@ -247,7 +296,7 @@
 			for product := range productConfigs {
 				func() {
 					defer logger.Recover(func(err error) {
-						status.Fail(product.config.TargetProduct(), err)
+						status.Fail(product.config.TargetProduct(), err, product.logFile)
 					})
 
 					buildWhat := 0
diff --git a/python/androidmk.go b/python/androidmk.go
new file mode 100644
index 0000000..0a79e73
--- /dev/null
+++ b/python/androidmk.go
@@ -0,0 +1,74 @@
+// Copyright 2017 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 python
+
+import (
+	"android/soong/android"
+	"fmt"
+	"io"
+	"path/filepath"
+	"strings"
+)
+
+type subAndroidMkProvider interface {
+	AndroidMk(*pythonBaseModule, *android.AndroidMkData)
+}
+
+func (p *pythonBaseModule) subAndroidMk(data *android.AndroidMkData, obj interface{}) {
+	if p.subAndroidMkOnce == nil {
+		p.subAndroidMkOnce = make(map[subAndroidMkProvider]bool)
+	}
+	if androidmk, ok := obj.(subAndroidMkProvider); ok {
+		if !p.subAndroidMkOnce[androidmk] {
+			p.subAndroidMkOnce[androidmk] = true
+			androidmk.AndroidMk(p, data)
+		}
+	}
+}
+
+func (p *pythonBaseModule) AndroidMk() (ret android.AndroidMkData, err error) {
+	p.subAndroidMk(&ret, p.installer)
+
+	return ret, nil
+}
+
+func (p *pythonBinaryHostDecorator) AndroidMk(base *pythonBaseModule, ret *android.AndroidMkData) {
+	ret.Class = "EXECUTABLES"
+	base.subAndroidMk(ret, p.pythonDecorator.baseInstaller)
+}
+
+func (p *pythonTestHostDecorator) AndroidMk(base *pythonBaseModule, ret *android.AndroidMkData) {
+	ret.Class = "NATIVE_TESTS"
+	base.subAndroidMk(ret, p.pythonDecorator.baseInstaller)
+}
+
+func (installer *pythonInstaller) AndroidMk(base *pythonBaseModule, ret *android.AndroidMkData) {
+	// Soong installation is only supported for host modules. Have Make
+	// installation trigger Soong installation.
+	if base.Target().Os.Class == android.Host {
+		ret.OutputFile = android.OptionalPathForPath(installer.path)
+	}
+
+	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) error {
+		path := installer.path.RelPathString()
+		dir, file := filepath.Split(path)
+		stem := strings.TrimSuffix(file, filepath.Ext(file))
+
+		fmt.Fprintln(w, "LOCAL_MODULE_SUFFIX := "+filepath.Ext(file))
+		fmt.Fprintln(w, "LOCAL_MODULE_PATH := $(OUT_DIR)/"+filepath.Clean(dir))
+		fmt.Fprintln(w, "LOCAL_MODULE_STEM := "+stem)
+		return nil
+	})
+}
diff --git a/python/binary.go b/python/binary.go
index 4b4ccc2..81e8bd9 100644
--- a/python/binary.go
+++ b/python/binary.go
@@ -18,7 +18,6 @@
 
 import (
 	"fmt"
-	"io"
 	"path/filepath"
 	"strings"
 
@@ -31,7 +30,7 @@
 	android.RegisterModuleType("python_binary_host", PythonBinaryHostFactory)
 }
 
-type PythonBinaryProperties struct {
+type PythonBinaryBaseProperties struct {
 	// the name of the source file that is the main entry point of the program.
 	// this file must also be listed in srcs.
 	// If left unspecified, module name is used instead.
@@ -45,40 +44,53 @@
 	Suffix string
 }
 
-type PythonBinary struct {
+type pythonBinaryBase struct {
 	pythonBaseModule
 
-	binaryProperties PythonBinaryProperties
+	binaryProperties PythonBinaryBaseProperties
 
 	// soong_zip arguments from all its dependencies.
 	depsParSpecs []parSpec
 
 	// Python runfiles paths from all its dependencies.
 	depsPyRunfiles []string
-
-	// the installation path for Python binary.
-	installPath android.OutputPath
 }
 
-var _ PythonSubModule = (*PythonBinary)(nil)
+type PythonBinaryHost struct {
+	pythonBinaryBase
+}
+
+var _ PythonSubModule = (*PythonBinaryHost)(nil)
+
+type pythonBinaryHostDecorator struct {
+	pythonDecorator
+}
+
+func (p *pythonBinaryHostDecorator) install(ctx android.ModuleContext, file android.Path) {
+	p.pythonDecorator.baseInstaller.install(ctx, file)
+}
 
 var (
 	stubTemplateHost = "build/soong/python/scripts/stub_template_host.txt"
 )
 
 func PythonBinaryHostFactory() (blueprint.Module, []interface{}) {
-	module := &PythonBinary{}
+	decorator := &pythonBinaryHostDecorator{
+		pythonDecorator: pythonDecorator{baseInstaller: NewPythonInstaller("bin")}}
 
-	return InitPythonBaseModule(&module.pythonBaseModule, module, android.HostSupportedNoCross,
-		&module.binaryProperties)
+	module := &PythonBinaryHost{}
+	module.pythonBaseModule.installer = decorator
+
+	return InitPythonBaseModule(&module.pythonBinaryBase.pythonBaseModule,
+		&module.pythonBinaryBase, android.HostSupportedNoCross, &module.binaryProperties)
 }
 
-func (p *PythonBinary) GeneratePythonBuildActions(ctx android.ModuleContext) {
+func (p *pythonBinaryBase) GeneratePythonBuildActions(ctx android.ModuleContext) android.OptionalPath {
 	p.pythonBaseModule.GeneratePythonBuildActions(ctx)
 
 	// no Python source file for compiling par file.
 	if len(p.pythonBaseModule.srcsPathMappings) == 0 && len(p.depsPyRunfiles) == 0 {
-		return
+		return android.OptionalPath{}
 	}
 
 	// the runfiles packages needs to be populated with "__init__.py".
@@ -121,11 +133,11 @@
 
 	main := p.getPyMainFile(ctx)
 	if main == "" {
-		return
+		return android.OptionalPath{}
 	}
 	interp := p.getInterpreter(ctx)
 	if interp == "" {
-		return
+		return android.OptionalPath{}
 	}
 
 	// we need remove "runfiles/" suffix since stub script starts
@@ -134,13 +146,11 @@
 		strings.TrimPrefix(main, runFiles+"/"), p.getStem(ctx),
 		newPyPkgs, append(p.depsParSpecs, p.pythonBaseModule.parSpec))
 
-	// install par file.
-	p.installPath = ctx.InstallFile(
-		android.PathForModuleInstall(ctx, "bin"), binFile)
+	return android.OptionalPathForPath(binFile)
 }
 
 // get interpreter path.
-func (p *PythonBinary) getInterpreter(ctx android.ModuleContext) string {
+func (p *pythonBinaryBase) getInterpreter(ctx android.ModuleContext) string {
 	var interp string
 	switch p.pythonBaseModule.properties.ActualVersion {
 	case pyVersion2:
@@ -156,7 +166,7 @@
 }
 
 // find main program path within runfiles tree.
-func (p *PythonBinary) getPyMainFile(ctx android.ModuleContext) string {
+func (p *pythonBinaryBase) getPyMainFile(ctx android.ModuleContext) string {
 	var main string
 	if p.binaryProperties.Main == "" {
 		main = p.BaseModuleName() + pyExt
@@ -174,7 +184,7 @@
 	return ""
 }
 
-func (p *PythonBinary) getStem(ctx android.ModuleContext) string {
+func (p *pythonBinaryBase) getStem(ctx android.ModuleContext) string {
 	stem := ctx.ModuleName()
 	if p.binaryProperties.Stem != "" {
 		stem = p.binaryProperties.Stem
@@ -209,27 +219,3 @@
 	}
 	return ""
 }
-
-func (p *PythonBinary) GeneratePythonAndroidMk() (ret android.AndroidMkData, err error) {
-	// Soong installation is only supported for host modules. Have Make
-	// installation trigger Soong installation.
-	if p.pythonBaseModule.Target().Os.Class == android.Host {
-		ret.OutputFile = android.OptionalPathForPath(p.installPath)
-	}
-	ret.Class = "EXECUTABLES"
-
-	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) error {
-		path := p.installPath.RelPathString()
-		dir, file := filepath.Split(path)
-		stem := strings.TrimSuffix(file, filepath.Ext(file))
-
-		fmt.Fprintln(w, "LOCAL_MODULE_SUFFIX := "+filepath.Ext(file))
-		fmt.Fprintln(w, "LOCAL_MODULE_PATH := $(OUT_DIR)/"+filepath.Clean(dir))
-		fmt.Fprintln(w, "LOCAL_MODULE_STEM := "+stem)
-
-		return nil
-	})
-
-	return
-
-}
diff --git a/python/installer.go b/python/installer.go
new file mode 100644
index 0000000..9c12f5f
--- /dev/null
+++ b/python/installer.go
@@ -0,0 +1,39 @@
+// Copyright 2017 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 python
+
+import (
+	"android/soong/android"
+)
+
+// This file handles installing python executables into their final location
+
+type pythonInstaller struct {
+	dir string
+
+	path android.OutputPath
+}
+
+func NewPythonInstaller(dir string) *pythonInstaller {
+	return &pythonInstaller{
+		dir: dir,
+	}
+}
+
+var _ installer = (*pythonInstaller)(nil)
+
+func (installer *pythonInstaller) install(ctx android.ModuleContext, file android.Path) {
+	installer.path = ctx.InstallFile(android.PathForModuleInstall(ctx, installer.dir), file)
+}
diff --git a/python/library.go b/python/library.go
index 1deaeb8..0b70756 100644
--- a/python/library.go
+++ b/python/library.go
@@ -37,7 +37,3 @@
 
 	return InitPythonBaseModule(&module.pythonBaseModule, module, android.HostSupportedNoCross)
 }
-
-func (p *PythonLibrary) GeneratePythonAndroidMk() (ret android.AndroidMkData, err error) {
-	return
-}
diff --git a/python/python.go b/python/python.go
index 1c74c9a..ab80e4d 100644
--- a/python/python.go
+++ b/python/python.go
@@ -110,11 +110,15 @@
 
 	// the soong_zip arguments for zipping current module source/data files.
 	parSpec parSpec
+
+	// the installer might be nil.
+	installer installer
+
+	subAndroidMkOnce map[subAndroidMkProvider]bool
 }
 
 type PythonSubModule interface {
-	GeneratePythonBuildActions(ctx android.ModuleContext)
-	GeneratePythonAndroidMk() (ret android.AndroidMkData, err error)
+	GeneratePythonBuildActions(ctx android.ModuleContext) android.OptionalPath
 }
 
 type PythonDependency interface {
@@ -123,6 +127,14 @@
 	GetParSpec() parSpec
 }
 
+type pythonDecorator struct {
+	baseInstaller *pythonInstaller
+}
+
+type installer interface {
+	install(ctx android.ModuleContext, path android.Path)
+}
+
 func (p *pythonBaseModule) GetSrcsPathMappings() []pathMapping {
 	return p.srcsPathMappings
 }
@@ -246,10 +258,14 @@
 }
 
 func (p *pythonBaseModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
-	p.subModule.GeneratePythonBuildActions(ctx)
+	installSource := p.subModule.GeneratePythonBuildActions(ctx)
+
+	if p.installer != nil && installSource.Valid() {
+		p.installer.install(ctx, installSource.Path())
+	}
 }
 
-func (p *pythonBaseModule) GeneratePythonBuildActions(ctx android.ModuleContext) {
+func (p *pythonBaseModule) GeneratePythonBuildActions(ctx android.ModuleContext) android.OptionalPath {
 	// expand python files from "srcs" property.
 	srcs := p.properties.Srcs
 	switch p.properties.ActualVersion {
@@ -277,7 +293,7 @@
 			strings.HasPrefix(pkg_path, "/") {
 			ctx.PropertyErrorf("pkg_path", "%q is not a valid format.",
 				p.properties.Pkg_path)
-			return
+			return android.OptionalPath{}
 		}
 		// pkg_path starts from "runfiles/" implicitly.
 		pkg_path = filepath.Join(runFiles, pkg_path)
@@ -291,6 +307,8 @@
 	p.parSpec = p.dumpFileList(ctx, pkg_path)
 
 	p.uniqWholeRunfilesTree(ctx)
+
+	return android.OptionalPath{}
 }
 
 // generate current module unique pathMappings: <dest: runfiles_path, src: source_path>
@@ -409,7 +427,7 @@
 				}
 				// binary needs the Python runfiles paths from all its
 				// dependencies to fill __init__.py in each runfiles dir.
-				if sub, ok := p.subModule.(*PythonBinary); ok {
+				if sub, ok := p.subModule.(*pythonBinaryBase); ok {
 					sub.depsPyRunfiles = append(sub.depsPyRunfiles, path.dest)
 				}
 			}
@@ -421,7 +439,7 @@
 			}
 			// binary needs the soong_zip arguments from all its
 			// dependencies to generate executable par file.
-			if sub, ok := p.subModule.(*PythonBinary); ok {
+			if sub, ok := p.subModule.(*pythonBinaryBase); ok {
 				sub.depsParSpecs = append(sub.depsParSpecs, dep.GetParSpec())
 			}
 		}
@@ -442,7 +460,3 @@
 
 	return true
 }
-
-func (p *pythonBaseModule) AndroidMk() (ret android.AndroidMkData, err error) {
-	return p.subModule.GeneratePythonAndroidMk()
-}
diff --git a/python/python_test.go b/python/python_test.go
index c6b8451..3f719f8 100644
--- a/python/python_test.go
+++ b/python/python_test.go
@@ -370,7 +370,7 @@
 	if !baseOk {
 		t.Fatalf("%s is not Python module!", name)
 	}
-	sub, subOk := base.subModule.(*PythonBinary)
+	sub, subOk := base.subModule.(*pythonBinaryBase)
 	if !subOk {
 		t.Fatalf("%s is not Python binary!", name)
 	}
diff --git a/python/test.go b/python/test.go
new file mode 100644
index 0000000..8318438
--- /dev/null
+++ b/python/test.go
@@ -0,0 +1,54 @@
+// Copyright 2017 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 python
+
+import (
+	"android/soong/android"
+	"path/filepath"
+
+	"github.com/google/blueprint"
+)
+
+// This file contains the module types for building Python test.
+
+func init() {
+	android.RegisterModuleType("python_test_host", PythonTestHostFactory)
+}
+
+type PythonTestHost struct {
+	pythonBinaryBase
+}
+
+var _ PythonSubModule = (*PythonTestHost)(nil)
+
+type pythonTestHostDecorator struct {
+	pythonDecorator
+}
+
+func (p *pythonTestHostDecorator) install(ctx android.ModuleContext, file android.Path) {
+	p.pythonDecorator.baseInstaller.dir = filepath.Join("nativetest", ctx.ModuleName())
+	p.pythonDecorator.baseInstaller.install(ctx, file)
+}
+
+func PythonTestHostFactory() (blueprint.Module, []interface{}) {
+	decorator := &pythonTestHostDecorator{
+		pythonDecorator: pythonDecorator{baseInstaller: NewPythonInstaller("nativetest")}}
+
+	module := &PythonBinaryHost{}
+	module.pythonBaseModule.installer = decorator
+
+	return InitPythonBaseModule(&module.pythonBinaryBase.pythonBaseModule,
+		&module.pythonBinaryBase, android.HostSupportedNoCross, &module.binaryProperties)
+}