Merge "Add robolectric-shadows to setup_go_workspace_for_soong.sh"
diff --git a/android/config.go b/android/config.go
index 84dd66f..0c9f957 100644
--- a/android/config.go
+++ b/android/config.go
@@ -583,7 +583,7 @@
 	if defaultCert != "" {
 		return PathForSource(ctx, filepath.Dir(defaultCert))
 	} else {
-		return PathForSource(ctx, "build/target/product/security")
+		return PathForSource(ctx, "build/make/target/product/security")
 	}
 }
 
@@ -600,7 +600,7 @@
 func (c *config) ApexKeyDir(ctx ModuleContext) SourcePath {
 	// TODO(b/121224311): define another variable such as TARGET_APEX_KEY_OVERRIDE
 	defaultCert := String(c.productVariables.DefaultAppCertificate)
-	if defaultCert == "" || filepath.Dir(defaultCert) == "build/target/product/security" {
+	if defaultCert == "" || filepath.Dir(defaultCert) == "build/make/target/product/security" {
 		// When defaultCert is unset or is set to the testkeys path, use the APEX keys
 		// that is under the module dir
 		return pathForModuleSrc(ctx)
diff --git a/android/variable.go b/android/variable.go
index 68a24ab..16d7b13 100644
--- a/android/variable.go
+++ b/android/variable.go
@@ -303,9 +303,15 @@
 
 func (v *productVariables) SetDefaultConfig() {
 	*v = productVariables{
-		Platform_sdk_version:              intPtr(26),
-		Platform_version_active_codenames: []string{"P"},
-		Platform_version_future_codenames: []string{"P"},
+		BuildNumberFromFile: stringPtr("123456789"),
+
+		Platform_version_name:             stringPtr("Q"),
+		Platform_sdk_version:              intPtr(28),
+		Platform_sdk_codename:             stringPtr("Q"),
+		Platform_sdk_final:                boolPtr(false),
+		Platform_version_active_codenames: []string{"Q"},
+		Platform_version_future_codenames: []string{"Q"},
+		Platform_vndk_version:             stringPtr("Q"),
 
 		HostArch:                   stringPtr("x86_64"),
 		HostSecondaryArch:          stringPtr("x86"),
diff --git a/apex/apex_test.go b/apex/apex_test.go
index 3c80376..fce2135 100644
--- a/apex/apex_test.go
+++ b/apex/apex_test.go
@@ -148,7 +148,7 @@
 
 	ctx.MockFileSystem(map[string][]byte{
 		"Android.bp":                                        []byte(bp),
-		"build/target/product/security":                     nil,
+		"build/make/target/product/security":                nil,
 		"apex_manifest.json":                                nil,
 		"AndroidManifest.xml":                               nil,
 		"system/sepolicy/apex/myapex-file_contexts":         nil,
diff --git a/java/androidmk.go b/java/androidmk.go
index 865c120..d2e0f2e 100644
--- a/java/androidmk.go
+++ b/java/androidmk.go
@@ -79,6 +79,10 @@
 					fmt.Fprintln(w, "LOCAL_EXPORT_SDK_LIBRARIES :=", strings.Join(library.exportedSdkLibs, " "))
 				}
 
+				if len(library.additionalCheckedModules) != 0 {
+					fmt.Fprintln(w, "LOCAL_ADDITIONAL_CHECKED_MODULE +=", strings.Join(library.additionalCheckedModules.Strings(), " "))
+				}
+
 				// Temporary hack: export sources used to compile framework.jar to Make
 				// to be used for droiddoc
 				// TODO(ccross): remove this once droiddoc is in soong
diff --git a/java/app_builder.go b/java/app_builder.go
index e5ccbbc..5bacb67 100644
--- a/java/app_builder.go
+++ b/java/app_builder.go
@@ -84,8 +84,10 @@
 	})
 
 	var certificateArgs []string
+	var deps android.Paths
 	for _, c := range certificates {
 		certificateArgs = append(certificateArgs, c.Pem.String(), c.Key.String())
+		deps = append(deps, c.Pem, c.Key)
 	}
 
 	ctx.Build(pctx, android.BuildParams{
@@ -93,6 +95,7 @@
 		Description: "signapk",
 		Output:      outputFile,
 		Input:       unsignedApk,
+		Implicits:   deps,
 		Args: map[string]string{
 			"certificates": strings.Join(certificateArgs, " "),
 		},
diff --git a/java/app_test.go b/java/app_test.go
index 1f6297c..a084c9c 100644
--- a/java/app_test.go
+++ b/java/app_test.go
@@ -712,7 +712,7 @@
 				}
 			`,
 			certificateOverride: "",
-			expected:            "build/target/product/security/testkey.x509.pem build/target/product/security/testkey.pk8",
+			expected:            "build/make/target/product/security/testkey.x509.pem build/make/target/product/security/testkey.pk8",
 		},
 		{
 			name: "module certificate property",
@@ -741,7 +741,7 @@
 				}
 			`,
 			certificateOverride: "",
-			expected:            "build/target/product/security/expiredkey.x509.pem build/target/product/security/expiredkey.pk8",
+			expected:            "build/make/target/product/security/expiredkey.x509.pem build/make/target/product/security/expiredkey.pk8",
 		},
 		{
 			name: "certificate overrides",
@@ -910,7 +910,7 @@
 		{
 			variantName: "android_common",
 			apkPath:     "/target/product/test_device/system/app/foo/foo.apk",
-			signFlag:    "build/target/product/security/expiredkey.x509.pem build/target/product/security/expiredkey.pk8",
+			signFlag:    "build/make/target/product/security/expiredkey.x509.pem build/make/target/product/security/expiredkey.pk8",
 			overrides:   []string{"baz"},
 			aaptFlag:    "",
 		},
@@ -924,7 +924,7 @@
 		{
 			variantName: "baz_android_common",
 			apkPath:     "/target/product/test_device/system/app/baz/baz.apk",
-			signFlag:    "build/target/product/security/expiredkey.x509.pem build/target/product/security/expiredkey.pk8",
+			signFlag:    "build/make/target/product/security/expiredkey.x509.pem build/make/target/product/security/expiredkey.pk8",
 			overrides:   []string{"baz", "foo"},
 			aaptFlag:    "--rename-manifest-package org.dandroid.bp",
 		},
diff --git a/java/builder.go b/java/builder.go
index ce9a5ee..338cd52 100644
--- a/java/builder.go
+++ b/java/builder.go
@@ -113,6 +113,15 @@
 		},
 		"rulesFile")
 
+	packageCheck = pctx.AndroidStaticRule("packageCheck",
+		blueprint.RuleParams{
+			Command: "rm -f $out && " +
+				"${config.PackageCheckCmd} $in $packages && " +
+				"touch $out",
+			CommandDeps: []string{"${config.PackageCheckCmd}"},
+		},
+		"packages")
+
 	jetifier = pctx.AndroidStaticRule("jetifier",
 		blueprint.RuleParams{
 			Command:     "${config.JavaCmd} -jar ${config.JetifierJar} -l error -o $out -i $in",
@@ -356,6 +365,19 @@
 	})
 }
 
+func CheckJarPackages(ctx android.ModuleContext, outputFile android.WritablePath,
+	classesJar android.Path, permittedPackages []string) {
+	ctx.Build(pctx, android.BuildParams{
+		Rule:        packageCheck,
+		Description: "packageCheck",
+		Output:      outputFile,
+		Input:       classesJar,
+		Args: map[string]string{
+			"packages": strings.Join(permittedPackages, " "),
+		},
+	})
+}
+
 func TransformJetifier(ctx android.ModuleContext, outputFile android.WritablePath,
 	inputFile android.Path) {
 	ctx.Build(pctx, android.BuildParams{
diff --git a/java/config/config.go b/java/config/config.go
index 3452a1d..46cd361 100644
--- a/java/config/config.go
+++ b/java/config/config.go
@@ -91,6 +91,7 @@
 	pctx.SourcePathVariable("GenKotlinBuildFileCmd", "build/soong/scripts/gen-kotlin-build-file.sh")
 
 	pctx.SourcePathVariable("JarArgsCmd", "build/soong/scripts/jar-args.sh")
+	pctx.SourcePathVariable("PackageCheckCmd", "build/soong/scripts/package-check.sh")
 	pctx.HostBinToolVariable("ExtractJarPackagesCmd", "extract_jar_packages")
 	pctx.HostBinToolVariable("SoongZipCmd", "soong_zip")
 	pctx.HostBinToolVariable("MergeZipsCmd", "merge_zips")
diff --git a/java/config/kotlin.go b/java/config/kotlin.go
index 2af7b3c..7cea042 100644
--- a/java/config/kotlin.go
+++ b/java/config/kotlin.go
@@ -27,6 +27,10 @@
 func init() {
 	pctx.SourcePathVariable("KotlincCmd", "external/kotlinc/bin/kotlinc")
 	pctx.SourcePathVariable("KotlinCompilerJar", "external/kotlinc/lib/kotlin-compiler.jar")
+	pctx.SourcePathVariable("KotlinPreloaderJar", "external/kotlinc/lib/kotlin-preloader.jar")
+	pctx.SourcePathVariable("KotlinReflectJar", "external/kotlinc/lib/kotlin-reflect.jar")
+	pctx.SourcePathVariable("KotlinScriptRuntimeJar", "external/kotlinc/lib/kotlin-script-runtime.jar")
+	pctx.SourcePathVariable("KotlinTrove4jJar", "external/kotlinc/lib/trove4j.jar")
 	pctx.SourcePathVariable("KotlinKaptJar", "external/kotlinc/lib/kotlin-annotation-processing.jar")
 	pctx.SourcePathVariable("KotlinStdlibJar", KotlinStdlibJar)
 
diff --git a/java/dexpreopt.go b/java/dexpreopt.go
index 6b93c10..9141f9e 100644
--- a/java/dexpreopt.go
+++ b/java/dexpreopt.go
@@ -98,6 +98,7 @@
 
 	global := dexpreoptGlobalConfig(ctx)
 	bootImage := defaultBootImageConfig(ctx)
+	defaultBootImage := bootImage
 	if global.UseApexImage {
 		bootImage = apexBootImageConfig(ctx)
 	}
@@ -165,8 +166,11 @@
 		Archs:           archs,
 		DexPreoptImages: images,
 
-		PreoptBootClassPathDexFiles:     bootImage.dexPaths.Paths(),
-		PreoptBootClassPathDexLocations: bootImage.dexLocations,
+		// We use the dex paths and dex locations of the default boot image, as it
+		// contains the full dexpreopt boot classpath. Other images may just contain a subset of
+		// the dexpreopt boot classpath.
+		PreoptBootClassPathDexFiles:     defaultBootImage.dexPaths.Paths(),
+		PreoptBootClassPathDexLocations: defaultBootImage.dexLocations,
 
 		PreoptExtractedApk: false,
 
diff --git a/java/gen.go b/java/gen.go
index 500d887..7c57a46 100644
--- a/java/gen.go
+++ b/java/gen.go
@@ -23,8 +23,9 @@
 func init() {
 	pctx.HostBinToolVariable("aidlCmd", "aidl")
 	pctx.HostBinToolVariable("syspropCmd", "sysprop_java")
-	pctx.SourcePathVariable("logtagsCmd", "build/tools/java-event-log-tags.py")
-	pctx.SourcePathVariable("mergeLogtagsCmd", "build/tools/merge-event-log-tags.py")
+	pctx.SourcePathVariable("logtagsCmd", "build/make/tools/java-event-log-tags.py")
+	pctx.SourcePathVariable("mergeLogtagsCmd", "build/make/tools/merge-event-log-tags.py")
+	pctx.SourcePathVariable("logtagsLib", "build/make/tools/event_log_tags.py")
 }
 
 var (
@@ -38,13 +39,13 @@
 	logtags = pctx.AndroidStaticRule("logtags",
 		blueprint.RuleParams{
 			Command:     "$logtagsCmd -o $out $in",
-			CommandDeps: []string{"$logtagsCmd"},
+			CommandDeps: []string{"$logtagsCmd", "$logtagsLib"},
 		})
 
 	mergeLogtags = pctx.AndroidStaticRule("mergeLogtags",
 		blueprint.RuleParams{
 			Command:     "$mergeLogtagsCmd -o $out $in",
-			CommandDeps: []string{"$mergeLogtagsCmd"},
+			CommandDeps: []string{"$mergeLogtagsCmd", "$logtagsLib"},
 		})
 
 	sysprop = pctx.AndroidStaticRule("sysprop",
diff --git a/java/java.go b/java/java.go
index 0417dee..bf62578 100644
--- a/java/java.go
+++ b/java/java.go
@@ -117,6 +117,10 @@
 	// If set to true, include sources used to compile the module in to the final jar
 	Include_srcs *bool
 
+	// If not empty, classes are restricted to the specified packages and their sub-packages.
+	// This restriction is checked after applying jarjar rules and including static libs.
+	Permitted_packages []string
+
 	// List of modules to use as annotation processors
 	Plugins []string
 
@@ -320,6 +324,9 @@
 	// expanded Jarjar_rules
 	expandJarjarRules android.Path
 
+	// list of additional targets for checkbuild
+	additionalCheckedModules android.Paths
+
 	hiddenAPI
 	dexpreopter
 }
@@ -1196,6 +1203,19 @@
 			return
 		}
 	}
+
+	// Check package restrictions if necessary.
+	if len(j.properties.Permitted_packages) > 0 {
+		// Check packages and copy to package-checked file.
+		pkgckFile := android.PathForModuleOut(ctx, "package-check.stamp")
+		CheckJarPackages(ctx, pkgckFile, outputFile, j.properties.Permitted_packages)
+		j.additionalCheckedModules = append(j.additionalCheckedModules, pkgckFile)
+
+		if ctx.Failed() {
+			return
+		}
+	}
+
 	j.implementationJarFile = outputFile
 	if j.headerJarFile == nil {
 		j.headerJarFile = j.implementationJarFile
diff --git a/java/java_test.go b/java/java_test.go
index 2546698..3ae993d 100644
--- a/java/java_test.go
+++ b/java/java_test.go
@@ -163,8 +163,8 @@
 		"prebuilts/sdk/Android.bp":                    []byte(`prebuilt_apis { name: "sdk", api_dirs: ["14", "28", "current"],}`),
 
 		// For framework-res, which is an implicit dependency for framework
-		"AndroidManifest.xml":                   nil,
-		"build/target/product/security/testkey": nil,
+		"AndroidManifest.xml":                        nil,
+		"build/make/target/product/security/testkey": nil,
 
 		"build/soong/scripts/jar-wrapper.sh": nil,
 
diff --git a/java/kotlin.go b/java/kotlin.go
index 81b89f9..054998f 100644
--- a/java/kotlin.go
+++ b/java/kotlin.go
@@ -37,6 +37,11 @@
 		CommandDeps: []string{
 			"${config.KotlincCmd}",
 			"${config.KotlinCompilerJar}",
+			"${config.KotlinPreloaderJar}",
+			"${config.KotlinReflectJar}",
+			"${config.KotlinScriptRuntimeJar}",
+			"${config.KotlinStdlibJar}",
+			"${config.KotlinTrove4jJar}",
 			"${config.GenKotlinBuildFileCmd}",
 			"${config.SoongZipCmd}",
 			"${config.ZipSyncCmd}",
diff --git a/python/proto.go b/python/proto.go
index b3ffaa6..85ed1a5 100644
--- a/python/proto.go
+++ b/python/proto.go
@@ -35,12 +35,12 @@
 	// into a srcszip.
 	zipCmd := rule.Command().
 		Tool(ctx.Config().HostToolPath(ctx, "soong_zip")).
-		FlagWithOutput("-o ", srcsZipFile).
-		FlagWithArg("-C ", outDir.String()).
-		FlagWithArg("-D ", outDir.String())
+		FlagWithOutput("-o ", srcsZipFile)
 	if pkgPath != "" {
 		zipCmd.FlagWithArg("-P ", pkgPath)
 	}
+	zipCmd.FlagWithArg("-C ", outDir.String()).
+		FlagWithArg("-D ", outDir.String())
 
 	rule.Command().Text("rm -rf").Flag(outDir.String())
 
diff --git a/scripts/build_broken_logs.go b/scripts/build_broken_logs.go
index 73832a6..f081f26 100644
--- a/scripts/build_broken_logs.go
+++ b/scripts/build_broken_logs.go
@@ -90,6 +90,10 @@
 			"Changes.md#LOCAL_MODULE_TAGS",
 		},
 	},
+	{
+		name:     "BUILD_BROKEN_USES_NETWORK",
+		behavior: DefaultDeprecated,
+	},
 }
 
 type ProductBranch struct {
diff --git a/scripts/package-check.sh b/scripts/package-check.sh
new file mode 100755
index 0000000..f982e82
--- /dev/null
+++ b/scripts/package-check.sh
@@ -0,0 +1,72 @@
+#!/bin/bash
+#
+# Copyright (C) 2019 The Android Open Source Project
+#
+# 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.
+
+set -e
+
+if [[ $# -le 1 ]]; then
+  cat <<EOF
+Usage:
+  package-check.sh <jar-file> <package-list>
+Checks that the class files in the <jar file> are in the <package-list> or
+sub-packages.
+EOF
+  exit 1
+fi
+
+jar_file=$1
+shift
+if [[ ! -f ${jar_file} ]]; then
+  echo "jar file \"${jar_file}\" does not exist."
+  exit 1
+fi
+
+prefixes=()
+while [[ $# -ge 1 ]]; do
+  package="$1"
+  if [[ "${package}" = */* ]]; then
+    echo "Invalid package \"${package}\". Use dot notation for packages."
+    exit 1
+  fi
+  # Transform to a slash-separated path and add a trailing slash to enforce
+  # package name boundary.
+  prefixes+=("${package//\./\/}/")
+  shift
+done
+
+# Get the file names from the jar file.
+zip_contents=`zipinfo -1 $jar_file`
+
+# Check all class file names against the expected prefixes.
+old_ifs=${IFS}
+IFS=$'\n'
+for zip_entry in ${zip_contents}; do
+  # Check the suffix.
+  if [[ "${zip_entry}" = *.class ]]; then
+    # Match against prefixes.
+    found=false
+    for prefix in ${prefixes[@]}; do
+      if [[ "${zip_entry}" = "${prefix}"* ]]; then
+        found=true
+        break
+      fi
+    done
+    if [[ "${found}" == "false" ]]; then
+      echo "Class file ${zip_entry} is outside specified packages."
+      exit 1
+    fi
+  fi
+done
+IFS=${old_ifs}
diff --git a/sysprop/sysprop_test.go b/sysprop/sysprop_test.go
index a7aff59..af89c24 100644
--- a/sysprop/sysprop_test.go
+++ b/sysprop/sysprop_test.go
@@ -135,8 +135,8 @@
 		"prebuilts/sdk/Android.bp":                                            []byte(`prebuilt_apis { name: "sdk", api_dirs: ["28", "current"],}`),
 
 		// For framework-res, which is an implicit dependency for framework
-		"AndroidManifest.xml":                   nil,
-		"build/target/product/security/testkey": nil,
+		"AndroidManifest.xml":                        nil,
+		"build/make/target/product/security/testkey": nil,
 
 		"build/soong/scripts/jar-wrapper.sh": nil,
 
diff --git a/ui/build/config.go b/ui/build/config.go
index 64270f8..7eb3a72 100644
--- a/ui/build/config.go
+++ b/ui/build/config.go
@@ -55,6 +55,7 @@
 
 	brokenDupRules     bool
 	brokenPhonyTargets bool
+	brokenUsesNetwork  bool
 
 	pathReplaced bool
 }
@@ -622,6 +623,14 @@
 	return c.brokenPhonyTargets
 }
 
+func (c *configImpl) SetBuildBrokenUsesNetwork(val bool) {
+	c.brokenUsesNetwork = val
+}
+
+func (c *configImpl) BuildBrokenUsesNetwork() bool {
+	return c.brokenUsesNetwork
+}
+
 func (c *configImpl) SetTargetDeviceDir(dir string) {
 	c.targetDeviceDir = dir
 }
diff --git a/ui/build/dumpvars.go b/ui/build/dumpvars.go
index 7f0b784..3e387c1 100644
--- a/ui/build/dumpvars.go
+++ b/ui/build/dumpvars.go
@@ -203,6 +203,9 @@
 		// Used to turn on --werror_ options in Kati
 		"BUILD_BROKEN_PHONY_TARGETS",
 
+		// Whether to enable the network during the build
+		"BUILD_BROKEN_USES_NETWORK",
+
 		// Not used, but useful to be in the soong.log
 		"BOARD_VNDK_VERSION",
 		"BUILD_BROKEN_ANDROIDMK_EXPORTS",
@@ -238,4 +241,5 @@
 	config.SetPdkBuild(make_vars["TARGET_BUILD_PDK"] == "true")
 	config.SetBuildBrokenDupRules(make_vars["BUILD_BROKEN_DUP_RULES"] == "true")
 	config.SetBuildBrokenPhonyTargets(make_vars["BUILD_BROKEN_PHONY_TARGETS"] == "true")
+	config.SetBuildBrokenUsesNetwork(make_vars["BUILD_BROKEN_USES_NETWORK"] == "true")
 }
diff --git a/ui/build/paths/config.go b/ui/build/paths/config.go
index fb30f85..ed2d9ca 100644
--- a/ui/build/paths/config.go
+++ b/ui/build/paths/config.go
@@ -155,6 +155,7 @@
 	"rm":        LinuxOnlyPrebuilt,
 	"rmdir":     LinuxOnlyPrebuilt,
 	"sed":       LinuxOnlyPrebuilt,
+	"seq":       LinuxOnlyPrebuilt,
 	"setsid":    LinuxOnlyPrebuilt,
 	"sha1sum":   LinuxOnlyPrebuilt,
 	"sha256sum": LinuxOnlyPrebuilt,
diff --git a/ui/build/sandbox_linux.go b/ui/build/sandbox_linux.go
index 85c4a9a..b94db74 100644
--- a/ui/build/sandbox_linux.go
+++ b/ui/build/sandbox_linux.go
@@ -26,6 +26,8 @@
 type Sandbox struct {
 	Enabled              bool
 	DisableWhenUsingGoma bool
+
+	AllowBuildBrokenUsesNetwork bool
 }
 
 var (
@@ -40,6 +42,8 @@
 	ninjaSandbox    = Sandbox{
 		Enabled:              true,
 		DisableWhenUsingGoma: true,
+
+		AllowBuildBrokenUsesNetwork: true,
 	}
 )
 
@@ -152,10 +156,17 @@
 
 		// Only log important warnings / errors
 		"-q",
-
-		// Stop parsing arguments
-		"--",
 	}
+
+	if c.Sandbox.AllowBuildBrokenUsesNetwork && c.config.BuildBrokenUsesNetwork() {
+		c.ctx.Printf("AllowBuildBrokenUsesNetwork: %v", c.Sandbox.AllowBuildBrokenUsesNetwork)
+		c.ctx.Printf("BuildBrokenUsesNetwork: %v", c.config.BuildBrokenUsesNetwork())
+		sandboxArgs = append(sandboxArgs, "-N")
+	}
+
+	// Stop nsjail from parsing arguments
+	sandboxArgs = append(sandboxArgs, "--")
+
 	c.Args = append(sandboxArgs, c.Args[1:]...)
 	c.Path = nsjailPath