Merge "Check system certificate violation for product apks"
diff --git a/Android.bp b/Android.bp
index 29ad569..d5f052e 100644
--- a/Android.bp
+++ b/Android.bp
@@ -249,6 +249,7 @@
         "java/java_resources.go",
         "java/prebuilt_apis.go",
         "java/proto.go",
+        "java/sdk.go",
         "java/sdk_library.go",
         "java/support_libraries.go",
         "java/system_modules.go",
@@ -258,6 +259,7 @@
         "java/dexpreopt_test.go",
         "java/java_test.go",
         "java/jdeps_test.go",
+        "java/sdk_test.go",
     ],
     pluginFor: ["soong_build"],
 }
diff --git a/androidmk/cmd/androidmk/android.go b/androidmk/cmd/androidmk/android.go
index c8228ed..a28cf49 100644
--- a/androidmk/cmd/androidmk/android.go
+++ b/androidmk/cmd/androidmk/android.go
@@ -158,6 +158,10 @@
 			"LOCAL_SHARED_ANDROID_LIBRARIES": "android_libs",
 			"LOCAL_STATIC_ANDROID_LIBRARIES": "android_static_libs",
 			"LOCAL_ADDITIONAL_CERTIFICATES":  "additional_certificates",
+
+			// Jacoco filters:
+			"LOCAL_JACK_COVERAGE_INCLUDE_FILTER": "jacoco.include_filter",
+			"LOCAL_JACK_COVERAGE_EXCLUDE_FILTER": "jacoco.exclude_filter",
 		})
 
 	addStandardProperties(bpparser.BoolType,
diff --git a/androidmk/cmd/androidmk/androidmk_test.go b/androidmk/cmd/androidmk/androidmk_test.go
index 40fc9f3..c750f22 100644
--- a/androidmk/cmd/androidmk/androidmk_test.go
+++ b/androidmk/cmd/androidmk/androidmk_test.go
@@ -643,12 +643,14 @@
 			include $(CLEAR_VARS)
 			LOCAL_SRC_FILES := test.java
 			LOCAL_RESOURCE_DIR := res
+			LOCAL_JACK_COVERAGE_INCLUDE_FILTER := foo.*
 			include $(BUILD_STATIC_JAVA_LIBRARY)
 
 			include $(CLEAR_VARS)
 			LOCAL_SRC_FILES := test.java
 			LOCAL_STATIC_LIBRARIES := foo
 			LOCAL_STATIC_ANDROID_LIBRARIES := bar
+			LOCAL_JACK_COVERAGE_EXCLUDE_FILTER := bar.*
 			include $(BUILD_STATIC_JAVA_LIBRARY)
 
 			include $(CLEAR_VARS)
@@ -666,6 +668,9 @@
 			android_library {
 				srcs: ["test.java"],
 				resource_dirs: ["res"],
+				jacoco: {
+					include_filter: ["foo.*"],
+				},
 			}
 
 			android_library {
@@ -674,6 +679,9 @@
 					"foo",
 					"bar",
 				],
+				jacoco: {
+					exclude_filter: ["bar.*"],
+				},
 			}
 
 			android_library {
diff --git a/apex/apex.go b/apex/apex.go
index 1d50cee..9f5a46c 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -492,6 +492,19 @@
 	if !cc.Arch().Native {
 		dirInApex = filepath.Join(dirInApex, cc.Arch().ArchType.String())
 	}
+	switch cc.Name() {
+	case "libc", "libm", "libdl":
+		// Special case for bionic libs. This is to prevent the bionic libs
+		// from being included in the search path /apex/com.android.apex/lib.
+		// This exclusion is required because bionic libs in the runtime APEX
+		// are available via the legacy paths /system/lib/libc.so, etc. By the
+		// init process, the bionic libs in the APEX are bind-mounted to the
+		// legacy paths and thus will be loaded into the default linker namespace.
+		// If the bionic libs are directly in /apex/com.android.apex/lib then
+		// the same libs will be again loaded to the runtime linker namespace,
+		// which will result double loading of bionic libs that isn't supported.
+		dirInApex = filepath.Join(dirInApex, "bionic")
+	}
 
 	fileToCopy = cc.OutputFile().Path()
 	return
@@ -837,7 +850,15 @@
 		// For flattened APEX, do nothing but make sure that apex_manifest.json file is also copied along
 		// with other ordinary files.
 		manifest := android.PathForModuleSrc(ctx, proptools.StringDefault(a.properties.Manifest, "apex_manifest.json"))
-		a.filesInfo = append(a.filesInfo, apexFile{manifest, ctx.ModuleName() + ".apex_manifest.json", android.Common, ".", etc, nil})
+
+		// rename to apex_manifest.json
+		copiedManifest := android.PathForModuleOut(ctx, "apex_manifest.json")
+		ctx.Build(pctx, android.BuildParams{
+			Rule:   android.Cp,
+			Input:  manifest,
+			Output: copiedManifest,
+		})
+		a.filesInfo = append(a.filesInfo, apexFile{copiedManifest, ctx.ModuleName() + ".apex_manifest.json", android.Common, ".", etc, nil})
 
 		for _, fi := range a.filesInfo {
 			dir := filepath.Join("apex", ctx.ModuleName(), fi.installDir)
diff --git a/apex/apex_test.go b/apex/apex_test.go
index f8f9b33..d4f0f7e 100644
--- a/apex/apex_test.go
+++ b/apex/apex_test.go
@@ -492,6 +492,13 @@
 				versions: ["27", "28", "29"],
 			},
 		}
+
+		cc_library {
+			name: "libBootstrap",
+			srcs: ["mylib.cpp"],
+			stl: "none",
+			bootstrap: true,
+		}
 	`)
 
 	apexRule := ctx.ModuleForTests("myapex", "android_common_myapex").Rule("apexRule")
@@ -499,11 +506,11 @@
 
 	// Ensure that mylib, libm, libdl are included.
 	ensureContains(t, copyCmds, "image.apex/lib64/mylib.so")
-	ensureContains(t, copyCmds, "image.apex/lib64/libm.so")
-	ensureContains(t, copyCmds, "image.apex/lib64/libdl.so")
+	ensureContains(t, copyCmds, "image.apex/lib64/bionic/libm.so")
+	ensureContains(t, copyCmds, "image.apex/lib64/bionic/libdl.so")
 
 	// Ensure that libc is not included (since it has stubs and not listed in native_shared_libs)
-	ensureNotContains(t, copyCmds, "image.apex/lib64/libc.so")
+	ensureNotContains(t, copyCmds, "image.apex/lib64/bionic/libc.so")
 
 	mylibLdFlags := ctx.ModuleForTests("mylib", "android_arm64_armv8-a_core_shared_myapex").Rule("ld").Args["libFlags"]
 	mylibCFlags := ctx.ModuleForTests("mylib", "android_arm64_armv8-a_core_static_myapex").Rule("cc").Args["cFlags"]
@@ -538,6 +545,12 @@
 	// ... Cflags from stub is correctly exported to mylib
 	ensureContains(t, mylibCFlags, "__LIBDL_API__=27")
 	ensureContains(t, mylibSharedCFlags, "__LIBDL_API__=27")
+
+	// Ensure that libBootstrap is depending on the platform variant of bionic libs
+	libFlags := ctx.ModuleForTests("libBootstrap", "android_arm64_armv8-a_core_shared").Rule("ld").Args["libFlags"]
+	ensureContains(t, libFlags, "libc/android_arm64_armv8-a_core_shared/libc.so")
+	ensureContains(t, libFlags, "libm/android_arm64_armv8-a_core_shared/libm.so")
+	ensureContains(t, libFlags, "libdl/android_arm64_armv8-a_core_shared/libdl.so")
 }
 
 func TestFilesInSubDir(t *testing.T) {
diff --git a/cc/androidmk.go b/cc/androidmk.go
index 82feec8..7844756 100644
--- a/cc/androidmk.go
+++ b/cc/androidmk.go
@@ -29,9 +29,12 @@
 )
 
 type AndroidMkContext interface {
+	Name() string
 	Target() android.Target
 	subAndroidMk(*android.AndroidMkData, interface{})
 	useVndk() bool
+	static() bool
+	inRecovery() bool
 }
 
 type subAndroidMkProvider interface {
@@ -59,8 +62,12 @@
 
 	ret := android.AndroidMkData{
 		OutputFile: c.outputFile,
-		Required:   append(c.Properties.AndroidMkRuntimeLibs, c.Properties.ApexesProvidingSharedLibs...),
-		Include:    "$(BUILD_SYSTEM)/soong_cc_prebuilt.mk",
+		// TODO(jiyong): add the APEXes providing shared libs to the required modules
+		// Currently, adding c.Properties.ApexesProvidingSharedLibs is causing multiple
+		// runtime APEXes (com.android.runtime.debug|release) to be installed. And this
+		// is breaking some older devices (like marlin) where system.img is small.
+		Required: c.Properties.AndroidMkRuntimeLibs,
+		Include:  "$(BUILD_SYSTEM)/soong_cc_prebuilt.mk",
 
 		Extra: []android.AndroidMkExtraFunc{
 			func(w io.Writer, outputFile android.Path) {
@@ -172,13 +179,23 @@
 		}
 	})
 
-	if library.shared() {
+	if library.shared() && !library.buildStubs() {
 		ctx.subAndroidMk(ret, library.baseInstaller)
 	} else {
 		ret.Extra = append(ret.Extra, func(w io.Writer, outputFile android.Path) {
 			fmt.Fprintln(w, "LOCAL_UNINSTALLABLE_MODULE := true")
+			if library.buildStubs() {
+				fmt.Fprintln(w, "LOCAL_NO_NOTICE_FILE := true")
+			}
 		})
 	}
+
+	if len(library.Properties.Stubs.Versions) > 0 && android.DirectlyInAnyApex(ctx.Name()) &&
+		!ctx.inRecovery() && !ctx.useVndk() && !ctx.static() {
+		if !library.buildStubs() {
+			ret.SubName = ".bootstrap"
+		}
+	}
 }
 
 func (object *objectLinker) AndroidMk(ctx AndroidMkContext, ret *android.AndroidMkData) {
diff --git a/cc/cc.go b/cc/cc.go
index ce28a3b..85e3a67 100644
--- a/cc/cc.go
+++ b/cc/cc.go
@@ -201,6 +201,10 @@
 	Recovery_available *bool
 
 	InRecovery bool `blueprint:"mutated"`
+
+	// Allows this module to use non-APEX version of libraries. Useful
+	// for building binaries that are started before APEXes are activated.
+	Bootstrap *bool
 }
 
 type VendorProperties struct {
@@ -250,6 +254,8 @@
 	isPgoCompile() bool
 	useClangLld(actx ModuleContext) bool
 	isApex() bool
+	hasStubsVariants() bool
+	isStubs() bool
 }
 
 type ModuleContext interface {
@@ -676,6 +682,14 @@
 	return ctx.mod.ApexName() != ""
 }
 
+func (ctx *moduleContextImpl) hasStubsVariants() bool {
+	return ctx.mod.HasStubsVariants()
+}
+
+func (ctx *moduleContextImpl) isStubs() bool {
+	return ctx.mod.IsStubs()
+}
+
 func newBaseModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
 	return &Module{
 		hod:      hod,
@@ -855,6 +869,18 @@
 			return
 		}
 		c.outputFile = android.OptionalPathForPath(outputFile)
+
+		// If a lib is directly included in any of the APEXes, unhide the stubs
+		// variant having the latest version gets visible to make. In addition,
+		// the non-stubs variant is renamed to <libname>.bootstrap. This is to
+		// force anything in the make world to link against the stubs library.
+		// (unless it is explicitly referenced via .bootstrap suffix or the
+		// module is marked with 'bootstrap: true').
+		if c.HasStubsVariants() && android.DirectlyInAnyApex(ctx.baseModuleName()) &&
+			!c.inRecovery() && !c.useVndk() && !c.static() && c.IsStubs() {
+			c.Properties.HideFromMake = false // unhide
+			// Note: this is still non-installable
+		}
 	}
 
 	if c.installer != nil && !c.Properties.PreventInstall && c.IsForPlatform() && c.outputFile.Valid() {
@@ -1446,8 +1472,8 @@
 					// If not building for APEX, use stubs only when it is from
 					// an APEX (and not from platform)
 					useThisDep = (depInPlatform != depIsStubs)
-					if c.inRecovery() {
-						// However, for recovery modules, since there is no APEX there,
+					if c.inRecovery() || Bool(c.Properties.Bootstrap) {
+						// However, for recovery or bootstrap modules,
 						// always link to non-stub variant
 						useThisDep = !depIsStubs
 					}
diff --git a/dexpreopt/config.go b/dexpreopt/config.go
index 13a14f4..6b5c40d 100644
--- a/dexpreopt/config.go
+++ b/dexpreopt/config.go
@@ -113,6 +113,7 @@
 
 	PresignedPrebuilt bool
 
+	NoStripping     bool
 	StripInputPath  string
 	StripOutputPath string
 }
diff --git a/dexpreopt/dexpreopt.go b/dexpreopt/dexpreopt.go
index 4ad039f..f316be4 100644
--- a/dexpreopt/dexpreopt.go
+++ b/dexpreopt/dexpreopt.go
@@ -95,11 +95,38 @@
 
 	rule = &Rule{}
 
-	dexpreoptDisabled := contains(global.DisablePreoptModules, module.Name)
+	generateProfile := module.ProfileClassListing != "" && !global.DisableGenerateProfile
 
-	if contains(global.BootJars, module.Name) {
-		// Don't preopt individual boot jars, they will be preopted together
-		dexpreoptDisabled = true
+	var profile string
+	if generateProfile {
+		profile = profileCommand(global, module, rule)
+	}
+
+	if !dexpreoptDisabled(global, module) {
+		// Don't preopt individual boot jars, they will be preopted together.
+		// This check is outside dexpreoptDisabled because they still need to be stripped.
+		if !contains(global.BootJars, module.Name) {
+			appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
+				!module.NoCreateAppImage
+
+			generateDM := shouldGenerateDM(module, global)
+
+			for _, arch := range module.Archs {
+				imageLocation := module.DexPreoptImageLocation
+				if imageLocation == "" {
+					imageLocation = global.DefaultDexPreoptImageLocation[arch]
+				}
+				dexpreoptCommand(global, module, rule, profile, arch, imageLocation, appImage, generateDM)
+			}
+		}
+	}
+
+	return rule, nil
+}
+
+func dexpreoptDisabled(global GlobalConfig, module ModuleConfig) bool {
+	if contains(global.DisablePreoptModules, module.Name) {
+		return true
 	}
 
 	// If OnlyPreoptBootImageAndSystemServer=true and module is not in boot class path skip
@@ -108,32 +135,10 @@
 	// or performance. If PreoptExtractedApk is true, we ignore the only preopt boot image options.
 	if global.OnlyPreoptBootImageAndSystemServer && !contains(global.BootJars, module.Name) &&
 		!contains(global.SystemServerJars, module.Name) && !module.PreoptExtractedApk {
-		dexpreoptDisabled = true
+		return true
 	}
 
-	generateProfile := module.ProfileClassListing != "" && !global.DisableGenerateProfile
-
-	var profile string
-	if generateProfile {
-		profile = profileCommand(global, module, rule)
-	}
-
-	if !dexpreoptDisabled {
-		appImage := (generateProfile || module.ForceCreateAppImage || global.DefaultAppImages) &&
-			!module.NoCreateAppImage
-
-		generateDM := shouldGenerateDM(module, global)
-
-		for _, arch := range module.Archs {
-			imageLocation := module.DexPreoptImageLocation
-			if imageLocation == "" {
-				imageLocation = global.DefaultDexPreoptImageLocation[arch]
-			}
-			dexpreoptCommand(global, module, rule, profile, arch, imageLocation, appImage, generateDM)
-		}
-	}
-
-	return rule, nil
+	return false
 }
 
 func profileCommand(global GlobalConfig, module ModuleConfig, rule *Rule) string {
@@ -445,6 +450,14 @@
 func shouldStripDex(module ModuleConfig, global GlobalConfig) bool {
 	strip := !global.DefaultNoStripping
 
+	if dexpreoptDisabled(global, module) {
+		strip = false
+	}
+
+	if module.NoStripping {
+		strip = false
+	}
+
 	// Don't strip modules that are not on the system partition in case the oat/vdex version in system ROM
 	// doesn't match the one in other partitions. It needs to be able to fall back to the APK for that case.
 	if !strings.HasPrefix(module.DexLocation, SystemPartition) {
diff --git a/dexpreopt/dexpreopt_test.go b/dexpreopt/dexpreopt_test.go
index fef85a7..f218d01 100644
--- a/dexpreopt/dexpreopt_test.go
+++ b/dexpreopt/dexpreopt_test.go
@@ -82,6 +82,7 @@
 	NoCreateAppImage:       false,
 	ForceCreateAppImage:    false,
 	PresignedPrebuilt:      false,
+	NoStripping:            false,
 	StripInputPath:         "",
 	StripOutputPath:        "",
 }
@@ -162,47 +163,60 @@
 }
 
 func TestStripDex(t *testing.T) {
-	global, module := testGlobalConfig, testModuleConfig
-
-	module.Name = "test"
-	module.DexLocation = "/system/app/test/test.apk"
-	module.BuildPath = "out/test/test.apk"
-	module.Archs = []string{"arm"}
-	module.StripInputPath = "$1"
-	module.StripOutputPath = "$2"
-
-	rule, err := GenerateStripRule(global, module)
-	if err != nil {
-		t.Error(err)
+	tests := []struct {
+		name  string
+		setup func(global *GlobalConfig, module *ModuleConfig)
+		strip bool
+	}{
+		{
+			name:  "default strip",
+			setup: func(global *GlobalConfig, module *ModuleConfig) {},
+			strip: true,
+		},
+		{
+			name:  "global no stripping",
+			setup: func(global *GlobalConfig, module *ModuleConfig) { global.DefaultNoStripping = true },
+			strip: false,
+		},
+		{
+			name:  "module no stripping",
+			setup: func(global *GlobalConfig, module *ModuleConfig) { module.NoStripping = true },
+			strip: false,
+		},
 	}
 
-	want := `zip2zip -i $1 -o $2 -x "classes*.dex"`
-	if len(rule.Commands()) < 1 || !strings.Contains(rule.Commands()[0], want) {
-		t.Errorf("\nwant commands[0] to have:\n   %v\ngot:\n   %v", want, rule.Commands()[0])
-	}
-}
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
 
-func TestNoStripDex(t *testing.T) {
-	global, module := testGlobalConfig, testModuleConfig
+			global, module := testGlobalConfig, testModuleConfig
 
-	global.DefaultNoStripping = true
+			module.Name = "test"
+			module.DexLocation = "/system/app/test/test.apk"
+			module.BuildPath = "out/test/test.apk"
+			module.Archs = []string{"arm"}
+			module.StripInputPath = "$1"
+			module.StripOutputPath = "$2"
 
-	module.Name = "test"
-	module.DexLocation = "/system/app/test/test.apk"
-	module.BuildPath = "out/test/test.apk"
-	module.Archs = []string{"arm"}
-	module.StripInputPath = "$1"
-	module.StripOutputPath = "$2"
+			test.setup(&global, &module)
 
-	rule, err := GenerateStripRule(global, module)
-	if err != nil {
-		t.Error(err)
-	}
+			rule, err := GenerateStripRule(global, module)
+			if err != nil {
+				t.Error(err)
+			}
 
-	wantCommands := []string{
-		"cp -f $1 $2",
-	}
-	if !reflect.DeepEqual(rule.Commands(), wantCommands) {
-		t.Errorf("\nwant commands:\n   %v\ngot:\n   %v", wantCommands, rule.Commands())
+			if test.strip {
+				want := `zip2zip -i $1 -o $2 -x "classes*.dex"`
+				if len(rule.Commands()) < 1 || !strings.Contains(rule.Commands()[0], want) {
+					t.Errorf("\nwant commands[0] to have:\n   %v\ngot:\n   %v", want, rule.Commands()[0])
+				}
+			} else {
+				wantCommands := []string{
+					"cp -f $1 $2",
+				}
+				if !reflect.DeepEqual(rule.Commands(), wantCommands) {
+					t.Errorf("\nwant commands:\n   %v\ngot:\n   %v", wantCommands, rule.Commands())
+				}
+			}
+		})
 	}
 }
diff --git a/java/dexpreopt.go b/java/dexpreopt.go
index ce51aba..2c8de55 100644
--- a/java/dexpreopt.go
+++ b/java/dexpreopt.go
@@ -43,6 +43,9 @@
 		// true.
 		Enabled *bool
 
+		// If true, never strip the dex files from the final jar when dexpreopting.  Defaults to false.
+		No_stripping *bool
+
 		// If true, generate an app image (.art file) for this module.
 		App_image *bool
 
@@ -171,6 +174,7 @@
 		NoCreateAppImage:    !BoolDefault(d.dexpreoptProperties.Dex_preopt.App_image, true),
 		ForceCreateAppImage: BoolDefault(d.dexpreoptProperties.Dex_preopt.App_image, false),
 
+		NoStripping:     Bool(d.dexpreoptProperties.Dex_preopt.No_stripping),
 		StripInputPath:  dexJarFile.String(),
 		StripOutputPath: strippedDexJarFile.String(),
 	}
diff --git a/java/java.go b/java/java.go
index 8b8e4ba..fa4aee4 100644
--- a/java/java.go
+++ b/java/java.go
@@ -430,154 +430,6 @@
 	return j.sdkVersion()
 }
 
-type sdkContext interface {
-	// sdkVersion eturns 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
-}
-
-func sdkVersionOrDefault(ctx android.BaseContext, v string) string {
-	switch v {
-	case "", "current", "system_current", "test_current", "core_current":
-		return ctx.Config().DefaultAppTargetSdk()
-	default:
-		return v
-	}
-}
-
-// Returns a sdk version as a number.  For modules targeting an unreleased SDK (meaning it does not yet have a number)
-// it returns android.FutureApiLevel (10000).
-func sdkVersionToNumber(ctx android.BaseContext, v string) (int, error) {
-	switch v {
-	case "", "current", "test_current", "system_current", "core_current":
-		return ctx.Config().DefaultAppTargetSdkInt(), nil
-	default:
-		n := android.GetNumericSdkVersion(v)
-		if i, err := strconv.Atoi(n); err != nil {
-			return -1, fmt.Errorf("invalid sdk version %q", n)
-		} else {
-			return i, nil
-		}
-	}
-}
-
-func sdkVersionToNumberAsString(ctx android.BaseContext, v string) (string, error) {
-	n, err := sdkVersionToNumber(ctx, v)
-	if err != nil {
-		return "", err
-	}
-	return strconv.Itoa(n), nil
-}
-
-func decodeSdkDep(ctx android.BaseContext, sdkContext sdkContext) sdkDep {
-	v := sdkContext.sdkVersion()
-	i, err := sdkVersionToNumber(ctx, v)
-	if err != nil {
-		ctx.PropertyErrorf("sdk_version", "%s", err)
-		return sdkDep{}
-	}
-
-	// Ensures that the specificed system SDK version is one of BOARD_SYSTEMSDK_VERSIONS (for vendor apks)
-	// or PRODUCT_SYSTEMSDK_VERSIONS (for other apks or when BOARD_SYSTEMSDK_VERSIONS is not set)
-	if strings.HasPrefix(v, "system_") && i != android.FutureApiLevel {
-		allowed_versions := ctx.DeviceConfig().PlatformSystemSdkVersions()
-		if ctx.DeviceSpecific() || ctx.SocSpecific() {
-			if len(ctx.DeviceConfig().SystemSdkVersions()) > 0 {
-				allowed_versions = ctx.DeviceConfig().SystemSdkVersions()
-			}
-		}
-		version := strings.TrimPrefix(v, "system_")
-		if len(allowed_versions) > 0 && !android.InList(version, allowed_versions) {
-			ctx.PropertyErrorf("sdk_version", "incompatible sdk version %q. System SDK version should be one of %q",
-				v, allowed_versions)
-		}
-	}
-
-	toPrebuilt := func(sdk string) sdkDep {
-		var api, v string
-		if strings.Contains(sdk, "_") {
-			t := strings.Split(sdk, "_")
-			api = t[0]
-			v = t[1]
-		} else {
-			api = "public"
-			v = sdk
-		}
-		dir := filepath.Join("prebuilts", "sdk", v, api)
-		jar := filepath.Join(dir, "android.jar")
-		// There's no aidl for other SDKs yet.
-		// TODO(77525052): Add aidl files for other SDKs too.
-		public_dir := filepath.Join("prebuilts", "sdk", v, "public")
-		aidl := filepath.Join(public_dir, "framework.aidl")
-		jarPath := android.ExistentPathForSource(ctx, jar)
-		aidlPath := android.ExistentPathForSource(ctx, aidl)
-		lambdaStubsPath := android.PathForSource(ctx, config.SdkLambdaStubsPath)
-
-		if (!jarPath.Valid() || !aidlPath.Valid()) && ctx.Config().AllowMissingDependencies() {
-			return sdkDep{
-				invalidVersion: true,
-				modules:        []string{fmt.Sprintf("sdk_%s_%s_android", api, v)},
-			}
-		}
-
-		if !jarPath.Valid() {
-			ctx.PropertyErrorf("sdk_version", "invalid sdk version %q, %q does not exist", v, jar)
-			return sdkDep{}
-		}
-
-		if !aidlPath.Valid() {
-			ctx.PropertyErrorf("sdk_version", "invalid sdk version %q, %q does not exist", v, aidl)
-			return sdkDep{}
-		}
-
-		return sdkDep{
-			useFiles: true,
-			jars:     android.Paths{jarPath.Path(), lambdaStubsPath},
-			aidl:     aidlPath.Path(),
-		}
-	}
-
-	toModule := func(m, r string) sdkDep {
-		ret := sdkDep{
-			useModule:          true,
-			modules:            []string{m, config.DefaultLambdaStubsLibrary},
-			systemModules:      m + "_system_modules",
-			frameworkResModule: r,
-		}
-		if m == "core.current.stubs" {
-			ret.systemModules = "core-system-modules"
-		} else if m == "core.platform.api.stubs" {
-			ret.systemModules = "core-platform-api-stubs-system-modules"
-		}
-		return ret
-	}
-
-	if ctx.Config().UnbundledBuildPrebuiltSdks() && v != "" {
-		return toPrebuilt(v)
-	}
-
-	switch v {
-	case "":
-		return sdkDep{
-			useDefaultLibs:     true,
-			frameworkResModule: "framework-res",
-		}
-	case "current":
-		return toModule("android_stubs_current", "framework-res")
-	case "system_current":
-		return toModule("android_system_stubs_current", "framework-res")
-	case "test_current":
-		return toModule("android_test_stubs_current", "framework-res")
-	case "core_current":
-		return toModule("core.current.stubs", "")
-	default:
-		return toPrebuilt(v)
-	}
-}
-
 func (j *Module) deps(ctx android.BottomUpMutatorContext) {
 	if ctx.Device() {
 		if !Bool(j.properties.No_standard_libs) {
@@ -925,7 +777,18 @@
 
 func getJavaVersion(ctx android.ModuleContext, javaVersion string, sdkContext sdkContext) string {
 	var ret string
-	sdk, err := sdkVersionToNumber(ctx, sdkContext.sdkVersion())
+	v := sdkContext.sdkVersion()
+	// For PDK builds, use the latest SDK version instead of "current"
+	if ctx.Config().IsPdkBuild() && (v == "" || v == "current") {
+		sdkVersions := ctx.Config().Get(sdkSingletonKey).([]int)
+		latestSdkVersion := 0
+		if len(sdkVersions) > 0 {
+			latestSdkVersion = sdkVersions[len(sdkVersions)-1]
+		}
+		v = strconv.Itoa(latestSdkVersion)
+	}
+
+	sdk, err := sdkVersionToNumber(ctx, v)
 	if err != nil {
 		ctx.PropertyErrorf("sdk_version", "%s", err)
 	}
diff --git a/java/java_test.go b/java/java_test.go
index c4cf905..570efb7 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -19,13 +19,10 @@
 	"io/ioutil"
 	"os"
 	"path/filepath"
-	"reflect"
 	"strconv"
 	"strings"
 	"testing"
 
-	"github.com/google/blueprint/proptools"
-
 	"android/soong/android"
 	"android/soong/cc"
 	"android/soong/genrule"
@@ -101,6 +98,7 @@
 		ctx.TopDown("java_sdk_library", sdkLibraryMutator).Parallel()
 	})
 	ctx.RegisterPreSingletonType("overlay", android.SingletonFactoryAdaptor(OverlaySingletonFactory))
+	ctx.RegisterPreSingletonType("sdk", android.SingletonFactoryAdaptor(sdkSingletonFactory))
 
 	// Register module types and mutators from cc needed for JNI testing
 	ctx.RegisterModuleType("cc_library", android.ModuleFactoryAdaptor(cc.LibraryFactory))
@@ -184,6 +182,9 @@
 		"prebuilts/sdk/14/public/android.jar":         nil,
 		"prebuilts/sdk/14/public/framework.aidl":      nil,
 		"prebuilts/sdk/14/system/android.jar":         nil,
+		"prebuilts/sdk/17/public/android.jar":         nil,
+		"prebuilts/sdk/17/public/framework.aidl":      nil,
+		"prebuilts/sdk/17/system/android.jar":         nil,
 		"prebuilts/sdk/current/core/android.jar":      nil,
 		"prebuilts/sdk/current/public/android.jar":    nil,
 		"prebuilts/sdk/current/public/framework.aidl": nil,
@@ -354,241 +355,6 @@
 
 }
 
-var classpathTestcases = []struct {
-	name          string
-	unbundled     bool
-	moduleType    string
-	host          android.OsClass
-	properties    string
-	bootclasspath []string
-	system        string
-	classpath     []string
-}{
-	{
-		name:          "default",
-		bootclasspath: []string{"core.platform.api.stubs", "core-lambda-stubs"},
-		system:        "core-platform-api-stubs-system-modules",
-		classpath:     []string{"ext", "framework"},
-	},
-	{
-		name:          "blank sdk version",
-		properties:    `sdk_version: "",`,
-		bootclasspath: []string{"core.platform.api.stubs", "core-lambda-stubs"},
-		system:        "core-platform-api-stubs-system-modules",
-		classpath:     []string{"ext", "framework"},
-	},
-	{
-
-		name:          "sdk v14",
-		properties:    `sdk_version: "14",`,
-		bootclasspath: []string{`""`},
-		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
-		classpath:     []string{"prebuilts/sdk/14/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
-	},
-	{
-
-		name:          "current",
-		properties:    `sdk_version: "current",`,
-		bootclasspath: []string{"android_stubs_current", "core-lambda-stubs"},
-		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
-	},
-	{
-
-		name:          "system_current",
-		properties:    `sdk_version: "system_current",`,
-		bootclasspath: []string{"android_system_stubs_current", "core-lambda-stubs"},
-		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
-	},
-	{
-
-		name:          "system_14",
-		properties:    `sdk_version: "system_14",`,
-		bootclasspath: []string{`""`},
-		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
-		classpath:     []string{"prebuilts/sdk/14/system/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
-	},
-	{
-
-		name:          "test_current",
-		properties:    `sdk_version: "test_current",`,
-		bootclasspath: []string{"android_test_stubs_current", "core-lambda-stubs"},
-		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
-	},
-	{
-
-		name:          "core_current",
-		properties:    `sdk_version: "core_current",`,
-		bootclasspath: []string{"core.current.stubs", "core-lambda-stubs"},
-		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
-	},
-	{
-
-		name:          "nostdlib",
-		properties:    `no_standard_libs: true, system_modules: "none"`,
-		system:        "none",
-		bootclasspath: []string{`""`},
-		classpath:     []string{},
-	},
-	{
-
-		name:          "nostdlib system_modules",
-		properties:    `no_standard_libs: true, 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:    ``,
-		host:          android.Host,
-		bootclasspath: []string{"jdk8/jre/lib/jce.jar", "jdk8/jre/lib/rt.jar"},
-		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,
-		properties:    `host_supported: true,`,
-		classpath:     []string{},
-		bootclasspath: []string{"jdk8/jre/lib/jce.jar", "jdk8/jre/lib/rt.jar"},
-	},
-	{
-		name:       "host supported nostdlib",
-		host:       android.Host,
-		properties: `host_supported: true, no_standard_libs: true, system_modules: "none"`,
-		classpath:  []string{},
-	},
-	{
-
-		name:          "unbundled sdk v14",
-		unbundled:     true,
-		properties:    `sdk_version: "14",`,
-		bootclasspath: []string{`""`},
-		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
-		classpath:     []string{"prebuilts/sdk/14/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
-	},
-	{
-
-		name:          "unbundled current",
-		unbundled:     true,
-		properties:    `sdk_version: "current",`,
-		bootclasspath: []string{`""`},
-		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
-		classpath:     []string{"prebuilts/sdk/current/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
-	},
-}
-
-func TestClasspath(t *testing.T) {
-	for _, testcase := range classpathTestcases {
-		t.Run(testcase.name, func(t *testing.T) {
-			moduleType := "java_library"
-			if testcase.moduleType != "" {
-				moduleType = testcase.moduleType
-			}
-
-			bp := moduleType + ` {
-				name: "foo",
-				srcs: ["a.java"],
-				` + testcase.properties + `
-			}`
-
-			variant := "android_common"
-			if testcase.host == android.Host {
-				variant = android.BuildOs.String() + "_common"
-			}
-
-			convertModulesToPaths := func(cp []string) []string {
-				ret := make([]string, len(cp))
-				for i, e := range cp {
-					ret[i] = moduleToPath(e)
-				}
-				return ret
-			}
-
-			bootclasspath := convertModulesToPaths(testcase.bootclasspath)
-			classpath := convertModulesToPaths(testcase.classpath)
-
-			bc := strings.Join(bootclasspath, ":")
-			if bc != "" {
-				bc = "-bootclasspath " + bc
-			}
-
-			c := strings.Join(classpath, ":")
-			if c != "" {
-				c = "-classpath " + c
-			}
-			system := ""
-			if testcase.system == "none" {
-				system = "--system=none"
-			} else if testcase.system != "" {
-				system = "--system=" + filepath.Join(buildDir, ".intermediates", testcase.system, "android_common", "system") + "/"
-			}
-
-			t.Run("1.8", func(t *testing.T) {
-				// Test default javac 1.8
-				config := testConfig(nil)
-				if testcase.unbundled {
-					config.TestProductVariables.Unbundled_build = proptools.BoolPtr(true)
-				}
-				ctx := testContext(config, bp, nil)
-				run(t, ctx, config)
-
-				javac := ctx.ModuleForTests("foo", variant).Rule("javac")
-
-				got := javac.Args["bootClasspath"]
-				if got != bc {
-					t.Errorf("bootclasspath expected %q != got %q", bc, got)
-				}
-
-				got = javac.Args["classpath"]
-				if got != c {
-					t.Errorf("classpath expected %q != got %q", c, got)
-				}
-
-				var deps []string
-				if len(bootclasspath) > 0 && bootclasspath[0] != `""` {
-					deps = append(deps, bootclasspath...)
-				}
-				deps = append(deps, classpath...)
-
-				if !reflect.DeepEqual(javac.Implicits.Strings(), deps) {
-					t.Errorf("implicits expected %q != got %q", deps, javac.Implicits.Strings())
-				}
-			})
-
-			// Test again with javac 1.9
-			t.Run("1.9", func(t *testing.T) {
-				config := testConfig(map[string]string{"EXPERIMENTAL_USE_OPENJDK9": "true"})
-				if testcase.unbundled {
-					config.TestProductVariables.Unbundled_build = proptools.BoolPtr(true)
-				}
-				ctx := testContext(config, bp, nil)
-				run(t, ctx, config)
-
-				javac := ctx.ModuleForTests("foo", variant).Rule("javac")
-				got := javac.Args["bootClasspath"]
-				expected := system
-				if testcase.system == "bootclasspath" {
-					expected = bc
-				}
-				if got != expected {
-					t.Errorf("bootclasspath expected %q != got %q", expected, got)
-				}
-			})
-		})
-	}
-
-}
-
 func TestPrebuilts(t *testing.T) {
 	ctx := testJava(t, `
 		java_library {
diff --git a/java/sdk.go b/java/sdk.go
new file mode 100644
index 0000000..988610f
--- /dev/null
+++ b/java/sdk.go
@@ -0,0 +1,218 @@
+// 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 (
+	"android/soong/android"
+	"android/soong/java/config"
+	"fmt"
+	"path/filepath"
+	"sort"
+	"strconv"
+	"strings"
+)
+
+func init() {
+	android.RegisterPreSingletonType("sdk", sdkSingletonFactory)
+}
+
+const sdkSingletonKey = "sdkSingletonKey"
+
+type sdkContext interface {
+	// sdkVersion eturns 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
+}
+
+func sdkVersionOrDefault(ctx android.BaseContext, v string) string {
+	switch v {
+	case "", "current", "system_current", "test_current", "core_current":
+		return ctx.Config().DefaultAppTargetSdk()
+	default:
+		return v
+	}
+}
+
+// Returns a sdk version as a number.  For modules targeting an unreleased SDK (meaning it does not yet have a number)
+// it returns android.FutureApiLevel (10000).
+func sdkVersionToNumber(ctx android.BaseContext, v string) (int, error) {
+	switch v {
+	case "", "current", "test_current", "system_current", "core_current":
+		return ctx.Config().DefaultAppTargetSdkInt(), nil
+	default:
+		n := android.GetNumericSdkVersion(v)
+		if i, err := strconv.Atoi(n); err != nil {
+			return -1, fmt.Errorf("invalid sdk version %q", n)
+		} else {
+			return i, nil
+		}
+	}
+}
+
+func sdkVersionToNumberAsString(ctx android.BaseContext, v string) (string, error) {
+	n, err := sdkVersionToNumber(ctx, v)
+	if err != nil {
+		return "", err
+	}
+	return strconv.Itoa(n), nil
+}
+
+func decodeSdkDep(ctx android.BaseContext, sdkContext sdkContext) sdkDep {
+	v := sdkContext.sdkVersion()
+	// For PDK builds, use the latest SDK version instead of "current"
+	if ctx.Config().IsPdkBuild() && (v == "" || v == "current") {
+		sdkVersions := ctx.Config().Get(sdkSingletonKey).([]int)
+		latestSdkVersion := 0
+		if len(sdkVersions) > 0 {
+			latestSdkVersion = sdkVersions[len(sdkVersions)-1]
+		}
+		v = strconv.Itoa(latestSdkVersion)
+	}
+
+	i, err := sdkVersionToNumber(ctx, v)
+	if err != nil {
+		ctx.PropertyErrorf("sdk_version", "%s", err)
+		return sdkDep{}
+	}
+
+	toPrebuilt := func(sdk string) sdkDep {
+		var api, v string
+		if strings.Contains(sdk, "_") {
+			t := strings.Split(sdk, "_")
+			api = t[0]
+			v = t[1]
+		} else {
+			api = "public"
+			v = sdk
+		}
+		dir := filepath.Join("prebuilts", "sdk", v, api)
+		jar := filepath.Join(dir, "android.jar")
+		// There's no aidl for other SDKs yet.
+		// TODO(77525052): Add aidl files for other SDKs too.
+		public_dir := filepath.Join("prebuilts", "sdk", v, "public")
+		aidl := filepath.Join(public_dir, "framework.aidl")
+		jarPath := android.ExistentPathForSource(ctx, jar)
+		aidlPath := android.ExistentPathForSource(ctx, aidl)
+		lambdaStubsPath := android.PathForSource(ctx, config.SdkLambdaStubsPath)
+
+		if (!jarPath.Valid() || !aidlPath.Valid()) && ctx.Config().AllowMissingDependencies() {
+			return sdkDep{
+				invalidVersion: true,
+				modules:        []string{fmt.Sprintf("sdk_%s_%s_android", api, v)},
+			}
+		}
+
+		if !jarPath.Valid() {
+			ctx.PropertyErrorf("sdk_version", "invalid sdk version %q, %q does not exist", v, jar)
+			return sdkDep{}
+		}
+
+		if !aidlPath.Valid() {
+			ctx.PropertyErrorf("sdk_version", "invalid sdk version %q, %q does not exist", v, aidl)
+			return sdkDep{}
+		}
+
+		return sdkDep{
+			useFiles: true,
+			jars:     android.Paths{jarPath.Path(), lambdaStubsPath},
+			aidl:     aidlPath.Path(),
+		}
+	}
+
+	toModule := func(m, r string) sdkDep {
+		ret := sdkDep{
+			useModule:          true,
+			modules:            []string{m, config.DefaultLambdaStubsLibrary},
+			systemModules:      m + "_system_modules",
+			frameworkResModule: r,
+		}
+		if m == "core.current.stubs" {
+			ret.systemModules = "core-system-modules"
+		} else if m == "core.platform.api.stubs" {
+			ret.systemModules = "core-platform-api-stubs-system-modules"
+		}
+		return ret
+	}
+
+	// Ensures that the specificed system SDK version is one of BOARD_SYSTEMSDK_VERSIONS (for vendor apks)
+	// or PRODUCT_SYSTEMSDK_VERSIONS (for other apks or when BOARD_SYSTEMSDK_VERSIONS is not set)
+	if strings.HasPrefix(v, "system_") && i != android.FutureApiLevel {
+		allowed_versions := ctx.DeviceConfig().PlatformSystemSdkVersions()
+		if ctx.DeviceSpecific() || ctx.SocSpecific() {
+			if len(ctx.DeviceConfig().SystemSdkVersions()) > 0 {
+				allowed_versions = ctx.DeviceConfig().SystemSdkVersions()
+			}
+		}
+		version := strings.TrimPrefix(v, "system_")
+		if len(allowed_versions) > 0 && !android.InList(version, allowed_versions) {
+			ctx.PropertyErrorf("sdk_version", "incompatible sdk version %q. System SDK version should be one of %q",
+				v, allowed_versions)
+		}
+	}
+
+	if ctx.Config().UnbundledBuildPrebuiltSdks() && v != "" {
+		return toPrebuilt(v)
+	}
+
+	switch v {
+	case "":
+		return sdkDep{
+			useDefaultLibs:     true,
+			frameworkResModule: "framework-res",
+		}
+	case "current":
+		return toModule("android_stubs_current", "framework-res")
+	case "system_current":
+		return toModule("android_system_stubs_current", "framework-res")
+	case "test_current":
+		return toModule("android_test_stubs_current", "framework-res")
+	case "core_current":
+		return toModule("core.current.stubs", "")
+	default:
+		return toPrebuilt(v)
+	}
+}
+
+func sdkSingletonFactory() android.Singleton {
+	return sdkSingleton{}
+}
+
+type sdkSingleton struct{}
+
+func (sdkSingleton) GenerateBuildActions(ctx android.SingletonContext) {
+	sdkJars, err := ctx.GlobWithDeps("prebuilts/sdk/*/public/android.jar", nil)
+	if err != nil {
+		ctx.Errorf("failed to glob prebuilts/sdk/*/public/android.jar: %s", err.Error())
+	}
+
+	var sdkVersions []int
+	for _, sdkJar := range sdkJars {
+		dir := filepath.Base(filepath.Dir(filepath.Dir(sdkJar)))
+		v, err := strconv.Atoi(dir)
+		if scerr, ok := err.(*strconv.NumError); ok && scerr.Err == strconv.ErrSyntax {
+			continue
+		} else if err != nil {
+			ctx.Errorf("invalid sdk jar %q, %s, %v", sdkJar, err.Error())
+		}
+		sdkVersions = append(sdkVersions, v)
+	}
+
+	sort.Ints(sdkVersions)
+
+	ctx.Config().Once(sdkSingletonKey, func() interface{} { return sdkVersions })
+}
diff --git a/java/sdk_test.go b/java/sdk_test.go
new file mode 100644
index 0000000..6924e26
--- /dev/null
+++ b/java/sdk_test.go
@@ -0,0 +1,291 @@
+// 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 (
+	"android/soong/android"
+	"path/filepath"
+	"reflect"
+	"strings"
+	"testing"
+
+	"github.com/google/blueprint/proptools"
+)
+
+var classpathTestcases = []struct {
+	name          string
+	unbundled     bool
+	pdk           bool
+	moduleType    string
+	host          android.OsClass
+	properties    string
+	bootclasspath []string
+	system        string
+	classpath     []string
+}{
+	{
+		name:          "default",
+		bootclasspath: []string{"core.platform.api.stubs", "core-lambda-stubs"},
+		system:        "core-platform-api-stubs-system-modules",
+		classpath:     []string{"ext", "framework"},
+	},
+	{
+		name:          "blank sdk version",
+		properties:    `sdk_version: "",`,
+		bootclasspath: []string{"core.platform.api.stubs", "core-lambda-stubs"},
+		system:        "core-platform-api-stubs-system-modules",
+		classpath:     []string{"ext", "framework"},
+	},
+	{
+
+		name:          "sdk v14",
+		properties:    `sdk_version: "14",`,
+		bootclasspath: []string{`""`},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+		classpath:     []string{"prebuilts/sdk/14/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
+	},
+	{
+
+		name:          "current",
+		properties:    `sdk_version: "current",`,
+		bootclasspath: []string{"android_stubs_current", "core-lambda-stubs"},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+	},
+	{
+
+		name:          "system_current",
+		properties:    `sdk_version: "system_current",`,
+		bootclasspath: []string{"android_system_stubs_current", "core-lambda-stubs"},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+	},
+	{
+
+		name:          "system_14",
+		properties:    `sdk_version: "system_14",`,
+		bootclasspath: []string{`""`},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+		classpath:     []string{"prebuilts/sdk/14/system/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
+	},
+	{
+
+		name:          "test_current",
+		properties:    `sdk_version: "test_current",`,
+		bootclasspath: []string{"android_test_stubs_current", "core-lambda-stubs"},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+	},
+	{
+
+		name:          "core_current",
+		properties:    `sdk_version: "core_current",`,
+		bootclasspath: []string{"core.current.stubs", "core-lambda-stubs"},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+	},
+	{
+
+		name:          "nostdlib",
+		properties:    `no_standard_libs: true, system_modules: "none"`,
+		system:        "none",
+		bootclasspath: []string{`""`},
+		classpath:     []string{},
+	},
+	{
+
+		name:          "nostdlib system_modules",
+		properties:    `no_standard_libs: true, 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:    ``,
+		host:          android.Host,
+		bootclasspath: []string{"jdk8/jre/lib/jce.jar", "jdk8/jre/lib/rt.jar"},
+		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,
+		properties:    `host_supported: true,`,
+		classpath:     []string{},
+		bootclasspath: []string{"jdk8/jre/lib/jce.jar", "jdk8/jre/lib/rt.jar"},
+	},
+	{
+		name:       "host supported nostdlib",
+		host:       android.Host,
+		properties: `host_supported: true, no_standard_libs: true, system_modules: "none"`,
+		classpath:  []string{},
+	},
+	{
+
+		name:          "unbundled sdk v14",
+		unbundled:     true,
+		properties:    `sdk_version: "14",`,
+		bootclasspath: []string{`""`},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+		classpath:     []string{"prebuilts/sdk/14/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
+	},
+	{
+
+		name:          "unbundled current",
+		unbundled:     true,
+		properties:    `sdk_version: "current",`,
+		bootclasspath: []string{`""`},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+		classpath:     []string{"prebuilts/sdk/current/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
+	},
+
+	{
+		name:          "pdk default",
+		pdk:           true,
+		bootclasspath: []string{`""`},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+		classpath:     []string{"prebuilts/sdk/17/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
+	},
+	{
+		name:          "pdk current",
+		pdk:           true,
+		properties:    `sdk_version: "current",`,
+		bootclasspath: []string{`""`},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+		classpath:     []string{"prebuilts/sdk/17/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
+	},
+	{
+		name:          "pdk 14",
+		pdk:           true,
+		properties:    `sdk_version: "14",`,
+		bootclasspath: []string{`""`},
+		system:        "bootclasspath", // special value to tell 1.9 test to expect bootclasspath
+		classpath:     []string{"prebuilts/sdk/14/public/android.jar", "prebuilts/sdk/tools/core-lambda-stubs.jar"},
+	},
+}
+
+func TestClasspath(t *testing.T) {
+	for _, testcase := range classpathTestcases {
+		t.Run(testcase.name, func(t *testing.T) {
+			moduleType := "java_library"
+			if testcase.moduleType != "" {
+				moduleType = testcase.moduleType
+			}
+
+			bp := moduleType + ` {
+				name: "foo",
+				srcs: ["a.java"],
+				` + testcase.properties + `
+			}`
+
+			variant := "android_common"
+			if testcase.host == android.Host {
+				variant = android.BuildOs.String() + "_common"
+			}
+
+			convertModulesToPaths := func(cp []string) []string {
+				ret := make([]string, len(cp))
+				for i, e := range cp {
+					ret[i] = moduleToPath(e)
+				}
+				return ret
+			}
+
+			bootclasspath := convertModulesToPaths(testcase.bootclasspath)
+			classpath := convertModulesToPaths(testcase.classpath)
+
+			bc := strings.Join(bootclasspath, ":")
+			if bc != "" {
+				bc = "-bootclasspath " + bc
+			}
+
+			c := strings.Join(classpath, ":")
+			if c != "" {
+				c = "-classpath " + c
+			}
+			system := ""
+			if testcase.system == "none" {
+				system = "--system=none"
+			} else if testcase.system != "" {
+				system = "--system=" + filepath.Join(buildDir, ".intermediates", testcase.system, "android_common", "system") + "/"
+			}
+
+			t.Run("1.8", func(t *testing.T) {
+				// Test default javac 1.8
+				config := testConfig(nil)
+				if testcase.unbundled {
+					config.TestProductVariables.Unbundled_build = proptools.BoolPtr(true)
+				}
+				if testcase.pdk {
+					config.TestProductVariables.Pdk = proptools.BoolPtr(true)
+				}
+				ctx := testContext(config, bp, nil)
+				run(t, ctx, config)
+
+				javac := ctx.ModuleForTests("foo", variant).Rule("javac")
+
+				got := javac.Args["bootClasspath"]
+				if got != bc {
+					t.Errorf("bootclasspath expected %q != got %q", bc, got)
+				}
+
+				got = javac.Args["classpath"]
+				if got != c {
+					t.Errorf("classpath expected %q != got %q", c, got)
+				}
+
+				var deps []string
+				if len(bootclasspath) > 0 && bootclasspath[0] != `""` {
+					deps = append(deps, bootclasspath...)
+				}
+				deps = append(deps, classpath...)
+
+				if !reflect.DeepEqual(javac.Implicits.Strings(), deps) {
+					t.Errorf("implicits expected %q != got %q", deps, javac.Implicits.Strings())
+				}
+			})
+
+			// Test again with javac 1.9
+			t.Run("1.9", func(t *testing.T) {
+				config := testConfig(map[string]string{"EXPERIMENTAL_USE_OPENJDK9": "true"})
+				if testcase.unbundled {
+					config.TestProductVariables.Unbundled_build = proptools.BoolPtr(true)
+				}
+				if testcase.pdk {
+					config.TestProductVariables.Pdk = proptools.BoolPtr(true)
+				}
+				ctx := testContext(config, bp, nil)
+				run(t, ctx, config)
+
+				javac := ctx.ModuleForTests("foo", variant).Rule("javac")
+				got := javac.Args["bootClasspath"]
+				expected := system
+				if testcase.system == "bootclasspath" {
+					expected = bc
+				}
+				if got != expected {
+					t.Errorf("bootclasspath expected %q != got %q", expected, got)
+				}
+			})
+		})
+	}
+
+}
diff --git a/ui/build/Android.bp b/ui/build/Android.bp
index 0eba5ce..1ddaf68 100644
--- a/ui/build/Android.bp
+++ b/ui/build/Android.bp
@@ -47,6 +47,7 @@
         "environment.go",
         "exec.go",
         "finder.go",
+        "goma.go",
         "kati.go",
         "ninja.go",
         "path.go",
diff --git a/ui/build/build.go b/ui/build/build.go
index c902a0f..0ae06d6 100644
--- a/ui/build/build.go
+++ b/ui/build/build.go
@@ -156,6 +156,11 @@
 
 	SetupPath(ctx, config)
 
+	if config.StartGoma() {
+		// Ensure start Goma compiler_proxy
+		startGoma(ctx, config)
+	}
+
 	if what&BuildProductConfig != 0 {
 		// Run make for product config
 		runMakeProductConfig(ctx, config)
diff --git a/ui/build/config.go b/ui/build/config.go
index 97b009a..64270f8 100644
--- a/ui/build/config.go
+++ b/ui/build/config.go
@@ -478,6 +478,20 @@
 	return false
 }
 
+func (c *configImpl) StartGoma() bool {
+	if !c.UseGoma() {
+		return false
+	}
+
+	if v, ok := c.environ.Get("NOSTART_GOMA"); ok {
+		v = strings.TrimSpace(v)
+		if v != "" && v != "false" {
+			return false
+		}
+	}
+	return true
+}
+
 // RemoteParallel controls how many remote jobs (i.e., commands which contain
 // gomacc) are run in parallel.  Note the parallelism of all other jobs is
 // still limited by Parallel()
diff --git a/ui/build/goma.go b/ui/build/goma.go
new file mode 100644
index 0000000..d0dc9cf
--- /dev/null
+++ b/ui/build/goma.go
@@ -0,0 +1,48 @@
+// 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 build
+
+import (
+	"errors"
+	"path/filepath"
+
+	"android/soong/ui/metrics"
+)
+
+const gomaCtlScript = "goma_ctl.py"
+
+var gomaCtlNotFound = errors.New("goma_ctl.py not found")
+
+func startGoma(ctx Context, config Config) error {
+	ctx.BeginTrace(metrics.RunSetupTool, "goma_ctl")
+	defer ctx.EndTrace()
+
+	var gomaCtl string
+	if gomaDir, ok := config.Environment().Get("GOMA_DIR"); ok {
+		gomaCtl = filepath.Join(gomaDir, gomaCtlScript)
+	} else if home, ok := config.Environment().Get("HOME"); ok {
+		gomaCtl = filepath.Join(home, "goma", gomaCtlScript)
+	} else {
+		return gomaCtlNotFound
+	}
+
+	cmd := Command(ctx, config, "goma_ctl.py ensure_start", gomaCtl, "ensure_start")
+
+	if err := cmd.Run(); err != nil {
+		ctx.Fatalf("goma_ctl.py ensure_start failed with: %v", err)
+	}
+
+	return nil
+}
diff --git a/ui/build/kati.go b/ui/build/kati.go
index 205d5ae..439c928 100644
--- a/ui/build/kati.go
+++ b/ui/build/kati.go
@@ -18,6 +18,8 @@
 	"crypto/md5"
 	"fmt"
 	"io/ioutil"
+	"os"
+	"os/user"
 	"path/filepath"
 	"strings"
 
@@ -96,6 +98,22 @@
 
 	envFunc(cmd.Environment)
 
+	if _, ok := cmd.Environment.Get("BUILD_USERNAME"); !ok {
+		u, err := user.Current()
+		if err != nil {
+			ctx.Println("Failed to get current user")
+		}
+		cmd.Environment.Set("BUILD_USERNAME", u.Username)
+	}
+
+	if _, ok := cmd.Environment.Get("BUILD_HOSTNAME"); !ok {
+		hostname, err := os.Hostname()
+		if err != nil {
+			ctx.Println("Failed to read hostname")
+		}
+		cmd.Environment.Set("BUILD_HOSTNAME", hostname)
+	}
+
 	cmd.StartOrFatal()
 	status.KatiReader(ctx.Status.StartTool(), pipe)
 	cmd.WaitOrFatal()
diff --git a/ui/build/paths/config.go b/ui/build/paths/config.go
index ec5c028..87f1e4e 100644
--- a/ui/build/paths/config.go
+++ b/ui/build/paths/config.go
@@ -78,12 +78,11 @@
 	"bash":      Allowed,
 	"bc":        Allowed,
 	"bzip2":     Allowed,
+	"cp":        Allowed,
 	"date":      Allowed,
 	"dd":        Allowed,
 	"diff":      Allowed,
-	"echo":      Allowed,
 	"egrep":     Allowed,
-	"expr":      Allowed,
 	"find":      Allowed,
 	"fuser":     Allowed,
 	"getconf":   Allowed,
@@ -96,7 +95,6 @@
 	"jar":       Allowed,
 	"java":      Allowed,
 	"javap":     Allowed,
-	"ln":        Allowed,
 	"ls":        Allowed,
 	"lsof":      Allowed,
 	"m4":        Allowed,
@@ -154,13 +152,15 @@
 	"chmod":    Toybox,
 	"cmp":      Toybox,
 	"comm":     Toybox,
-	"cp":       Toybox,
 	"cut":      Toybox,
 	"dirname":  Toybox,
 	"du":       Toybox,
+	"echo":     Toybox,
 	"env":      Toybox,
+	"expr":     Toybox,
 	"head":     Toybox,
 	"id":       Toybox,
+	"ln":       Toybox,
 	"mkdir":    Toybox,
 	"od":       Toybox,
 	"paste":    Toybox,