Merge "Have AndroidMk skip emitting LOCAL_MODULE_TAGS="optional""
diff --git a/Android.bp b/Android.bp
index c6b6ee4..4d06710 100644
--- a/Android.bp
+++ b/Android.bp
@@ -95,6 +95,7 @@
 
         "cc/config/x86_darwin_host.go",
         "cc/config/x86_linux_host.go",
+        "cc/config/x86_linux_bionic_host.go",
         "cc/config/x86_windows_host.go",
     ],
     testSrcs: [
@@ -145,6 +146,8 @@
         "cc/ndk_headers.go",
         "cc/ndk_library.go",
         "cc/ndk_sysroot.go",
+
+        "cc/vndk_library.go",
     ],
     testSrcs: [
         "cc/cc_test.go",
diff --git a/android/androidmk.go b/android/androidmk.go
index 793947e..ec3abe1 100644
--- a/android/androidmk.go
+++ b/android/androidmk.go
@@ -164,6 +164,11 @@
 		return err
 	}
 
+	// Make does not understand LinuxBionic
+	if amod.Os() == LinuxBionic {
+		return nil
+	}
+
 	if data.SubName != "" {
 		name += data.SubName
 	}
diff --git a/android/arch.go b/android/arch.go
index df50afa..3d56b37 100644
--- a/android/arch.go
+++ b/android/arch.go
@@ -217,7 +217,8 @@
 type OsClass int
 
 const (
-	Device OsClass = iota
+	Generic OsClass = iota
+	Device
 	Host
 	HostCross
 )
@@ -780,6 +781,10 @@
 		addTarget(BuildOs, *variables.HostSecondaryArch, nil, nil, nil)
 	}
 
+	if config.Host_bionic != nil && *config.Host_bionic {
+		addTarget(LinuxBionic, "x86_64", nil, nil, nil)
+	}
+
 	if variables.CrossHost != nil && *variables.CrossHost != "" {
 		crossHostOs := osByName(*variables.CrossHost)
 		if crossHostOs == NoOsType {
diff --git a/android/config.go b/android/config.go
index 1d8cdba..2413f52 100644
--- a/android/config.go
+++ b/android/config.go
@@ -40,6 +40,7 @@
 type FileConfigurableOptions struct {
 	Mega_device *bool `json:",omitempty"`
 	Ndk_abis    *bool `json:",omitempty"`
+	Host_bionic *bool `json:",omitempty"`
 }
 
 func (f *FileConfigurableOptions) SetDefaultConfig() {
@@ -496,3 +497,7 @@
 	}
 	return coverage
 }
+
+func (c *deviceConfig) SameProcessHalDeps() []string {
+	return append([]string(nil), c.config.ProductVariables.SameProcessHalDeps...)
+}
diff --git a/android/module.go b/android/module.go
index 7b35d32..6474e47 100644
--- a/android/module.go
+++ b/android/module.go
@@ -631,7 +631,7 @@
 	a.module.base().hooks.runInstallHooks(a, fullInstallPath, false)
 
 	if !a.module.base().commonProperties.SkipInstall &&
-		(a.Host() || !a.AConfig().SkipDeviceInstall()) {
+		(!a.Device() || !a.AConfig().SkipDeviceInstall()) {
 
 		deps = append(deps, a.installDeps...)
 
@@ -669,7 +669,7 @@
 	a.module.base().hooks.runInstallHooks(a, fullInstallPath, true)
 
 	if !a.module.base().commonProperties.SkipInstall &&
-		(a.Host() || !a.AConfig().SkipDeviceInstall()) {
+		(!a.Device() || !a.AConfig().SkipDeviceInstall()) {
 
 		a.ModuleBuild(pctx, ModuleBuildParams{
 			Rule:      Symlink,
diff --git a/android/variable.go b/android/variable.go
index c5b957b..aefe1e3 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -135,6 +135,8 @@
 	ArtUseReadBarrier *bool `json:",omitempty"`
 
 	BtConfigIncludeDir *string `json:",omitempty"`
+
+	SameProcessHalDeps []string `json:",omitempty"`
 }
 
 func boolPtr(v bool) *bool {
diff --git a/cc/androidmk.go b/cc/androidmk.go
index f45fbbe..0cd6faf 100644
--- a/cc/androidmk.go
+++ b/cc/androidmk.go
@@ -156,6 +156,14 @@
 	}
 }
 
+func (vndkLibrary *vndkExtLibraryDecorator) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkData) {
+	ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) error {
+		fmt.Fprintln(w, "LOCAL_EXTENDS_MODULE := ", vndkLibrary.properties.Extends)
+		return nil
+	})
+	vndkLibrary.libraryDecorator.AndroidMk(ctx, ret)
+}
+
 func (object *objectLinker) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkData) {
 	ret.Custom = func(w io.Writer, name, prefix, moduleDir string) error {
 		out := ret.OutputFile.Path()
diff --git a/cc/binary.go b/cc/binary.go
index 521ccb7..637f6c7 100644
--- a/cc/binary.go
+++ b/cc/binary.go
@@ -15,6 +15,8 @@
 package cc
 
 import (
+	"path/filepath"
+
 	"github.com/google/blueprint"
 	"github.com/google/blueprint/proptools"
 
@@ -236,7 +238,22 @@
 				if binary.Properties.DynamicLinker != "" {
 					flags.DynamicLinker = binary.Properties.DynamicLinker
 				} else {
-					flags.DynamicLinker = "/system/bin/linker"
+					switch ctx.Os() {
+					case android.Android:
+						flags.DynamicLinker = "/system/bin/linker"
+					case android.LinuxBionic:
+						// The linux kernel expects the linker to be an
+						// absolute path
+						path := android.PathForOutput(ctx,
+							"host", "linux_bionic-x86", "bin", "linker")
+						if p, err := filepath.Abs(path.String()); err == nil {
+							flags.DynamicLinker = p
+						} else {
+							ctx.ModuleErrorf("can't find path to dynamic linker: %q", err)
+						}
+					default:
+						ctx.ModuleErrorf("unknown dynamic linker")
+					}
 					if flags.Toolchain.Is64Bit() {
 						flags.DynamicLinker += "64"
 					}
diff --git a/cc/builder.go b/cc/builder.go
index 9a871d5..f3a4bcb 100644
--- a/cc/builder.go
+++ b/cc/builder.go
@@ -184,6 +184,7 @@
 
 type builderFlags struct {
 	globalFlags string
+	arFlags     string
 	asFlags     string
 	cFlags      string
 	conlyFlags  string
@@ -367,6 +368,9 @@
 
 	arCmd := gccCmd(flags.toolchain, "ar")
 	arFlags := "crsPD"
+	if flags.arFlags != "" {
+		arFlags += " " + flags.arFlags
+	}
 
 	ctx.ModuleBuild(pctx, android.ModuleBuildParams{
 		Rule:      ar,
diff --git a/cc/cc.go b/cc/cc.go
index d486db3..c5f1c35 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -96,6 +96,7 @@
 
 type Flags struct {
 	GlobalFlags []string // Flags that apply to C, C++, and assembly source files
+	ArFlags     []string // Flags that apply to ar
 	AsFlags     []string // Flags that apply to assembly source files
 	CFlags      []string // Flags that apply to C and C++ source files
 	ConlyFlags  []string // Flags that apply to C source files
@@ -162,6 +163,9 @@
 	vndk() bool
 	selectedStl() string
 	baseModuleName() string
+	isNdk() bool
+	isVndk() bool
+	isSameProcessHal() bool
 }
 
 type ModuleContext interface {
@@ -404,6 +408,18 @@
 	return ctx.mod.ModuleBase.BaseModuleName()
 }
 
+func (ctx *moduleContextImpl) isNdk() bool {
+	return inList(ctx.baseModuleName(), ndkPrebuiltSharedLibraries)
+}
+
+func (ctx *moduleContextImpl) isVndk() bool {
+	return config.IsVndkLibrary(ctx.baseModuleName())
+}
+
+func (ctx *moduleContextImpl) isSameProcessHal() bool {
+	return inList(ctx.baseModuleName(), ctx.ctx.DeviceConfig().SameProcessHalDeps())
+}
+
 func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
 	return &Module{
 		hod:      hod,
diff --git a/cc/compiler.go b/cc/compiler.go
index dc594e3..84ee652 100644
--- a/cc/compiler.go
+++ b/cc/compiler.go
@@ -262,10 +262,7 @@
 		flags.LdFlags = config.ClangFilterUnknownCflags(flags.LdFlags)
 
 		target := "-target " + tc.ClangTriple()
-		var gccPrefix string
-		if !ctx.Darwin() {
-			gccPrefix = "-B" + filepath.Join(tc.GccRoot(), tc.GccTriple(), "bin")
-		}
+		gccPrefix := "-B" + config.ToolPath(tc)
 
 		flags.CFlags = append(flags.CFlags, target, gccPrefix)
 		flags.AsFlags = append(flags.AsFlags, target, gccPrefix)
diff --git a/cc/config/global.go b/cc/config/global.go
index 1ce1cce..68de5d0 100644
--- a/cc/config/global.go
+++ b/cc/config/global.go
@@ -176,3 +176,11 @@
 func VndkLibraries() []string {
 	return []string{}
 }
+
+func VndkIndirectLibraries() []string {
+	return []string{}
+}
+
+func IsVndkLibrary(name string) bool {
+	return inList(name, VndkLibraries()) || inList(name, VndkIndirectLibraries())
+}
diff --git a/cc/config/toolchain.go b/cc/config/toolchain.go
index 995c8c6..8fc4a21 100644
--- a/cc/config/toolchain.go
+++ b/cc/config/toolchain.go
@@ -16,6 +16,7 @@
 
 import (
 	"fmt"
+	"path/filepath"
 
 	"android/soong/android"
 )
@@ -47,6 +48,7 @@
 	GccTriple() string
 	// GccVersion should return a real value, not a ninja reference
 	GccVersion() string
+	ToolPath() string
 
 	ToolchainCflags() string
 	ToolchainLdflags() string
@@ -145,6 +147,10 @@
 	return true
 }
 
+func (t toolchainBase) ToolPath() string {
+	return ""
+}
+
 type toolchain64Bit struct {
 	toolchainBase
 }
@@ -216,3 +222,10 @@
 	}
 	return "libclang_rt.ubsan_standalone-" + arch + "-android.so"
 }
+
+func ToolPath(t Toolchain) string {
+	if p := t.ToolPath(); p != "" {
+		return p
+	}
+	return filepath.Join(t.GccRoot(), t.GccTriple(), "bin")
+}
diff --git a/cc/config/x86_darwin_host.go b/cc/config/x86_darwin_host.go
index 18acef8..b6b08fe 100644
--- a/cc/config/x86_darwin_host.go
+++ b/cc/config/x86_darwin_host.go
@@ -17,6 +17,7 @@
 import (
 	"fmt"
 	"os/exec"
+	"path/filepath"
 	"strings"
 
 	"android/soong/android"
@@ -131,6 +132,11 @@
 		return strings.TrimSpace(string(bytes)), err
 	})
 
+	pctx.VariableFunc("MacToolPath", func(config interface{}) (string, error) {
+		bytes, err := exec.Command("xcrun", "--find", "ld").Output()
+		return filepath.Dir(strings.TrimSpace(string(bytes))), err
+	})
+
 	pctx.StaticVariable("DarwinGccVersion", darwinGccVersion)
 	pctx.SourcePathVariable("DarwinGccRoot",
 		"prebuilts/gcc/${HostPrebuiltTag}/host/i686-apple-darwin-${DarwinGccVersion}")
@@ -276,6 +282,10 @@
 	return false
 }
 
+func (t *toolchainDarwin) ToolPath() string {
+	return "${config.MacToolPath}"
+}
+
 var toolchainDarwinX86Singleton Toolchain = &toolchainDarwinX86{}
 var toolchainDarwinX8664Singleton Toolchain = &toolchainDarwinX8664{}
 
diff --git a/cc/config/x86_linux_bionic_host.go b/cc/config/x86_linux_bionic_host.go
new file mode 100644
index 0000000..bd6cd0e
--- /dev/null
+++ b/cc/config/x86_linux_bionic_host.go
@@ -0,0 +1,168 @@
+// Copyright 2016 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 config
+
+import (
+	"strings"
+
+	"android/soong/android"
+)
+
+var (
+	linuxBionicCflags = ClangFilterUnknownCflags([]string{
+		"-fno-exceptions", // from build/core/combo/select.mk
+		"-Wno-multichar",  // from build/core/combo/select.mk
+
+		"-fdiagnostics-color",
+
+		"-Wa,--noexecstack",
+
+		"-fPIC",
+		"-no-canonical-prefixes",
+
+		"-U_FORTIFY_SOURCE",
+		"-D_FORTIFY_SOURCE=2",
+		"-fstack-protector-strong",
+
+		// From x86_64_device
+		"-ffunction-sections",
+		"-finline-functions",
+		"-finline-limit=300",
+		"-fno-short-enums",
+		"-funswitch-loops",
+		"-funwind-tables",
+		"-no-canonical-prefixes",
+		"-fno-canonical-system-headers",
+
+		// HOST_RELEASE_CFLAGS
+		"-O2", // from build/core/combo/select.mk
+		"-g",  // from build/core/combo/select.mk
+		"-fno-strict-aliasing", // from build/core/combo/select.mk
+
+		// Tell clang where the gcc toolchain is
+		"--gcc-toolchain=${LinuxBionicGccRoot}",
+
+		// TODO: We're not really android, but we don't have a triple yet b/31393676
+		"-U__ANDROID__",
+		"-fno-emulated-tls",
+
+		// This is normally in ClangExtraTargetCflags, but this is considered host
+		"-nostdlibinc",
+	})
+
+	linuxBionicLdflags = ClangFilterUnknownCflags([]string{
+		"-Wl,-z,noexecstack",
+		"-Wl,-z,relro",
+		"-Wl,-z,now",
+		"-Wl,--build-id=md5",
+		"-Wl,--warn-shared-textrel",
+		"-Wl,--fatal-warnings",
+		"-Wl,--gc-sections",
+		"-Wl,--hash-style=gnu",
+		"-Wl,--no-undefined-version",
+
+		// Use the device gcc toolchain
+		"--gcc-toolchain=${LinuxBionicGccRoot}",
+	})
+)
+
+func init() {
+	pctx.StaticVariable("LinuxBionicCflags", strings.Join(linuxBionicCflags, " "))
+	pctx.StaticVariable("LinuxBionicLdflags", strings.Join(linuxBionicLdflags, " "))
+
+	pctx.StaticVariable("LinuxBionicIncludeFlags", bionicHeaders("x86_64", "x86"))
+
+	// Use the device gcc toolchain for now
+	pctx.StaticVariable("LinuxBionicGccRoot", "${X86_64GccRoot}")
+}
+
+type toolchainLinuxBionic struct {
+	toolchain64Bit
+}
+
+func (t *toolchainLinuxBionic) Name() string {
+	return "x86_64"
+}
+
+func (t *toolchainLinuxBionic) GccRoot() string {
+	return "${config.LinuxBionicGccRoot}"
+}
+
+func (t *toolchainLinuxBionic) GccTriple() string {
+	return "x86_64-linux-android"
+}
+
+func (t *toolchainLinuxBionic) GccVersion() string {
+	return "4.9"
+}
+
+func (t *toolchainLinuxBionic) Cflags() string {
+	return ""
+}
+
+func (t *toolchainLinuxBionic) Cppflags() string {
+	return ""
+}
+
+func (t *toolchainLinuxBionic) Ldflags() string {
+	return ""
+}
+
+func (t *toolchainLinuxBionic) IncludeFlags() string {
+	return "${config.LinuxBionicIncludeFlags}"
+}
+
+func (t *toolchainLinuxBionic) ClangTriple() string {
+	// TODO: we don't have a triple yet b/31393676
+	return "x86_64-linux-android"
+}
+
+func (t *toolchainLinuxBionic) ClangCflags() string {
+	return "${config.LinuxBionicCflags}"
+}
+
+func (t *toolchainLinuxBionic) ClangCppflags() string {
+	return ""
+}
+
+func (t *toolchainLinuxBionic) ClangLdflags() string {
+	return "${config.LinuxBionicLdflags}"
+}
+
+func (t *toolchainLinuxBionic) ToolchainClangCflags() string {
+	return "-m64 -march=x86-64"
+}
+
+func (t *toolchainLinuxBionic) ToolchainClangLdflags() string {
+	return "-m64"
+}
+
+func (t *toolchainLinuxBionic) AvailableLibraries() []string {
+	return nil
+}
+
+func (t *toolchainLinuxBionic) Bionic() bool {
+	return true
+}
+
+var toolchainLinuxBionicSingleton Toolchain = &toolchainLinuxBionic{}
+
+func linuxBionicToolchainFactory(arch android.Arch) Toolchain {
+	return toolchainLinuxBionicSingleton
+}
+
+func init() {
+	registerToolchainFactory(android.LinuxBionic, android.X86_64, linuxBionicToolchainFactory)
+}
diff --git a/cc/config/x86_windows_host.go b/cc/config/x86_windows_host.go
index 4aad9c8..4709823 100644
--- a/cc/config/x86_windows_host.go
+++ b/cc/config/x86_windows_host.go
@@ -69,6 +69,7 @@
 
 	windowsX86Ldflags = []string{
 		"-m32",
+		"-Wl,--large-address-aware",
 		"-L${WindowsGccRoot}/${WindowsGccTriple}/lib32",
 	}
 
diff --git a/cc/installer.go b/cc/installer.go
index 64f87d9..de04ab6 100644
--- a/cc/installer.go
+++ b/cc/installer.go
@@ -47,6 +47,7 @@
 
 	dir      string
 	dir64    string
+	subDir   string
 	relative string
 	location installLocation
 
@@ -60,14 +61,14 @@
 }
 
 func (installer *baseInstaller) installDir(ctx ModuleContext) android.OutputPath {
-	subDir := installer.dir
+	dir := installer.dir
 	if ctx.toolchain().Is64Bit() && installer.dir64 != "" {
-		subDir = installer.dir64
+		dir = installer.dir64
 	}
 	if !ctx.Host() && !ctx.Arch().Native {
-		subDir = filepath.Join(subDir, ctx.Arch().ArchType.String())
+		dir = filepath.Join(dir, ctx.Arch().ArchType.String())
 	}
-	return android.PathForModuleInstall(ctx, subDir, installer.Properties.Relative_install_path, installer.relative)
+	return android.PathForModuleInstall(ctx, dir, installer.subDir, installer.Properties.Relative_install_path, installer.relative)
 }
 
 func (installer *baseInstaller) install(ctx ModuleContext, file android.Path) {
diff --git a/cc/library.go b/cc/library.go
index f7194e4..0ce84a1 100644
--- a/cc/library.go
+++ b/cc/library.go
@@ -246,7 +246,7 @@
 			sharedFlag = "-shared"
 		}
 		var f []string
-		if ctx.Device() {
+		if ctx.toolchain().Bionic() {
 			f = append(f,
 				"-nostdlib",
 				"-Wl,--gc-sections",
@@ -587,6 +587,26 @@
 
 func (library *libraryDecorator) install(ctx ModuleContext, file android.Path) {
 	if !ctx.static() {
+		if ctx.Device() {
+			if ctx.isNdk() {
+				library.baseInstaller.subDir = "ndk"
+				if ctx.Proprietary() {
+					ctx.ModuleErrorf("NDK library must not be proprietary")
+				}
+			} else if ctx.isVndk() {
+				library.baseInstaller.subDir = "vndk"
+				if ctx.Proprietary() {
+					ctx.ModuleErrorf("VNDK library must not be proprietary")
+				}
+			} else if ctx.isSameProcessHal() {
+				library.baseInstaller.subDir = "sameprocess"
+				if !ctx.Proprietary() {
+					ctx.ModuleErrorf("SameProcess HAL library must be proprietary")
+				}
+			} else {
+				// Do nothing for other types of lib
+			}
+		}
 		library.baseInstaller.install(ctx, file)
 	}
 }
diff --git a/cc/makevars.go b/cc/makevars.go
index e4d8fe6..3ab7955 100644
--- a/cc/makevars.go
+++ b/cc/makevars.go
@@ -16,7 +16,6 @@
 
 import (
 	"fmt"
-	"path/filepath"
 	"sort"
 	"strings"
 
@@ -59,6 +58,7 @@
 		ctx.Strict("BOARD_VNDK_VERSION", "")
 	}
 	ctx.Strict("VNDK_LIBRARIES", strings.Join(config.VndkLibraries(), " "))
+	ctx.Strict("VNDK_INDIRECT_LIBRARIES", strings.Join(config.VndkIndirectLibraries(), " "))
 
 	ctx.Strict("ADDRESS_SANITIZER_CONFIG_EXTRA_CFLAGS", asanCflags)
 	ctx.Strict("ADDRESS_SANITIZER_CONFIG_EXTRA_LDFLAGS", asanLdflags)
@@ -186,9 +186,7 @@
 	if toolchain.ClangSupported() {
 		clangPrefix := secondPrefix + "CLANG_" + typePrefix
 		clangExtras := "-target " + toolchain.ClangTriple()
-		if target.Os != android.Darwin {
-			clangExtras += " -B" + filepath.Join(toolchain.GccRoot(), toolchain.GccTriple(), "bin")
-		}
+		clangExtras += " -B" + config.ToolPath(toolchain)
 
 		ctx.Strict(clangPrefix+"GLOBAL_CFLAGS", strings.Join([]string{
 			toolchain.ClangCflags(),
diff --git a/cc/ndk_headers.go b/cc/ndk_headers.go
index a40fc72..e4a790f 100644
--- a/cc/ndk_headers.go
+++ b/cc/ndk_headers.go
@@ -138,12 +138,7 @@
 
 func ndkHeadersFactory() (blueprint.Module, []interface{}) {
 	module := &headerModule{}
-	// Host module rather than device module because device module install steps
-	// do not get run when embedded in make. We're not any of the existing
-	// module types that can be exposed via the Android.mk exporter, so just use
-	// a host module.
-	return android.InitAndroidArchModule(module, android.HostSupportedNoCross,
-		android.MultilibFirst, &module.properties)
+	return android.InitAndroidModule(module, &module.properties)
 }
 
 type preprocessedHeaderProperies struct {
diff --git a/cc/util.go b/cc/util.go
index 570052e..919e14c 100644
--- a/cc/util.go
+++ b/cc/util.go
@@ -88,6 +88,7 @@
 func flagsToBuilderFlags(in Flags) builderFlags {
 	return builderFlags{
 		globalFlags: strings.Join(in.GlobalFlags, " "),
+		arFlags:     strings.Join(in.ArFlags, " "),
 		asFlags:     strings.Join(in.AsFlags, " "),
 		cFlags:      strings.Join(in.CFlags, " "),
 		conlyFlags:  strings.Join(in.ConlyFlags, " "),
diff --git a/cc/vndk_library.go b/cc/vndk_library.go
new file mode 100644
index 0000000..cca4f3f
--- /dev/null
+++ b/cc/vndk_library.go
@@ -0,0 +1,85 @@
+// 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 cc
+
+import (
+	"github.com/google/blueprint"
+
+	"android/soong/android"
+	"android/soong/cc/config"
+)
+
+type vndkExtLibraryProperties struct {
+	// Name of the VNDK library module that this VNDK-ext library is extending.
+	// This library will have the same file name and soname as the original VNDK
+	// library, but will be installed in /system/lib/vndk-ext rather
+	// than /system/lib/vndk.
+	Extends string
+}
+
+type vndkExtLibraryDecorator struct {
+	*libraryDecorator
+
+	properties vndkExtLibraryProperties
+}
+
+func init() {
+	android.RegisterModuleType("vndk_ext_library", vndkExtLibraryFactory)
+}
+
+func (deco *vndkExtLibraryDecorator) linkerFlags(ctx ModuleContext, flags Flags) Flags {
+	extends := deco.properties.Extends
+	if extends != "" {
+		if config.IsVndkLibrary(extends) {
+			// TODO(jiyong): ensure that the module referenced by 'extends' exists. Don't know how...
+			// Adding a dependency was not successful because it leads to circular dependency
+			// in between this and the 'extends' module.
+			// Ideally, this should be something like follows:
+			// otherCtx = findModuleByName(deco.properties.Extends)
+			// if otherCtx != nil && otherCtx.isVndk() {
+			//     deco.libaryDecorator.libName = otherCtx.getBaseName()
+			// }
+			deco.libraryDecorator.libName = extends
+		} else {
+			ctx.PropertyErrorf("extends", "%s should be a VNDK or VNDK-indirect library", extends)
+		}
+	} else {
+		ctx.PropertyErrorf("extends", "missing. A VNDK-ext library must extend existing VNDK library")
+	}
+	return deco.libraryDecorator.linkerFlags(ctx, flags)
+}
+
+func (deco *vndkExtLibraryDecorator) install(ctx ModuleContext, file android.Path) {
+	deco.libraryDecorator.baseInstaller.subDir = "vndk-ext"
+	deco.libraryDecorator.baseInstaller.install(ctx, file)
+}
+
+func vndkExtLibraryFactory() (blueprint.Module, []interface{}) {
+	module, library := NewLibrary(android.DeviceSupported)
+	library.BuildOnlyShared()
+
+	_, props := module.Init()
+
+	deco := &vndkExtLibraryDecorator{
+		libraryDecorator: library,
+	}
+
+	module.installer = deco
+	module.linker = deco
+
+	props = append(props, &deco.properties)
+
+	return module, props
+}
diff --git a/cmd/soong_zip/soong_zip.go b/cmd/soong_zip/soong_zip.go
index b0f3daa..1ec2265 100644
--- a/cmd/soong_zip/soong_zip.go
+++ b/cmd/soong_zip/soong_zip.go
@@ -357,6 +357,7 @@
 
 func (z *zipWriter) writeFile(rel, file string) error {
 	var fileSize int64
+	var executable bool
 
 	if s, err := os.Lstat(file); err != nil {
 		return err
@@ -371,6 +372,7 @@
 		return fmt.Errorf("%s is not a file, directory, or symlink", file)
 	} else {
 		fileSize = s.Size()
+		executable = s.Mode()&0100 != 0
 	}
 
 	if z.directories {
@@ -395,6 +397,9 @@
 		},
 	}
 	ze.fh.SetModTime(z.time)
+	if executable {
+		ze.fh.SetMode(0700)
+	}
 
 	r, err := os.Open(file)
 	if err != nil {
@@ -445,7 +450,7 @@
 			f.Close()
 		}(wg, r)
 	} else {
-		go z.compressWholeFile(rel, r, exec, compressChan)
+		go z.compressWholeFile(ze, r, exec, compressChan)
 	}
 
 	return nil
@@ -514,26 +519,19 @@
 	return buf, nil
 }
 
-func (z *zipWriter) compressWholeFile(rel string, r *os.File, exec Execution, compressChan chan *zipEntry) {
+func (z *zipWriter) compressWholeFile(ze *zipEntry, r *os.File, exec Execution, compressChan chan *zipEntry) {
 	var bufSize int
 
 	defer r.Close()
 
-	fileHeader := &zip.FileHeader{
-		Name:   rel,
-		Method: zip.Deflate,
-	}
-	fileHeader.SetModTime(z.time)
-
 	crc := crc32.NewIEEE()
-	count, err := io.Copy(crc, r)
+	_, err := io.Copy(crc, r)
 	if err != nil {
 		z.errors <- err
 		return
 	}
 
-	fileHeader.CRC32 = crc.Sum32()
-	fileHeader.UncompressedSize64 = uint64(count)
+	ze.fh.CRC32 = crc.Sum32()
 
 	_, err = r.Seek(0, 0)
 	if err != nil {
@@ -543,10 +541,7 @@
 
 	compressed, err := z.compressBlock(r, nil, true)
 
-	ze := &zipEntry{
-		fh:            fileHeader,
-		futureReaders: make(chan chan io.Reader, 1),
-	}
+	ze.futureReaders = make(chan chan io.Reader, 1)
 	futureReader := make(chan io.Reader, 1)
 	ze.futureReaders <- futureReader
 	close(ze.futureReaders)