Merge "For b/110066051, add KeyGuard check when run cts. If device didn't support keyguard, not run this cases."
diff --git a/Android.bp b/Android.bp
new file mode 100644
index 0000000..3eec2e6
--- /dev/null
+++ b/Android.bp
@@ -0,0 +1,51 @@
+java_defaults {
+    name: "cts_error_prone_rules",
+    errorprone: {
+        javacflags: [
+            // Set of error prone rules to ensure code quality
+            // When updating this list, also update error_prone_rules.mk
+            "-Xep:ArrayToString:ERROR",
+            "-Xep:BoxedPrimitiveConstructor:ERROR",
+            "-Xep:ConstantField:ERROR",
+            "-Xep:EqualsIncompatibleType:ERROR",
+            "-Xep:FormatString:ERROR",
+            "-Xep:GetClassOnClass:ERROR",
+            "-Xep:IdentityBinaryExpression:ERROR",
+            "-Xep:JUnit3TestNotRun:ERROR",
+            "-Xep:JUnit4ClassUsedInJUnit3:ERROR",
+            "-Xep:JUnitAmbiguousTestClass:ERROR",
+            "-Xep:MissingFail:ERROR",
+            "-Xep:MissingOverride:ERROR",
+            "-Xep:Overrides:ERROR",
+            "-Xep:ReferenceEquality:ERROR",
+            "-Xep:RemoveUnusedImports:ERROR",
+            "-Xep:ReturnValueIgnored:ERROR",
+            "-Xep:SelfEquals:ERROR",
+            "-Xep:SizeGreaterThanOrEqualsZero:ERROR",
+            "-Xep:TryFailThrowable:ERROR",
+        ],
+    },
+}
+
+java_defaults {
+    name: "cts_error_prone_rules_tests",
+    errorprone: {
+        javacflags: [
+            // Set of error prone rules to ensure code quality of tests
+            // Goal is to eventually merge with cts_error_prone_rules
+            // When updating this list, also update error_prone_rules_tests.mk
+            "-Xep:ArrayToString:ERROR",
+            "-Xep:CollectionIncompatibleType:ERROR",
+            "-Xep:EqualsIncompatibleType:ERROR",
+            "-Xep:EqualsNaN:ERROR",
+            "-Xep:FormatString:ERROR",
+            "-Xep:IdentityBinaryExpression:ERROR",
+            "-Xep:JUnit3TestNotRun:ERROR",
+            "-Xep:JUnit4ClassUsedInJUnit3:ERROR",
+            "-Xep:JUnitAmbiguousTestClass:ERROR",
+            "-Xep:MissingFail:ERROR",
+            "-Xep:SizeGreaterThanOrEqualsZero:ERROR",
+            "-Xep:TryFailThrowable:ERROR",
+        ],
+    },
+}
diff --git a/CleanSpec.mk b/CleanSpec.mk
index a7121ad..7bb2bdf 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -47,6 +47,7 @@
 $(call add-clean-step, rm -rf $(HOST_OUT_INTERMEDIATES)/EXECUTABLES/vm-tests-tf_intermediates)
 $(call add-clean-step, rm -rf $(OUT_DIR)/host/common/obj/JAVA_LIBRARIES/cts-tradefed_intermediates/com/android/compatibility/SuiteInfo.java)
 $(call add-clean-step, rm -rf $(HOST_OUT)/cts/android-cts/testcases/CtsUiHostTestCases*)
+$(call add-clean-step, rm -rf $(HOST_OUT)/cts_instant/android-cts_instant/testcases/CtsJobSchedulerTestCases*)
 
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
diff --git a/apps/CameraITS/pymodules/its/cv2image.py b/apps/CameraITS/pymodules/its/cv2image.py
index 8cd7ca9..21804e9 100644
--- a/apps/CameraITS/pymodules/its/cv2image.py
+++ b/apps/CameraITS/pymodules/its/cv2image.py
@@ -158,6 +158,9 @@
         print 'Finding chart in scene...'
         for scale in numpy.arange(scale_start, scale_stop, scale_step):
             scene_scaled = scale_img(scene_gray, scale)
+            if (scene_scaled.shape[0] < chart.shape[0] or
+                scene_scaled.shape[1] < chart.shape[1]):
+                continue
             result = cv2.matchTemplate(scene_scaled, chart, cv2.TM_CCOEFF)
             _, opt_val, _, top_left_scaled = cv2.minMaxLoc(result)
             # print out scale and match
diff --git a/apps/CameraITS/tests/scene0/test_read_write.py b/apps/CameraITS/tests/scene0/test_read_write.py
index 3c56fba..1b76806 100644
--- a/apps/CameraITS/tests/scene0/test_read_write.py
+++ b/apps/CameraITS/tests/scene0/test_read_write.py
@@ -21,7 +21,7 @@
 
 NAME = os.path.basename(__file__).split('.')[0]
 RTOL_EXP_GAIN = 0.97
-TEST_EXP_RANGE = [1E6, 1E9]  # ns [1ms, 1s]
+TEST_EXP_RANGE = [6E6, 1E9]  # ns [6ms, 1s]
 
 
 def main():
diff --git a/apps/CameraITS/tests/scene1/test_exposure.py b/apps/CameraITS/tests/scene1/test_exposure.py
index 460fe7c..cac49d0 100644
--- a/apps/CameraITS/tests/scene1/test_exposure.py
+++ b/apps/CameraITS/tests/scene1/test_exposure.py
@@ -33,7 +33,7 @@
 THRESH_ROUND_DOWN_GAIN = 0.1
 THRESH_ROUND_DOWN_EXP = 0.03
 THRESH_ROUND_DOWN_EXP0 = 1.00  # tol at 0ms exp; theoretical limit @ 4-line exp
-THRESH_EXP_KNEE = 1E6  # exposures less than 1ms have relaxed tol
+THRESH_EXP_KNEE = 6E6  # exposures less than knee have relaxed tol
 
 
 def get_raw_active_array_size(props):
@@ -67,9 +67,7 @@
         its.caps.skip_unless(its.caps.compute_target_exposure(props) and
                              its.caps.per_frame_control(props))
 
-        process_raw = (its.caps.compute_target_exposure(props) and
-                       its.caps.per_frame_control(props) and
-                       its.caps.raw16(props) and
+        process_raw = (its.caps.raw16(props) and
                        its.caps.manual_sensor(props))
 
         debug = its.caps.debug_mode()
@@ -112,7 +110,7 @@
             assert 0 <= e_test - e_res < e_test * thresh_round_down_exp, e_msg
             s_e_product_res = s_res * e_res
             request_result_ratio = s_e_product / s_e_product_res
-            print 'Capture result s:', s_test, 'e:', e_test
+            print 'Capture result s:', s_res, 'e:', e_res
             img = its.image.convert_capture_to_rgb_image(cap)
             its.image.write_image(img, '%s_mult=%3.2f.jpg' % (NAME, m))
             tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1)
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 0376cc1..c7888b6 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -488,6 +488,11 @@
         <!-- CTS Verifier BLE Server Encrypted Test Service -->
         <service android:name=".bluetooth.BleEncryptedServerService" />
 
+        <!-- CTS Verifier BLE CoC Client Test Service -->
+        <service android:name=".bluetooth.BleCocClientService" />
+        <!-- CTS Verifier BLE CoC Server Test Service -->
+        <service android:name=".bluetooth.BleCocServerService" />
+
         <!--
              =================================================================================
              ==                     BLE Insecure Client Test Info                           ==
@@ -571,6 +576,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.bluetooth_le" />
+            <meta-data
+                android:name="test_excluded_features"
+                android:value="android.hardware.type.watch"  />
         </activity>
 
         <!--
@@ -683,6 +691,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.bluetooth_le" />
+            <meta-data
+                android:name="test_excluded_features"
+                android:value="android.hardware.type.watch"  />
         </activity>
 
         <!--
@@ -796,6 +807,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.bluetooth_le" />
+            <meta-data
+                android:name="test_excluded_features"
+                android:value="android.hardware.type.watch"  />
         </activity>
 
         <!--
@@ -906,6 +920,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.bluetooth_le" />
+            <meta-data
+                android:name="test_excluded_features"
+                android:value="android.hardware.type.watch"  />
         </activity>
 
         <!--
@@ -937,6 +954,234 @@
 
         <!--
              =================================================================================
+             ==                     BLE CoC Insecure Client Test Info                       ==
+             =================================================================================
+        -->
+        <!--
+            CTS Verifier BLE CoC Insecure Client Test Top Screen
+                test category : bt_le_coc
+                test parent : BluetoothTestActivity
+        -->
+        <activity
+            android:name=".bluetooth.BleCocInsecureClientTestListActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/ble_coc_insecure_client_test_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+
+            <meta-data
+                android:name="test_category"
+                android:value="@string/bt_le_coc" />
+            <meta-data
+                android:name="test_parent"
+                android:value="com.android.cts.verifier.bluetooth.BluetoothTestActivity" />
+            <meta-data
+                android:name="test_required_features"
+                android:value="android.hardware.bluetooth_le" />
+        </activity>
+
+        <!--
+             CTS Verifier BLE CoC Insecure Client Test List Screen
+                 test category : bt_le_coc
+                 test parent : BleInsecureClientTestListActivity
+        -->
+        <activity
+            android:name=".bluetooth.BleCocInsecureClientStartActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/ble_coc_client_test_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+
+            <meta-data
+                android:name="test_category"
+                android:value="@string/bt_le_coc" />
+            <meta-data
+                android:name="test_parent"
+                android:value="com.android.cts.verifier.bluetooth.BleCocInsecureClientTestListActivity" />
+            <meta-data
+                android:name="test_required_features"
+                android:value="android.hardware.bluetooth_le" />
+        </activity>
+
+        <!--
+              =================================================================================
+              ==                     BLE CoC Insecure Server Test Info                       ==
+              =================================================================================
+        -->
+        <!--
+             CTS Verifier BLE Coc Insecure Server Test Top Screen
+                 test category : bt_le_coc
+                 test parent : BluetoothTestActivity
+        -->
+        <activity
+            android:name=".bluetooth.BleCocInsecureServerTestListActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/ble_coc_insecure_server_test_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+
+            <meta-data
+                android:name="test_category"
+                android:value="@string/bt_le_coc" />
+            <meta-data
+                android:name="test_parent"
+                android:value="com.android.cts.verifier.bluetooth.BluetoothTestActivity" />
+            <meta-data
+                android:name="test_required_features"
+                android:value="android.hardware.bluetooth_le" />
+        </activity>
+
+        <!--
+              CTS Verifier BLE Coc Insecure Server Test List Screen
+                  test category : bt_le_coc
+                  test parent : BleCocInsecureServerTestListActivity
+        -->
+        <activity
+            android:name=".bluetooth.BleCocInsecureServerStartActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/ble_coc_server_start_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+
+            <meta-data
+                android:name="test_category"
+                android:value="@string/bt_le_coc" />
+            <meta-data
+                android:name="test_parent"
+                android:value="com.android.cts.verifier.bluetooth.BleCocInsecureServerTestListActivity" />
+            <meta-data
+                android:name="test_required_features"
+                android:value="android.hardware.bluetooth_le" />
+        </activity>
+
+        <!--
+             =================================================================================
+             ==                     BLE CoC Secure Client Test Info                         ==
+             =================================================================================
+        -->
+        <!--
+            CTS Verifier BLE Coc Secure Client Test Top Screen
+                test category : bt_le_coc
+                test parent : BluetoothTestActivity
+        -->
+        <activity
+            android:name=".bluetooth.BleCocSecureClientTestListActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/ble_coc_secure_client_test_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+
+            <meta-data
+                android:name="test_category"
+                android:value="@string/bt_le_coc" />
+            <meta-data
+                android:name="test_parent"
+                android:value="com.android.cts.verifier.bluetooth.BluetoothTestActivity" />
+            <meta-data
+                android:name="test_required_features"
+                android:value="android.hardware.bluetooth_le" />
+        </activity>
+
+        <!--
+             CTS Verifier BLE Coc Secure Client Test List Screen
+                 test category : bt_le_coc
+                 test parent : BleSecureClientTestListActivity
+        -->
+        <activity
+            android:name=".bluetooth.BleCocSecureClientStartActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/ble_coc_client_test_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+
+            <meta-data
+                android:name="test_category"
+                android:value="@string/bt_le_coc" />
+            <meta-data
+                android:name="test_parent"
+                android:value="com.android.cts.verifier.bluetooth.BleCocSecureClientTestListActivity" />
+            <meta-data
+                android:name="test_required_features"
+                android:value="android.hardware.bluetooth_le" />
+        </activity>
+
+        <!--
+              =================================================================================
+              ==                     BLE CoC Secure Server Test Info                         ==
+              =================================================================================
+        -->
+        <!--
+             CTS Verifier BLE Coc Secure Server Test Top Screen
+                 test category : bt_le_coc
+                 test parent : BluetoothTestActivity
+        -->
+        <activity
+            android:name=".bluetooth.BleCocSecureServerTestListActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/ble_coc_secure_server_test_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+
+            <meta-data
+                android:name="test_category"
+                android:value="@string/bt_le_coc" />
+            <meta-data
+                android:name="test_parent"
+                android:value="com.android.cts.verifier.bluetooth.BluetoothTestActivity" />
+            <meta-data
+                android:name="test_required_features"
+                android:value="android.hardware.bluetooth_le" />
+        </activity>
+
+        <!--
+              CTS Verifier BLE Coc Secure Server Test List Screen
+                  test category : bt_le_coc
+                  test parent : BleCocSecureServerTestListActivity
+        -->
+        <activity
+            android:name=".bluetooth.BleCocSecureServerStartActivity"
+            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:label="@string/ble_coc_server_start_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+
+            <meta-data
+                android:name="test_category"
+                android:value="@string/bt_le_coc" />
+            <meta-data
+                android:name="test_parent"
+                android:value="com.android.cts.verifier.bluetooth.BleCocSecureServerTestListActivity" />
+            <meta-data
+                android:name="test_required_features"
+                android:value="android.hardware.bluetooth_le" />
+        </activity>
+
+        <!--
+             =================================================================================
              ==                      BLE Scanner Test Info                            ==
              =================================================================================
         -->
@@ -2616,11 +2861,15 @@
             </intent-filter>
             <intent-filter>
                 <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_STATUS" />
-                <category android:name="android.intent.category.DEFAULT"></category>
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+            <intent-filter>
+            <action android:name="com.android.cts.verifier.managedprovisioning.BYOD_TEST_RESULT" />
+                <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
             <intent-filter>
                 <action android:name="com.android.cts.verifier.managedprovisioning.action.BYOD_DISK_ENCRYPTION_STATUS" />
-                <category android:name="android.intent.category.DEFAULT"></category>
+                <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_managed_provisioning" />
             <meta-data android:name="test_required_features" android:value="android.software.managed_users:android.software.device_admin" />
@@ -2984,6 +3233,7 @@
             </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_excluded_features" android:value="android.software.leanback" />
         </activity>
 
         <activity android:name=".audio.AudioInputDeviceNotificationsActivity"
@@ -2994,6 +3244,7 @@
             </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_excluded_features" android:value="android.software.leanback" />
         </activity>
 
         <activity android:name=".audio.AudioOutputRoutingNotificationsActivity"
@@ -3004,7 +3255,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
             <meta-data android:name="test_required_features" android:value="android.hardware.audio.output" />
-            </activity>
+            <meta-data android:name="test_excluded_features" android:value="android.software.leanback" />
+        </activity>
 
         <activity android:name=".audio.AudioInputRoutingNotificationsActivity"
                   android:label="@string/audio_input_routingnotifications_test">
@@ -3014,7 +3266,8 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_audio" />
             <meta-data android:name="test_required_features" android:value="android.hardware.microphone" />
-            </activity>
+            <meta-data android:name="test_excluded_features" android:value="android.software.leanback" />
+        </activity>
 
         <activity android:name=".audio.USBAudioPeripheralAttributesActivity"
                   android:label="@string/audio_uap_attribs_test">
@@ -3213,6 +3466,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <receiver android:name=".voicemail.VoicemailBroadcastReceiver">
@@ -3235,6 +3491,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3251,6 +3510,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <service android:name=".dialer.DialerCallTestService"
@@ -3275,6 +3537,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3291,6 +3556,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3307,6 +3575,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3323,6 +3594,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <service
@@ -3367,6 +3641,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3383,6 +3660,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
             </activity>
 
         <activity
@@ -3399,6 +3679,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <activity
@@ -3415,6 +3698,9 @@
             <meta-data
                 android:name="test_required_features"
                 android:value="android.hardware.telephony"/>
+            <meta-data
+                android:name="test_required_configs"
+                android:value="config_voice_capable"/>
         </activity>
 
         <service android:name="com.android.cts.verifier.telecom.CtsConnectionService"
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index e4c0bda..9ec5dd3 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -183,6 +183,10 @@
         \n\n\"Bluetooth LE Insecure Server Test\" x \"Bluetooth LE Insecure Client Test\"
         \n\n\"Bluetooth LE Secure Client Test\" x \"Bluetooth LE Secure Server Test\"
         \n\n\"Bluetooth LE Secure Server Test\" x \"Bluetooth LE Secure Client Test\"
+        \n\n\"Bluetooth LE CoC Insecure Server Test\" x \"Bluetooth LE CoC Insecure Client Test\"
+        \n\n\"Bluetooth LE CoC Insecure Client Test\" x \"Bluetooth LE CoC Insecure Server Test\"
+        \n\n\"Bluetooth LE CoC Secure Server Test\" x \"Bluetooth LE CoC Secure Client Test\"
+        \n\n\"Bluetooth LE CoC Secure Client Test\" x \"Bluetooth LE CoC Secure Server Test\"
         \n\nThe Device Communication tests require two
         devices to pair and exchange messages. The two devices must be:
         \n\n1. a candidate device implementation running the software build to be tested
@@ -193,6 +197,7 @@
     <string name="bt_device_communication">Device Communication</string>
     <string name="bt_le">Bluetooth LE</string>
     <string name="bt_hid">Bluetooth HID</string>
+    <string name="bt_le_coc">Bluetooth LE CoC</string>
 
     <string name="bt_toggle_bluetooth">Toggle Bluetooth</string>
     <string name="bt_toggle_instructions">Disable and enable Bluetooth to successfully complete this test.</string>
@@ -201,6 +206,65 @@
     <string name="bt_disabling">Disabling Bluetooth...</string>
     <string name="bt_disabling_error">Could not disable Bluetooth...</string>
 
+    <string name="ble_coc_insecure_client_test_list_name">Bluetooth LE CoC Insecure Client Test</string>
+    <string name="ble_coc_insecure_client_test_list_info">
+        The Bluetooth LE CoC test must be done simultaneously on two devices. This device is the client.
+        All tests listed here must be done without pairing. Tap \"Bluetooth LE CoC Insecure Server Test\" on the other device.
+        \n\nTap \"01 Bluetooth LE CoC Client Test\" on this device, then tap \"01 Bluetooth LE CoC Server Test\" on the other device.
+        \nWhen the test is complete, move to the next item. You must complete all tests.
+    </string>
+    <string name="ble_coc_insecure_client_test_info">
+        The Bluetooth LE CoC test must be done simultaneously on two devices. This device is the client.
+        All tests listed here must be done without pairing.
+    </string>
+    <string name="ble_coc_insecure_server_test_list_name">Bluetooth LE CoC Insecure Server Test</string>
+    <string name="ble_coc_insecure_server_test_list_info">
+        This test is mostly automated, but requires some user interaction.
+        Once the list items below have check marks, the test is complete.
+        \n\nTap \"01 Bluetooth LE CoC Server Test\" on this device, then tap \"01 Bluetooth LE CoC Client Test\" on the other device.
+        \nWhen the test is complete, move to the next item. You must complete all tests.
+    </string>
+
+    <string name="ble_coc_secure_client_test_list_name">Bluetooth LE CoC Secure Client Test</string>
+    <string name="ble_coc_secure_client_test_list_info">
+        The Bluetooth LE CoC test must be done simultaneously on two devices. This device is the client.
+        All tests listed here must be done without pairing. Tap \"Bluetooth LE CoC Secure Server Test\" on the other device.
+        \n\nTap \"01 Bluetooth LE CoC Client Test\" on this device, then tap \"01 Bluetooth LE CoC Server Test\" on the other device.
+        \nWhen the test is complete, move to the next item. You must complete all tests.
+    </string>
+    <string name="ble_coc_secure_client_test_info">
+        The Bluetooth LE CoC test must be done simultaneously on two devices. This device is the client.
+        All tests listed here must be done without pairing.
+    </string>
+    <string name="ble_coc_secure_server_test_list_name">Bluetooth LE CoC Secure Server Test</string>
+    <string name="ble_coc_secure_server_test_list_info">
+        This test is mostly automated, but requires some user interaction.
+        Once the list items below have check marks, the test is complete.
+        \n\nTap \"01 Bluetooth LE CoC Server Test\" on this device, then tap \"01 Bluetooth LE CoC Client Test\" on the other device.
+        \nWhen the test is complete, move to the next item. You must complete all tests.
+    </string>
+
+    <!-- BLE CoC client side strings -->
+    <string name="ble_coc_client_test_name">01 Bluetooth LE CoC Client Test</string>
+    <string name="ble_coc_client_le_connect">Bluetooth LE Client Connect</string>
+    <string name="ble_coc_client_get_psm">Get peer PSM value</string>
+    <string name="ble_coc_client_coc_connect">LE CoC client Connect</string>
+    <string name="ble_coc_client_check_connection_type">Check connection type</string>
+    <string name="ble_coc_client_send_data_8bytes">Send 8 bytes</string>
+    <string name="ble_coc_client_receive_data_8bytes">Receive 8 bytes</string>
+    <string name="ble_coc_client_data_exchange">Send and receive large data buffer</string>
+
+    <!-- BLE CoC server side strings -->
+    <string name="ble_coc_server_start_name">01 Bluetooth LE CoC Server Test</string>
+    <string name="ble_coc_server_le_connect">Bluetooth LE Server Connect</string>
+    <string name="ble_coc_server_create_listener">Create LE CoC listener</string>
+    <string name="ble_coc_server_psm_read">Waiting on PSM to be read</string>
+    <string name="ble_coc_server_connection">Waiting on LE CoC connection</string>
+    <string name="ble_coc_server_check_connection_type">Check connection type</string>
+    <string name="ble_coc_server_receive_data_8bytes">Waiting to receive 8 bytes</string>
+    <string name="ble_coc_server_send_data_8bytes">Sending 8 bytes</string>
+    <string name="ble_coc_server_data_exchange">Send and receive large data buffer</string>
+
     <string name="bt_connection_access_server">Connection Access Server</string>
     <string name="bt_connection_access_client">Connection Access Client</string>
     <string name="bt_connection_access_server_info">
@@ -456,6 +520,11 @@
     <string name="ble_secure_server_test_name">Bluetooth LE Secure Server Test</string>
     <string name="ble_insecure_server_test_name">Bluetooth LE Insecure Server Test</string>
 
+    <string name="ble_coc_secure_client_test_name">Bluetooth LE CoC Secure Client Test</string>
+    <string name="ble_coc_insecure_client_test_name">Bluetooth LE CoC Insecure Client Test</string>
+    <string name="ble_coc_secure_server_test_name">Bluetooth LE CoC Secure Server Test</string>
+    <string name="ble_coc_insecure_server_test_name">Bluetooth LE CoC Insecure Server Test</string>
+
     <string name="ble_read_characteristic_nopermission_name">Bluetooth LE Read Characteristic Without Perrmission</string>
     <string name="ble_write_characteristic_nopermission_name">Bluetooth LE Write Characteristic Without Permission</string>
     <string name="ble_read_descriptor_nopermission_name">Bluetooth LE Read Descriptor Without Perrmission</string>
@@ -1999,7 +2068,7 @@
     <string name="provisioning_byod_recents_verify_redacted_instruction">
         1) Follow the instructions on-screen to set a work password.\n
         2) Turn the screen off and on again, or use the "lock now" button, to lock the work profile.\n
-        3) Open Recents.\n
+        3) Go to home screen and then open Recents.\n
         4) Confirm that this "CTS Verifier" activity is shown in Recents.\n
         5) Confirm that the contents of the activity <b>are</b> hidden.\n
         6) Return to this page and pass the test.
@@ -2177,9 +2246,9 @@
     <string name="device_admin_notification">This is device admin notification</string>
     <string name="device_admin_keyguard_disable_camera">Disable camera</string>
     <string name="device_admin_keyguard_disable_camera_instruction">
-        Please press the Go button to lock the screen. Then try to open the camera
-        from the lower right corner of the screen. Expected result is you cannot
-        open the camera from lock screen and it will ask for password instead.\n
+        Please press the Go button to lock the screen. Expected result is you cannot
+        see the camera icon on the lower right corner of the screen, or if there is one, you cannot
+        open the camera using it before you are asked for a password.\n
         Also, it shouldn\'t be possible to open the camera on the lockscreen by
         any other device specific gesture (such as double press on power button).
     </string>
@@ -2690,7 +2759,7 @@
     <string name="negative_device_owner">No Device Owner Tests</string>
     <string name="device_owner_negative_category">No Device Owner Tests</string>
     <string name="device_owner_provisioning_negative">Device owner provisioning</string>
-    <string name="device_owner_provisioning_negative_info">The device owner provisioning test verifies that setting up a corporate owned device can only be done on a factory reset device.\n\nPlease click the "Start provisioning" button, and when you see a warning dialog telling the device can\'t be set up, select "pass". Otherwise, select "fail".</string>
+    <string name="device_owner_provisioning_negative_info">The device owner provisioning test verifies that setting up a corporate owned device can only be done on a factory reset device.\n\nPlease click the "Start provisioning" button, and when you see a warning dialog telling the device is already set up, select "pass". Otherwise, select "fail".</string>
     <string name="start_device_owner_provisioning_button">Start provisioning</string>
     <string name="enterprise_privacy_quick_settings_negative">Quick settings disclosure</string>
     <string name="enterprise_privacy_quick_settings_negative_info">
@@ -2975,8 +3044,8 @@
     <string name="device_owner_disallow_usb_file_transfer_test_info">
             Please press below button to set the \"disallow USB file transfer\" restriction.\n
             If a USB notification appears, open the notification and check that the
-            \"Transfer files (MTP)\" and \"Transfer photos (PTP)\" cannot be selected and trigger a
-            support message when trying to select them.\n
+            \"Transfer files (MTP)\" and \"Transfer photos (PTP)\" options either are not displayed,
+            or they trigger a support message when trying to select them.\n
             Check if you can mount the device as a USB drive on your desktop computer. The test is
             successful if you cannot mount the device, and files from your phone cannot be
             downloaded through USB.\n
@@ -3278,13 +3347,16 @@
     <string name="disallow_outgoing_beam">Disallow outgoing beam</string>
     <string name="disallow_outgoing_beam_action">Switching on android beam</string>
     <string name="disallow_remove_user">Disallow remove user</string>
-    <string name="disallow_remove_user_action">Removing other users (please create a user and attempt to remove it to verify)</string>
+    <string name="disallow_remove_user_action">Removing other users (please create a user and attempt to remove it to verify). This test should also be considered as passed if \'remove user\' option cannot be found in Settings</string>
     <string name="disallow_remove_managed_profile">Disallow remove managed profile</string>
     <string name="disallow_remove_managed_profile_action">Removing the work profile. It shouldn\'t be possible neither from the Accounts screen nor the Device Administrators screen (after selecting the Device Administrator that corresponds to the badged version of \"CTS Verifier\")</string>
     <string name="disallow_share_location">Disallow share location</string>
     <string name="disallow_share_location_action">Turning on location sharing</string>
     <string name="disallow_uninstall_apps">Disallow uninstall apps</string>
-    <string name="disallow_uninstall_apps_action">Uninstalling applications from the work profile (badged applications) other than CtsVerifier</string>
+    <string name="disallow_uninstall_apps_action">
+        a. If testing in work profile: uninstall applications from the work profile (badged applications) other than CtsVerifier and system apps. \n
+        b. Otherwise: uninstall applications other than CtsVerifier and system apps
+    </string>
     <string name="disallow_unified_challenge">Disallow unified challenge</string>
     <string name="disallow_unified_challenge_action">Setting one lock for both personal and work profiles. IMPORTANT: Separate work lock should be set prior to this test in Set work lock test</string>
     <string name="disallow_keyguard_unredacted_notifications">Disallow lockscreen unredacted notification</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
index 44e2e0f..a339a43 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
@@ -22,6 +22,7 @@
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.os.Bundle;
+import android.telephony.TelephonyManager;
 import android.util.Log;
 import android.widget.ListView;
 
@@ -99,6 +100,10 @@
 
     private static final String TEST_APPLICABLE_FEATURES_META_DATA = "test_applicable_features";
 
+    private static final String TEST_REQUIRED_CONFIG_META_DATA = "test_required_configs";
+
+    private static final String CONFIG_VOICE_CAPABLE = "config_voice_capable";
+
     private final HashSet<String> mDisabledTests;
 
     private Context mContext;
@@ -188,10 +193,11 @@
             String testName = info.activityInfo.name;
             Intent intent = getActivityIntent(info.activityInfo);
             String[] requiredFeatures = getRequiredFeatures(info.activityInfo.metaData);
+            String[] requiredConfigs = getRequiredConfigs(info.activityInfo.metaData);
             String[] excludedFeatures = getExcludedFeatures(info.activityInfo.metaData);
             String[] applicableFeatures = getApplicableFeatures(info.activityInfo.metaData);
             TestListItem item = TestListItem.newTest(title, testName, intent, requiredFeatures,
-                    excludedFeatures, applicableFeatures);
+                     requiredConfigs, excludedFeatures, applicableFeatures);
 
             String testCategory = getTestCategory(mContext, info.activityInfo.metaData);
             addTestToCategory(testsByCategory, testCategory, item);
@@ -229,6 +235,19 @@
         }
     }
 
+    static String[] getRequiredConfigs(Bundle metaData) {
+        if (metaData == null) {
+            return null;
+        } else {
+            String value = metaData.getString(TEST_REQUIRED_CONFIG_META_DATA);
+            if (value == null) {
+                return null;
+            } else {
+                return value.split(":");
+            }
+        }
+    }
+
     static String[] getExcludedFeatures(Bundle metaData) {
         if (metaData == null) {
             return null;
@@ -305,10 +324,29 @@
         return true;
     }
 
+    private boolean matchAllConfigs(String[] configs) {
+        if (configs != null) {
+            TelephonyManager telephonyManager =
+                    (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
+            for (String config : configs) {
+                switch(config) {
+                    case CONFIG_VOICE_CAPABLE:
+                        if (!telephonyManager.isVoiceCapable()) {
+                            return false;
+                        }
+                    default:
+                        break;
+                }
+            }
+        }
+        return true;
+    }
+
     List<TestListItem> filterTests(List<TestListItem> tests) {
         List<TestListItem> filteredTests = new ArrayList<TestListItem>();
         for (TestListItem test : tests) {
-            if (!hasAnyFeature(test.excludedFeatures) && hasAllFeatures(test.requiredFeatures)) {
+            if (!hasAnyFeature(test.excludedFeatures) && hasAllFeatures(test.requiredFeatures)
+                    && matchAllConfigs(test.requiredConfigs)) {
                 if (test.applicableFeatures == null || hasAnyFeature(test.applicableFeatures)) {
                     filteredTests.add(test);
                 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
index 642b951..d9ea84f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestListAdapter.java
@@ -91,6 +91,9 @@
         /** Features necessary to run this test. */
         final String[] requiredFeatures;
 
+        /** Configs necessary to run this test. */
+        final String[] requiredConfigs;
+
         /** Features such that, if any present, the test gets excluded from being shown. */
         final String[] excludedFeatures;
 
@@ -117,20 +120,27 @@
         }
 
         public static TestListItem newTest(String title, String testName, Intent intent,
+                String[] requiredFeatures, String[] requiredConfigs, String[] excludedFeatures,
+                String[] applicableFeatures) {
+            return new TestListItem(title, testName, intent, requiredFeatures, requiredConfigs,
+                    excludedFeatures, applicableFeatures);
+        }
+
+        public static TestListItem newTest(String title, String testName, Intent intent,
                 String[] requiredFeatures, String[] excludedFeatures, String[] applicableFeatures) {
-            return new TestListItem(title, testName, intent, requiredFeatures, excludedFeatures,
+            return new TestListItem(title, testName, intent, requiredFeatures, null, excludedFeatures,
                     applicableFeatures);
         }
 
         public static TestListItem newTest(String title, String testName, Intent intent,
                 String[] requiredFeatures, String[] excludedFeatures) {
-            return new TestListItem(title, testName, intent, requiredFeatures, excludedFeatures,
+            return new TestListItem(title, testName, intent, requiredFeatures, null, excludedFeatures,
                     null);
         }
 
         public static TestListItem newTest(String title, String testName, Intent intent,
                 String[] requiredFeatures) {
-            return new TestListItem(title, testName, intent, requiredFeatures, null, null);
+            return new TestListItem(title, testName, intent, requiredFeatures, null, null, null);
         }
 
         public static TestListItem newCategory(Context context, int titleResId) {
@@ -138,15 +148,22 @@
         }
 
         public static TestListItem newCategory(String title) {
-            return new TestListItem(title, null, null, null, null, null);
+            return new TestListItem(title, null, null, null, null, null, null);
         }
 
         protected TestListItem(String title, String testName, Intent intent,
                 String[] requiredFeatures, String[] excludedFeatures, String[] applicableFeatures) {
+            this(title, testName, intent, requiredFeatures, null, excludedFeatures, applicableFeatures);
+        }
+
+        protected TestListItem(String title, String testName, Intent intent,
+                String[] requiredFeatures, String[] requiredConfigs, String[] excludedFeatures,
+                String[] applicableFeatures) {
             this.title = title;
             this.testName = testName;
             this.intent = intent;
             this.requiredFeatures = requiredFeatures;
+            this.requiredConfigs = requiredConfigs;
             this.excludedFeatures = excludedFeatures;
             this.applicableFeatures = applicableFeatures;
         }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java b/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java
index c5d2d52..07208dd 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/TestResult.java
@@ -68,7 +68,7 @@
                 testDetails, reportLog));
     }
 
-    private static Intent createResult(Activity activity, int testResult, String testName,
+    public static Intent createResult(Activity activity, int testResult, String testName,
             String testDetails, ReportLog reportLog) {
         Intent data = new Intent(activity, activity.getClass());
         addResultData(data, testResult, testName, testDetails, reportLog);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/StreamPlayer.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/StreamPlayer.java
index 12f1853..bebc2a7 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/StreamPlayer.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/audiolib/StreamPlayer.java
@@ -131,7 +131,7 @@
             allocBurstBuffer();
             return true;
         }  catch (UnsupportedOperationException ex) {
-            Log.i(TAG, "Couldn't open AudioTrack: " + ex);
+            Log.e(TAG, "Couldn't open AudioTrack: " + ex);
             mAudioTrack = null;
             return false;
         }
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 d9094e5..7cdff34 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,7 +120,7 @@
         mNumChannels = numChans;
         mSampleRate = sampleRate;
 
-        int chanPosMask = AudioUtils.countToInPositionMask(numChans);
+        int chanIndexMask = AudioUtils.countToIndexMask(numChans);
         int bufferSizeInBytes = 2048;   // Some, non-critical value
 
         try {
@@ -128,14 +128,14 @@
                     .setAudioFormat(new AudioFormat.Builder()
                             .setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
                             .setSampleRate(mSampleRate)
-                            .setChannelMask(chanPosMask)
+                            .setChannelIndexMask(chanIndexMask)
                             .build())
                     .setBufferSizeInBytes(bufferSizeInBytes)
                     .build();
 
             return true;
         } catch (UnsupportedOperationException ex) {
-            Log.i(TAG, "Couldn't open AudioRecord: " + ex);
+            Log.e(TAG, "Couldn't open AudioRecord: " + ex);
             mAudioRecord = null;
             return false;
         }
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/bluetooth/BleCocClientService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientService.java
new file mode 100644
index 0000000..183cebd
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientService.java
@@ -0,0 +1,725 @@
+/*
+ * Copyright 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.verifier.bluetooth;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import java.io.ByteArrayOutputStream;
+
+import com.android.cts.verifier.R;
+
+import android.app.Service;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothGatt;
+import android.bluetooth.BluetoothGattCallback;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattDescriptor;
+import android.bluetooth.BluetoothGattService;
+import android.bluetooth.BluetoothManager;
+import android.bluetooth.BluetoothProfile;
+import android.bluetooth.BluetoothSocket;
+import android.bluetooth.le.BluetoothLeScanner;
+import android.bluetooth.le.ScanCallback;
+import android.bluetooth.le.ScanFilter;
+import android.bluetooth.le.ScanResult;
+import android.bluetooth.le.ScanSettings;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Build;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Message;
+import android.os.ParcelUuid;
+import android.text.TextUtils;
+import android.util.Log;
+import android.widget.Toast;
+
+public class BleCocClientService extends Service {
+
+    public static final boolean DEBUG = true;
+    public static final String TAG = "BleCocClientService";
+
+    private static final int TRANSPORT_MODE_FOR_SECURE_CONNECTION = BluetoothDevice.TRANSPORT_LE;
+
+    public static final String BLE_LE_CONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_LE_CONNECTED";
+    public static final String BLE_GOT_PSM =
+            "com.android.cts.verifier.bluetooth.BLE_GOT_PSM";
+    public static final String BLE_COC_CONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CONNECTED";
+    public static final String BLE_CONNECTION_TYPE_CHECKED =
+            "com.android.cts.verifier.bluetooth.BLE_CONNECTION_TYPE_CHECKED";
+    public static final String BLE_DATA_8BYTES_SENT =
+            "com.android.cts.verifier.bluetooth.BLE_DATA_8BYTES_SENT";
+    public static final String BLE_DATA_8BYTES_READ =
+            "com.android.cts.verifier.bluetooth.BLE_DATA_8BYTES_READ";
+    public static final String BLE_DATA_LARGEBUF_READ =
+            "com.android.cts.verifier.bluetooth.BLE_DATA_LARGEBUF_READ";
+    public static final String BLE_LE_DISCONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_LE_DISCONNECTED";
+
+    public static final String BLE_BLUETOOTH_MISMATCH_SECURE =
+            "com.android.cts.verifier.bluetooth.BLE_BLUETOOTH_MISMATCH_SECURE";
+    public static final String BLE_BLUETOOTH_MISMATCH_INSECURE =
+            "com.android.cts.verifier.bluetooth.BLE_BLUETOOTH_MISMATCH_INSECURE";
+    public static final String BLE_BLUETOOTH_DISABLED =
+            "com.android.cts.verifier.bluetooth.BLE_BLUETOOTH_DISABLED";
+    public static final String BLE_GATT_CONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_GATT_CONNECTED";
+    public static final String BLE_BLUETOOTH_DISCONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_BLUETOOTH_DISCONNECTED";
+    public static final String BLE_CLIENT_ERROR =
+            "com.android.cts.verifier.bluetooth.BLE_CLIENT_ERROR";
+    public static final String EXTRA_COMMAND =
+            "com.android.cts.verifier.bluetooth.EXTRA_COMMAND";
+    public static final String EXTRA_WRITE_VALUE =
+            "com.android.cts.verifier.bluetooth.EXTRA_WRITE_VALUE";
+    public static final String EXTRA_BOOL =
+            "com.android.cts.verifier.bluetooth.EXTRA_BOOL";
+
+    // Literal for Client Action
+    public static final String BLE_COC_CLIENT_ACTION_LE_INSECURE_CONNECT =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_LE_INSECURE_CONNECT";
+    public static final String BLE_COC_CLIENT_ACTION_LE_SECURE_CONNECT =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_LE_SECURE_CONNECT";
+    public static final String BLE_COC_CLIENT_ACTION_GET_PSM =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_GET_PSM";
+    public static final String BLE_COC_CLIENT_ACTION_COC_CLIENT_CONNECT =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_COC_CLIENT_CONNECT";
+    public static final String BLE_COC_CLIENT_ACTION_CHECK_CONNECTION_TYPE =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_CHECK_CONNECTION_TYPE";
+    public static final String BLE_COC_CLIENT_ACTION_SEND_DATA_8BYTES =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_SEND_DATA_8BYTES";
+    public static final String BLE_COC_CLIENT_ACTION_READ_DATA_8BYTES =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_READ_DATA_8BYTES";
+    public static final String BLE_COC_CLIENT_ACTION_EXCHANGE_DATA =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_EXCHANGE_DATA";
+    public static final String BLE_COC_CLIENT_ACTION_CLIENT_CONNECT =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_CLIENT_CONNECT";
+    public static final String BLE_COC_CLIENT_ACTION_CLIENT_CONNECT_SECURE =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CLIENT_ACTION_CLIENT_CONNECT_SECURE";
+    public static final String BLE_CLIENT_ACTION_CLIENT_DISCONNECT =
+            "com.android.cts.verifier.bluetooth.BLE_CLIENT_ACTION_CLIENT_DISCONNECT";
+
+    private static final UUID SERVICE_UUID =
+            UUID.fromString("00009999-0000-1000-8000-00805f9b34fb");
+
+    /**
+     * UUID of the GATT Read Characteristics for LE_PSM value.
+     */
+    public static final UUID LE_PSM_CHARACTERISTIC_UUID =
+            UUID.fromString("2d410339-82b6-42aa-b34e-e2e01df8cc1a");
+
+    public static final String WRITE_VALUE = "CLIENT_TEST";
+    private static final String NOTIFY_VALUE = "NOTIFY_TEST";
+    private int mBleState = BluetoothProfile.STATE_DISCONNECTED;
+    private static final int EXECUTION_DELAY = 1500;
+
+    // current test category
+    private String mCurrentAction;
+
+    private BluetoothManager mBluetoothManager;
+    private BluetoothAdapter mBluetoothAdapter;
+    private BluetoothDevice mDevice;
+    private BluetoothGatt mBluetoothGatt;
+    private BluetoothLeScanner mScanner;
+    private Handler mHandler;
+    private boolean mSecure;
+    private boolean mValidityService;
+    private int mPsm;
+    private BluetoothChatService mChatService;
+    private int mNextReadExpectedLen = -1;
+    private String mNextReadCompletionIntent;
+    private int mTotalReadLen = 0;
+    private byte mNextReadByte;
+    private int mNextWriteExpectedLen = -1;
+    private String mNextWriteCompletionIntent = null;
+
+    // Handler for communicating task with peer.
+    private TestTaskQueue mTaskQueue;
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+
+        registerReceiver(mBondStatusReceiver,
+                         new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
+
+        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
+        mBluetoothAdapter = mBluetoothManager.getAdapter();
+        mScanner = mBluetoothAdapter.getBluetoothLeScanner();
+        mHandler = new Handler();
+
+        mTaskQueue = new TestTaskQueue(getClass().getName() + "_taskHandlerThread");
+    }
+
+    @Override
+    public int onStartCommand(final Intent intent, int flags, int startId) {
+        if (!mBluetoothAdapter.isEnabled()) {
+            notifyBluetoothDisabled();
+        } else {
+            mTaskQueue.addTask(new Runnable() {
+                @Override
+                public void run() {
+                    onTestFinish(intent.getAction());
+                }
+            }, EXECUTION_DELAY);
+        }
+        return START_NOT_STICKY;
+    }
+
+    private void onTestFinish(String action) {
+        mCurrentAction = action;
+        if (mCurrentAction != null) {
+            switch (mCurrentAction) {
+                case BLE_COC_CLIENT_ACTION_LE_INSECURE_CONNECT:
+                    mSecure = false;
+                    startScan();
+                    break;
+                case BLE_COC_CLIENT_ACTION_LE_SECURE_CONNECT:
+                    mSecure = true;
+                    startScan();
+                    break;
+                case BLE_COC_CLIENT_ACTION_GET_PSM:
+                    startLeDiscovery();
+                    break;
+                case BLE_COC_CLIENT_ACTION_COC_CLIENT_CONNECT:
+                    leCocClientConnect();
+                    break;
+                case BLE_COC_CLIENT_ACTION_CHECK_CONNECTION_TYPE:
+                    leCheckConnectionType();
+                    break;
+                case BLE_COC_CLIENT_ACTION_SEND_DATA_8BYTES:
+                    sendData8bytes();
+                    break;
+                case BLE_COC_CLIENT_ACTION_READ_DATA_8BYTES:
+                    readData8bytes();
+                    break;
+                case BLE_COC_CLIENT_ACTION_EXCHANGE_DATA:
+                    sendDataLargeBuf();
+                    readDataLargeBuf();
+                    break;
+                case BLE_CLIENT_ACTION_CLIENT_DISCONNECT:
+                    if (mBluetoothGatt != null) {
+                        mBluetoothGatt.disconnect();
+                    }
+                    if (mChatService != null) {
+                        mChatService.stop();
+                    }
+                    break;
+                default:
+                    Log.e(TAG, "Error: Unhandled or invalid action=" + mCurrentAction);
+            }
+        }
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        if (mBluetoothGatt != null) {
+            mBluetoothGatt.disconnect();
+            mBluetoothGatt.close();
+            mBluetoothGatt = null;
+        }
+        stopScan();
+        unregisterReceiver(mBondStatusReceiver);
+
+        if (mChatService != null) {
+            mChatService.stop();
+        }
+
+        mTaskQueue.quit();
+    }
+
+    public static BluetoothGatt connectGatt(BluetoothDevice device, Context context,
+                                            boolean autoConnect, boolean isSecure,
+                                            BluetoothGattCallback callback) {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+            if (isSecure) {
+                if (TRANSPORT_MODE_FOR_SECURE_CONNECTION == BluetoothDevice.TRANSPORT_AUTO) {
+                    Toast.makeText(context, "connectGatt(transport=AUTO)", Toast.LENGTH_SHORT)
+                    .show();
+                } else {
+                    Toast.makeText(context, "connectGatt(transport=LE)", Toast.LENGTH_SHORT).show();
+                }
+                return device.connectGatt(context, autoConnect, callback,
+                                          TRANSPORT_MODE_FOR_SECURE_CONNECTION);
+            } else {
+                Toast.makeText(context, "connectGatt(transport=LE)", Toast.LENGTH_SHORT).show();
+                return device.connectGatt(context, autoConnect, callback,
+                                          BluetoothDevice.TRANSPORT_LE);
+            }
+        } else {
+            Toast.makeText(context, "connectGatt", Toast.LENGTH_SHORT).show();
+            return device.connectGatt(context, autoConnect, callback);
+        }
+    }
+
+    private void readCharacteristic(UUID uuid) {
+        BluetoothGattCharacteristic characteristic = getCharacteristic(uuid);
+        if (characteristic != null) {
+            mBluetoothGatt.readCharacteristic(characteristic);
+        }
+    }
+
+    private void notifyError(String message) {
+        showMessage(message);
+        Log.e(TAG, message);
+
+        Intent intent = new Intent(BLE_CLIENT_ERROR);
+        sendBroadcast(intent);
+    }
+
+    private void notifyMismatchSecure() {
+        Intent intent = new Intent(BLE_BLUETOOTH_MISMATCH_SECURE);
+        sendBroadcast(intent);
+    }
+
+    private void notifyMismatchInsecure() {
+        Intent intent = new Intent(BLE_BLUETOOTH_MISMATCH_INSECURE);
+        sendBroadcast(intent);
+    }
+
+    private void notifyBluetoothDisabled() {
+        Intent intent = new Intent(BLE_BLUETOOTH_DISABLED);
+        sendBroadcast(intent);
+    }
+
+    private void notifyConnected() {
+        showMessage("Bluetooth LE GATT connected");
+        Intent intent = new Intent(BLE_LE_CONNECTED);
+        sendBroadcast(intent);
+    }
+
+    private void startLeDiscovery() {
+        // Start Service Discovery
+        if (mBluetoothGatt != null && mBleState == BluetoothProfile.STATE_CONNECTED) {
+            mBluetoothGatt.discoverServices();
+        } else {
+            showMessage("Bluetooth LE GATT not connected.");
+        }
+    }
+
+    private void notifyDisconnected() {
+        showMessage("Bluetooth LE disconnected");
+        Intent intent = new Intent(BLE_BLUETOOTH_DISCONNECTED);
+        sendBroadcast(intent);
+    }
+
+    private void notifyServicesDiscovered() {
+        showMessage("Service discovered");
+        // Find the LE_COC_PSM characteristics
+        if (DEBUG) {
+            Log.d(TAG, "notifyServicesDiscovered: Next step is to read the PSM char.");
+        }
+        readCharacteristic(LE_PSM_CHARACTERISTIC_UUID);
+    }
+
+    private BluetoothGattService getService() {
+        BluetoothGattService service = null;
+
+        if (mBluetoothGatt != null) {
+            service = mBluetoothGatt.getService(SERVICE_UUID);
+            if (service == null) {
+                showMessage("GATT Service not found");
+            }
+        }
+        return service;
+    }
+
+    private BluetoothGattCharacteristic getCharacteristic(UUID uuid) {
+        BluetoothGattCharacteristic characteristic = null;
+
+        BluetoothGattService service = getService();
+        if (service != null) {
+            characteristic = service.getCharacteristic(uuid);
+            if (characteristic == null) {
+                showMessage("Characteristic not found");
+            }
+        }
+        return characteristic;
+    }
+
+    private void showMessage(final String msg) {
+        mHandler.post(new Runnable() {
+            public void run() {
+                Toast.makeText(BleCocClientService.this, msg, Toast.LENGTH_SHORT).show();
+            }
+        });
+    }
+
+    private final BluetoothGattCallback mGattCallbacks = new BluetoothGattCallback() {
+        @Override
+        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
+            if (DEBUG) {
+                Log.d(TAG, "onConnectionStateChange: status=" + status + ", newState=" + newState);
+            }
+            if (status == BluetoothGatt.GATT_SUCCESS) {
+                if (newState == BluetoothProfile.STATE_CONNECTED) {
+                    mBleState = newState;
+                    int bondState = gatt.getDevice().getBondState();
+                    boolean bonded = false;
+                    BluetoothDevice target = gatt.getDevice();
+                    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
+                    if (!pairedDevices.isEmpty()) {
+                        for (BluetoothDevice device : pairedDevices) {
+                            if (device.getAddress().equals(target.getAddress())) {
+                                bonded = true;
+                                break;
+                            }
+                        }
+                    }
+                    if (mSecure && ((bondState == BluetoothDevice.BOND_NONE) || !bonded)) {
+                        // not pairing and execute Secure Test
+                        Log.e(TAG, "BluetoothGattCallback.onConnectionStateChange: "
+                              + "Not paired but execute secure test");
+                        mBluetoothGatt.disconnect();
+                        notifyMismatchSecure();
+                    } else if (!mSecure && ((bondState != BluetoothDevice.BOND_NONE) || bonded)) {
+                        // already pairing and execute Insecure Test
+                        Log.e(TAG, "BluetoothGattCallback.onConnectionStateChange: "
+                              + "Paired but execute insecure test");
+                        mBluetoothGatt.disconnect();
+                        notifyMismatchInsecure();
+                    } else {
+                        notifyConnected();
+                    }
+                } else if (status == BluetoothProfile.STATE_DISCONNECTED) {
+                    mBleState = newState;
+                    mSecure = false;
+                    mBluetoothGatt.close();
+                    notifyDisconnected();
+                }
+            } else {
+                showMessage("Failed to connect: " + status + " , newState = " + newState);
+                mBluetoothGatt.close();
+                mBluetoothGatt = null;
+            }
+        }
+
+        @Override
+        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
+            if (DEBUG) {
+                Log.d(TAG, "onServicesDiscovered: status=" + status);
+            }
+            if ((status == BluetoothGatt.GATT_SUCCESS) &&
+                (mBluetoothGatt.getService(SERVICE_UUID) != null)) {
+                notifyServicesDiscovered();
+            }
+        }
+
+        @Override
+        public void onCharacteristicRead(BluetoothGatt gatt,
+                BluetoothGattCharacteristic characteristic, int status) {
+            UUID uid = characteristic.getUuid();
+            if (DEBUG) {
+                Log.d(TAG, "onCharacteristicRead: status=" + status + ", uuid=" + uid);
+            }
+            if (status == BluetoothGatt.GATT_SUCCESS) {
+                String value = characteristic.getStringValue(0);
+                if (characteristic.getUuid().equals(LE_PSM_CHARACTERISTIC_UUID)) {
+                    mPsm = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
+                    if (DEBUG) {
+                        Log.d(TAG, "onCharacteristicRead: reading PSM=" + mPsm);
+                    }
+                    Intent intent = new Intent(BLE_GOT_PSM);
+                    sendBroadcast(intent);
+                } else {
+                    if (DEBUG) {
+                        Log.d(TAG, "onCharacteristicRead: Note: unknown uuid=" + uid);
+                    }
+                }
+            } else if (status == BluetoothGatt.GATT_READ_NOT_PERMITTED) {
+                notifyError("Not Permission Read: " + status + " : " + uid);
+            } else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
+                notifyError("Not Authentication Read: " + status + " : " + uid);
+            } else {
+                notifyError("Failed to read characteristic: " + status + " : " + uid);
+            }
+        }
+    };
+
+    private final ScanCallback mScanCallback = new ScanCallback() {
+        @Override
+        public void onScanResult(int callbackType, ScanResult result) {
+            if (mBluetoothGatt == null) {
+                // verify the validity of the advertisement packet.
+                mValidityService = false;
+                List<ParcelUuid> uuids = result.getScanRecord().getServiceUuids();
+                for (ParcelUuid uuid : uuids) {
+                    if (uuid.getUuid().equals(BleCocServerService.ADV_COC_SERVICE_UUID)) {
+                        if (DEBUG) {
+                            Log.d(TAG, "onScanResult: Found ADV with LE CoC Service UUID.");
+                        }
+                        mValidityService = true;
+                        break;
+                    }
+                }
+                if (mValidityService) {
+                    stopScan();
+
+                    BluetoothDevice device = result.getDevice();
+                    if (DEBUG) {
+                        Log.d(TAG, "onScanResult: Found ADV with CoC UUID on device="
+                              + device);
+                    }
+                    if (mSecure) {
+                        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
+                            if (!device.createBond()) {
+                                notifyError("Failed to call create bond");
+                            }
+                        } else {
+                            mDevice = device;
+                            mBluetoothGatt = connectGatt(result.getDevice(), BleCocClientService.this, false,
+                                                         mSecure, mGattCallbacks);
+                        }
+                    } else {
+                        mDevice = device;
+                        mBluetoothGatt = connectGatt(result.getDevice(), BleCocClientService.this, false, mSecure,
+                                                     mGattCallbacks);
+                    }
+                } else {
+                    notifyError("No valid service in Advertisement");
+                }
+            }
+        }
+    };
+
+    private boolean checkReadBufContent(byte[] buf, int len) {
+        // Check that the content is correct
+        for (int i = 0; i < len; i++) {
+            if (buf[i] != mNextReadByte) {
+                Log.e(TAG, "handleMessageRead: Error: wrong byte content. buf["
+                      + i + "]=" + buf[i] + " not equal to " + mNextReadByte);
+                return false;
+            }
+            mNextReadByte++;
+        }
+        return true;
+    }
+
+    private void handleMessageRead(Message msg) {
+        byte[] buf = (byte[])msg.obj;
+        int len = msg.arg1;
+        if (len <= 0) {
+            return;
+        }
+        mTotalReadLen += len;
+        if (DEBUG) {
+            Log.d(TAG, "handleMessageRead: receive buffer of length=" + len + ", mTotalReadLen="
+                  + mTotalReadLen + ", mNextReadExpectedLen=" + mNextReadExpectedLen);
+        }
+
+        if (mNextReadExpectedLen == mTotalReadLen) {
+            if (!checkReadBufContent(buf, len)) {
+                mNextReadExpectedLen = -1;
+                return;
+            }
+            showMessage("Read " + len + " bytes");
+            if (DEBUG) {
+                Log.d(TAG, "handleMessageRead: broadcast intent " + mNextReadCompletionIntent);
+            }
+            Intent intent = new Intent(mNextReadCompletionIntent);
+            sendBroadcast(intent);
+            mNextReadExpectedLen = -1;
+            mNextReadCompletionIntent = null;
+            mTotalReadLen = 0;
+        } else if (mNextReadExpectedLen > mTotalReadLen) {
+            if (!checkReadBufContent(buf, len)) {
+                mNextReadExpectedLen = -1;
+                return;
+            }
+        } else if (mNextReadExpectedLen < mTotalReadLen) {
+            Log.e(TAG, "handleMessageRead: Unexpected receive buffer of length=" + len
+                  + ", expected len=" + mNextReadExpectedLen);
+        }
+    }
+
+    private void sendMessage(byte[] buf) {
+        mChatService.write(buf);
+    }
+
+    private void handleMessageWrite(Message msg) {
+        byte[] buffer = (byte[]) msg.obj;
+        int len = buffer.length;
+
+        showMessage("LE Coc Client wrote " + len + " bytes");
+        if (len == mNextWriteExpectedLen) {
+            if (mNextWriteCompletionIntent != null) {
+                Intent intent = new Intent(mNextWriteCompletionIntent);
+                sendBroadcast(intent);
+            }
+        } else {
+            Log.d(TAG, "handleMessageWrite: unrecognized length=" + len);
+        }
+    }
+
+    private class ChatHandler extends Handler {
+        @Override
+        public void handleMessage(Message msg) {
+            super.handleMessage(msg);
+            if (DEBUG) {
+                Log.d(TAG, "ChatHandler.handleMessage: msg=" + msg);
+            }
+            int state = msg.arg1;
+            switch (msg.what) {
+            case BluetoothChatService.MESSAGE_STATE_CHANGE:
+                if (state == BluetoothChatService.STATE_CONNECTED) {
+                    // LE CoC is established
+                    notifyLeCocClientConnected();
+                }
+                break;
+            case BluetoothChatService.MESSAGE_READ:
+                handleMessageRead(msg);
+                break;
+            case BluetoothChatService.MESSAGE_WRITE:
+                handleMessageWrite(msg);
+                break;
+            }
+        }
+    }
+
+    private void notifyLeCocClientConnected() {
+        if (DEBUG) {
+            Log.d(TAG, "notifyLeCocClientConnected: device=" + mDevice + ", mSecure=" + mSecure);
+        }
+        showMessage("Bluetooth LE Coc connected");
+        Intent intent = new Intent(BLE_COC_CONNECTED);
+        sendBroadcast(intent);
+    }
+
+    private void leCocClientConnect() {
+        if (DEBUG) {
+            Log.d(TAG, "leCocClientConnect: device=" + mDevice + ", mSecure=" + mSecure);
+        }
+        if (mDevice == null) {
+            Log.e(TAG, "leCocClientConnect: mDevice is null");
+            return;
+        }
+        // Construct BluetoothChatService with useBle=true parameter
+        mChatService = new BluetoothChatService(this, new ChatHandler(), true);
+        mChatService.connect(mDevice, mSecure, mPsm);
+    }
+
+    private void leCheckConnectionType() {
+        if (mChatService == null) {
+            Log.e(TAG, "leCheckConnectionType: no LE Coc connection");
+            return;
+        }
+        int type = mChatService.getSocketConnectionType();
+        if (type != BluetoothSocket.TYPE_L2CAP) {
+            Log.e(TAG, "leCheckConnectionType: invalid connection type=" + type);
+            return;
+        }
+        showMessage("LE Coc Connection Type Checked");
+        Intent intent = new Intent(BLE_CONNECTION_TYPE_CHECKED);
+        sendBroadcast(intent);
+    }
+
+    private void sendData8bytes() {
+        if (DEBUG) Log.d(TAG, "sendData8bytes");
+
+        final byte[] buf = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
+        mNextWriteExpectedLen = 8;
+        mNextWriteCompletionIntent = BLE_DATA_8BYTES_SENT;
+        sendMessage(buf);
+    }
+
+    private void sendDataLargeBuf() {
+        final int len = BleCocServerService.TEST_DATA_EXCHANGE_BUFSIZE;
+        if (DEBUG) Log.d(TAG, "sendDataLargeBuf of size=" + len);
+
+        byte[] buf = new byte[len];
+        for (int i = 0; i < len; i++) {
+            buf[i] = (byte)(i + 1);
+        }
+        mNextWriteExpectedLen = len;
+        mNextWriteCompletionIntent = null;
+        sendMessage(buf);
+    }
+
+    private void readData8bytes() {
+        mNextReadExpectedLen = 8;
+        mNextReadCompletionIntent = BLE_DATA_8BYTES_READ;
+        mNextReadByte = 1;
+    }
+
+    private void readDataLargeBuf() {
+        mNextReadExpectedLen = BleCocServerService.TEST_DATA_EXCHANGE_BUFSIZE;
+        mNextReadCompletionIntent = BLE_DATA_LARGEBUF_READ;
+        mNextReadByte = 1;
+    }
+
+    private void startScan() {
+        if (DEBUG) Log.d(TAG, "startScan");
+        List<ScanFilter> filter = Arrays.asList(new ScanFilter.Builder().setServiceUuid(
+                new ParcelUuid(BleCocServerService.ADV_COC_SERVICE_UUID)).build());
+        ScanSettings setting = new ScanSettings.Builder()
+                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
+        mScanner.startScan(filter, setting, mScanCallback);
+    }
+
+    private void stopScan() {
+        if (DEBUG) Log.d(TAG, "stopScan");
+        if (mScanner != null) {
+            mScanner.stopScan(mScanCallback);
+        }
+    }
+
+    private final BroadcastReceiver mBondStatusReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
+                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+                int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
+                                               BluetoothDevice.BOND_NONE);
+                switch (state) {
+                    case BluetoothDevice.BOND_BONDED:
+                        if (mBluetoothGatt == null) {
+                            if (DEBUG) {
+                                Log.d(TAG, "onReceive:BOND_BONDED: calling connectGatt. device="
+                                             + device + ", mSecure=" + mSecure);
+                            }
+                            mDevice = device;
+                            mBluetoothGatt = connectGatt(device, BleCocClientService.this, false, mSecure,
+                                                         mGattCallbacks);
+                        }
+                        break;
+                    case BluetoothDevice.BOND_NONE:
+                        notifyError("Failed to create bond");
+                        break;
+                    case BluetoothDevice.BOND_BONDING:
+                        // fall through
+                    default:
+                        // wait for next state
+                        break;
+                }
+            }
+        }
+    };
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientTestBaseActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientTestBaseActivity.java
new file mode 100644
index 0000000..c5c84d2
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientTestBaseActivity.java
@@ -0,0 +1,295 @@
+/*
+ * Copyright 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.verifier.bluetooth;
+
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.ProgressDialog;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Handler;
+import android.widget.ListView;
+
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+
+import java.util.ArrayList;
+import java.util.List;
+import android.util.Log;
+
+public class BleCocClientTestBaseActivity extends PassFailButtons.Activity {
+    public static final String TAG = "BleCocClientTestBase";
+
+    private static final boolean STEP_EXECUTION = false;
+
+    private final int TEST_BLE_LE_CONNECTED = 0;
+    private final int TEST_BLE_GOT_PSM = 1;
+    private final int TEST_BLE_COC_CONNECTED = 2;
+    private final int TEST_BLE_CONNECTION_TYPE_CHECKED = 3;
+    private final int TEST_BLE_DATA_8BYTES_SENT = 4;
+    private final int TEST_BLE_DATA_8BYTES_READ = 5;
+    private final int TEST_BLE_DATA_EXCHANGED = 6;
+    private final int TEST_BLE_CLIENT_DISCONNECTED = 7;
+    private static final int PASS_FLAG_ALL = 0x00FF;
+
+    private TestAdapter mTestAdapter;
+    private long mPassed;
+    private Dialog mDialog;
+    private Handler mHandler;
+
+    private static final long BT_ON_DELAY = 10000;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.ble_server_start);
+        setPassFailButtonClickListeners();
+        getPassButton().setEnabled(false);
+
+        mTestAdapter = new TestAdapter(this, setupTestList());
+        ListView listView = (ListView) findViewById(R.id.ble_server_tests);
+        listView.setAdapter(mTestAdapter);
+
+        mPassed = 0;
+        mHandler = new Handler();
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+
+        IntentFilter filter = new IntentFilter();
+
+        filter.addAction(BleCocClientService.BLE_LE_CONNECTED);
+        filter.addAction(BleCocClientService.BLE_GOT_PSM);
+        filter.addAction(BleCocClientService.BLE_COC_CONNECTED);
+        filter.addAction(BleCocClientService.BLE_CONNECTION_TYPE_CHECKED);
+        filter.addAction(BleCocClientService.BLE_DATA_8BYTES_SENT);
+        filter.addAction(BleCocClientService.BLE_DATA_8BYTES_READ);
+        filter.addAction(BleCocClientService.BLE_DATA_LARGEBUF_READ);
+        filter.addAction(BleCocClientService.BLE_LE_DISCONNECTED);
+
+        filter.addAction(BleCocClientService.BLE_BLUETOOTH_DISCONNECTED);
+        filter.addAction(BleCocClientService.BLE_BLUETOOTH_DISABLED);
+        filter.addAction(BleCocClientService.BLE_BLUETOOTH_MISMATCH_SECURE);
+        filter.addAction(BleCocClientService.BLE_BLUETOOTH_MISMATCH_INSECURE);
+        filter.addAction(BleCocClientService.BLE_CLIENT_ERROR);
+
+        registerReceiver(mBroadcast, filter);
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        unregisterReceiver(mBroadcast);
+        closeDialog();
+    }
+
+    private synchronized void closeDialog() {
+        if (mDialog != null) {
+            mDialog.dismiss();
+            mDialog = null;
+        }
+    }
+
+    private synchronized void showProgressDialog() {
+        closeDialog();
+
+        ProgressDialog dialog = new ProgressDialog(this);
+        dialog.setTitle(R.string.ble_test_running);
+        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
+        dialog.setMessage(getString(R.string.ble_test_running_message));
+        dialog.setCanceledOnTouchOutside(false);
+        mDialog = dialog;
+        mDialog.show();
+    }
+
+    private List<Integer> setupTestList() {
+        ArrayList<Integer> testList = new ArrayList<Integer>();
+        testList.add(R.string.ble_coc_client_le_connect);
+        testList.add(R.string.ble_coc_client_get_psm);
+        testList.add(R.string.ble_coc_client_coc_connect);
+        testList.add(R.string.ble_coc_client_check_connection_type);
+        testList.add(R.string.ble_coc_client_send_data_8bytes);
+        testList.add(R.string.ble_coc_client_receive_data_8bytes);
+        testList.add(R.string.ble_coc_client_data_exchange);
+        testList.add(R.string.ble_client_disconnect_name);
+        return testList;
+    }
+
+    private void showErrorDialog(int titleId, int messageId, boolean finish) {
+        AlertDialog.Builder builder = new AlertDialog.Builder(this)
+                .setTitle(titleId)
+                .setMessage(messageId);
+        if (finish) {
+            builder.setOnCancelListener(new Dialog.OnCancelListener() {
+                @Override
+                public void onCancel(DialogInterface dialog) {
+                    finish();
+                }
+            });
+        }
+        builder.create().show();
+    }
+
+    private BroadcastReceiver mBroadcast = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            boolean showProgressDialog = false;
+            closeDialog();
+
+            String action = intent.getAction();
+            String newAction = null;
+            String actionName = null;
+            long previousPassed = mPassed;
+            final Intent startIntent = new Intent(BleCocClientTestBaseActivity.this, BleCocClientService.class);
+            if (action != null) {
+                Log.d(TAG, "Processing " + action);
+            }
+            switch (action) {
+            case BleCocClientService.BLE_LE_CONNECTED:
+                actionName = getString(R.string.ble_coc_client_le_connect);
+                mTestAdapter.setTestPass(TEST_BLE_LE_CONNECTED);
+                mPassed |= (1 << TEST_BLE_LE_CONNECTED);
+                // Start LE Service Discovery and then read the PSM
+                newAction = BleCocClientService.BLE_COC_CLIENT_ACTION_GET_PSM;
+                break;
+
+            case BleCocClientService.BLE_GOT_PSM:
+                actionName = getString(R.string.ble_coc_client_get_psm);
+                mTestAdapter.setTestPass(TEST_BLE_GOT_PSM);
+                mPassed |= (1 << TEST_BLE_GOT_PSM);
+                // Connect the LE CoC
+                newAction = BleCocClientService.BLE_COC_CLIENT_ACTION_COC_CLIENT_CONNECT;
+                break;
+
+            case BleCocClientService.BLE_COC_CONNECTED:
+                actionName = getString(R.string.ble_coc_client_coc_connect);
+                mTestAdapter.setTestPass(TEST_BLE_COC_CONNECTED);
+                mPassed |= (1 << TEST_BLE_COC_CONNECTED);
+                // Check the connection type
+                newAction = BleCocClientService.BLE_COC_CLIENT_ACTION_CHECK_CONNECTION_TYPE;
+                break;
+
+            case BleCocClientService.BLE_CONNECTION_TYPE_CHECKED:
+                actionName = getString(R.string.ble_coc_client_check_connection_type);
+                mTestAdapter.setTestPass(TEST_BLE_CONNECTION_TYPE_CHECKED);
+                mPassed |= (1 << TEST_BLE_CONNECTION_TYPE_CHECKED);
+                // Send 8 bytes
+                newAction = BleCocClientService.BLE_COC_CLIENT_ACTION_SEND_DATA_8BYTES;
+                break;
+
+            case BleCocClientService.BLE_DATA_8BYTES_SENT:
+                actionName = getString(R.string.ble_coc_client_send_data_8bytes);
+                mTestAdapter.setTestPass(TEST_BLE_DATA_8BYTES_SENT);
+                mPassed |= (1 << TEST_BLE_DATA_8BYTES_SENT);
+                // Read 8 bytes
+                newAction = BleCocClientService.BLE_COC_CLIENT_ACTION_READ_DATA_8BYTES;
+                break;
+
+            case BleCocClientService.BLE_DATA_8BYTES_READ:
+                actionName = getString(R.string.ble_coc_client_receive_data_8bytes);
+                mTestAdapter.setTestPass(TEST_BLE_DATA_8BYTES_READ);
+                mPassed |= (1 << TEST_BLE_DATA_8BYTES_READ);
+                // Do data exchanges
+                newAction = BleCocClientService.BLE_COC_CLIENT_ACTION_EXCHANGE_DATA;
+                break;
+
+            case BleCocClientService.BLE_DATA_LARGEBUF_READ:
+                actionName = getString(R.string.ble_coc_client_data_exchange);
+                mTestAdapter.setTestPass(TEST_BLE_DATA_EXCHANGED);
+                mPassed |= (1 << TEST_BLE_DATA_EXCHANGED);
+                // Disconnect
+                newAction = BleCocClientService.BLE_CLIENT_ACTION_CLIENT_DISCONNECT;
+                break;
+
+            case BleCocClientService.BLE_BLUETOOTH_DISCONNECTED:
+                mTestAdapter.setTestPass(TEST_BLE_CLIENT_DISCONNECTED);
+                mPassed |= (1 << TEST_BLE_CLIENT_DISCONNECTED);
+                // all tests done
+                newAction = null;
+                break;
+
+            case BleCocClientService.BLE_BLUETOOTH_DISABLED:
+                showErrorDialog(R.string.ble_bluetooth_disable_title, R.string.ble_bluetooth_disable_message, true);
+                break;
+
+            case BleCocClientService.BLE_BLUETOOTH_MISMATCH_SECURE:
+                showErrorDialog(R.string.ble_bluetooth_mismatch_title, R.string.ble_bluetooth_mismatch_secure_message, true);
+                break;
+
+            case BleCocClientService.BLE_BLUETOOTH_MISMATCH_INSECURE:
+                showErrorDialog(R.string.ble_bluetooth_mismatch_title, R.string.ble_bluetooth_mismatch_insecure_message, true);
+                break;
+
+            default:
+                Log.e(TAG, "onReceive: Error: unhandled action=" + action);
+            }
+
+            if (previousPassed != mPassed) {
+                String logMessage = String.format("Passed Flags has changed from 0x%08X to 0x%08X. Delta=0x%08X",
+                                                  previousPassed, mPassed, mPassed ^ previousPassed);
+                Log.d(TAG, logMessage);
+            }
+
+            mTestAdapter.notifyDataSetChanged();
+
+            if (newAction != null) {
+                Log.d(TAG, "Starting " + newAction);
+                startIntent.setAction(newAction);
+                if (STEP_EXECUTION) {
+                    closeDialog();
+                    final boolean showProgressDialogValue = showProgressDialog;
+                    mDialog = new AlertDialog.Builder(BleCocClientTestBaseActivity.this)
+                            .setTitle(actionName)
+                            .setMessage(R.string.ble_test_finished)
+                            .setCancelable(false)
+                            .setPositiveButton(R.string.ble_test_next,
+                                    new DialogInterface.OnClickListener() {
+                                        @Override
+                                        public void onClick(DialogInterface dialog, int which) {
+                                            closeDialog();
+                                            if (showProgressDialogValue) {
+                                                showProgressDialog();
+                                            }
+                                            startService(startIntent);
+                                        }
+                                    })
+                            .show();
+                } else {
+                    if (showProgressDialog) {
+                        showProgressDialog();
+                    }
+                    startService(startIntent);
+                }
+            } else {
+                closeDialog();
+            }
+
+            if (mPassed == PASS_FLAG_ALL) {
+                Log.d(TAG, "All Tests Passed.");
+                getPassButton().setEnabled(true);
+            }
+        }
+    };
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureClientStartActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureClientStartActivity.java
new file mode 100644
index 0000000..177f953
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureClientStartActivity.java
@@ -0,0 +1,44 @@
+/*

+ * Copyright 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.verifier.bluetooth;

+

+import android.content.Intent;

+import android.os.Bundle;

+import com.android.cts.verifier.R;

+

+public class BleCocInsecureClientStartActivity extends BleCocClientTestBaseActivity {

+    private Intent mIntent;

+

+    @Override

+    public void onCreate(Bundle savedInstanceState) {

+        super.onCreate(savedInstanceState);

+

+        setInfoResources(R.string.ble_coc_client_test_name,

+                R.string.ble_coc_insecure_client_test_info, -1);

+

+        mIntent = new Intent(this, BleCocClientService.class);

+        mIntent.setAction(BleCocClientService.BLE_COC_CLIENT_ACTION_LE_INSECURE_CONNECT);

+

+        startService(mIntent);

+    }

+

+    @Override

+    public void onDestroy() {

+        super.onDestroy();

+        stopService(mIntent);

+    }

+}

diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureClientTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureClientTestListActivity.java
new file mode 100644
index 0000000..f60909a
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureClientTestListActivity.java
@@ -0,0 +1,46 @@
+/*

+ * Copyright 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.verifier.bluetooth;

+

+import android.bluetooth.BluetoothAdapter;

+import android.os.Bundle;

+

+import com.android.cts.verifier.ManifestTestListAdapter;

+import com.android.cts.verifier.PassFailButtons;

+import com.android.cts.verifier.R;

+

+import java.util.ArrayList;

+import java.util.List;

+

+public class BleCocInsecureClientTestListActivity extends PassFailButtons.TestListActivity {

+

+    @Override

+    protected void onCreate(Bundle savedInstanceState) {

+        super.onCreate(savedInstanceState);

+        setContentView(R.layout.pass_fail_list);

+        setPassFailButtonClickListeners();

+        setInfoResources(R.string.ble_coc_insecure_client_test_list_name,

+                R.string.ble_coc_insecure_client_test_list_info,

+                -1);

+

+        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

+        List<String> disabledTest = new ArrayList<String>();

+

+        setTestListAdapter(new ManifestTestListAdapter(this, getClass().getName(),

+                disabledTest.toArray(new String[disabledTest.size()])));

+    }

+}

diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureServerStartActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureServerStartActivity.java
new file mode 100644
index 0000000..7f7808b
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureServerStartActivity.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 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.verifier.bluetooth;
+
+import android.content.Intent;
+import android.os.Bundle;
+
+public class BleCocInsecureServerStartActivity extends BleCocServerTestBaseActivity {
+    private Intent mIntent;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mIntent = new Intent(this, BleCocServerService.class);
+        mIntent.setAction(BleCocServerService.BLE_ACTION_COC_SERVER_INSECURE);
+        startService(mIntent);
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        stopService(mIntent);
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureServerTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureServerTestListActivity.java
new file mode 100644
index 0000000..2f5c59e
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocInsecureServerTestListActivity.java
@@ -0,0 +1,45 @@
+/*

+ * Copyright 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.verifier.bluetooth;

+

+import android.bluetooth.BluetoothAdapter;

+import android.os.Bundle;

+

+import com.android.cts.verifier.ManifestTestListAdapter;

+import com.android.cts.verifier.PassFailButtons;

+import com.android.cts.verifier.R;

+

+import java.util.ArrayList;

+import java.util.List;

+

+public class BleCocInsecureServerTestListActivity extends PassFailButtons.TestListActivity {

+

+    @Override

+    protected void onCreate(Bundle savedInstanceState) {

+        super.onCreate(savedInstanceState);

+        setContentView(R.layout.pass_fail_list);

+        setPassFailButtonClickListeners();

+        setInfoResources(R.string.ble_coc_insecure_server_test_list_name, R.string.ble_coc_insecure_server_test_list_info, -1);

+

+        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

+        List<String> disabledTest = new ArrayList<String>();

+        // TODO: Any need to remove certain tests based on supported features?

+

+        setTestListAdapter(new ManifestTestListAdapter(this, getClass().getName(),

+                disabledTest.toArray(new String[disabledTest.size()])));

+    }

+}

diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureClientStartActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureClientStartActivity.java
new file mode 100644
index 0000000..ae97daa
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureClientStartActivity.java
@@ -0,0 +1,44 @@
+/*

+ * Copyright 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.verifier.bluetooth;

+

+import android.content.Intent;

+import android.os.Bundle;

+import com.android.cts.verifier.R;

+

+public class BleCocSecureClientStartActivity extends BleCocClientTestBaseActivity {

+    private Intent mIntent;

+

+    @Override

+    public void onCreate(Bundle savedInstanceState) {

+        super.onCreate(savedInstanceState);

+

+        setInfoResources(R.string.ble_coc_client_test_name,

+                R.string.ble_coc_secure_client_test_info, -1);

+

+        mIntent = new Intent(this, BleCocClientService.class);

+        mIntent.setAction(BleCocClientService.BLE_COC_CLIENT_ACTION_LE_SECURE_CONNECT);

+

+        startService(mIntent);

+    }

+

+    @Override

+    public void onDestroy() {

+        super.onDestroy();

+        stopService(mIntent);

+    }

+}

diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureClientTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureClientTestListActivity.java
new file mode 100644
index 0000000..0370ab6
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureClientTestListActivity.java
@@ -0,0 +1,46 @@
+/*

+ * Copyright 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.verifier.bluetooth;

+

+import android.bluetooth.BluetoothAdapter;

+import android.os.Bundle;

+

+import com.android.cts.verifier.ManifestTestListAdapter;

+import com.android.cts.verifier.PassFailButtons;

+import com.android.cts.verifier.R;

+

+import java.util.ArrayList;

+import java.util.List;

+

+public class BleCocSecureClientTestListActivity extends PassFailButtons.TestListActivity {

+

+    @Override

+    protected void onCreate(Bundle savedInstanceState) {

+        super.onCreate(savedInstanceState);

+        setContentView(R.layout.pass_fail_list);

+        setPassFailButtonClickListeners();

+        setInfoResources(R.string.ble_coc_secure_client_test_list_name,

+                R.string.ble_coc_secure_client_test_list_info,

+                -1);

+

+        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

+        List<String> disabledTest = new ArrayList<String>();

+

+        setTestListAdapter(new ManifestTestListAdapter(this, getClass().getName(),

+                disabledTest.toArray(new String[disabledTest.size()])));

+    }

+}

diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureServerStartActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureServerStartActivity.java
new file mode 100644
index 0000000..b7b04ac
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureServerStartActivity.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 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.verifier.bluetooth;
+
+import android.content.Intent;
+import android.os.Bundle;
+
+public class BleCocSecureServerStartActivity extends BleCocServerTestBaseActivity {
+    private Intent mIntent;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mIntent = new Intent(this, BleCocServerService.class);
+        mIntent.setAction(BleCocServerService.BLE_ACTION_COC_SERVER_SECURE);
+        startService(mIntent);
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        stopService(mIntent);
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureServerTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureServerTestListActivity.java
new file mode 100644
index 0000000..84f541c
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocSecureServerTestListActivity.java
@@ -0,0 +1,45 @@
+/*

+ * Copyright 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.verifier.bluetooth;

+

+import android.bluetooth.BluetoothAdapter;

+import android.os.Bundle;

+

+import com.android.cts.verifier.ManifestTestListAdapter;

+import com.android.cts.verifier.PassFailButtons;

+import com.android.cts.verifier.R;

+

+import java.util.ArrayList;

+import java.util.List;

+

+public class BleCocSecureServerTestListActivity extends PassFailButtons.TestListActivity {

+

+    @Override

+    protected void onCreate(Bundle savedInstanceState) {

+        super.onCreate(savedInstanceState);

+        setContentView(R.layout.pass_fail_list);

+        setPassFailButtonClickListeners();

+        setInfoResources(R.string.ble_coc_secure_server_test_list_name, R.string.ble_coc_secure_server_test_list_info, -1);

+

+        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

+        List<String> disabledTest = new ArrayList<String>();

+        // TODO: Any need to remove certain tests based on supported features?

+

+        setTestListAdapter(new ManifestTestListAdapter(this, getClass().getName(),

+                disabledTest.toArray(new String[disabledTest.size()])));

+    }

+}

diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocServerService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocServerService.java
new file mode 100644
index 0000000..ee6342b
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocServerService.java
@@ -0,0 +1,766 @@
+/*
+ * Copyright 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.verifier.bluetooth;
+
+import android.app.Service;
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothGatt;
+import android.bluetooth.BluetoothGattCharacteristic;
+import android.bluetooth.BluetoothGattDescriptor;
+import android.bluetooth.BluetoothGattServer;
+import android.bluetooth.BluetoothGattServerCallback;
+import android.bluetooth.BluetoothGattService;
+import android.bluetooth.BluetoothManager;
+import android.bluetooth.BluetoothProfile;
+import android.bluetooth.BluetoothServerSocket;
+import android.bluetooth.BluetoothSocket;
+import android.bluetooth.le.AdvertiseCallback;
+import android.bluetooth.le.AdvertiseData;
+import android.bluetooth.le.AdvertiseSettings;
+import android.bluetooth.le.BluetoothLeAdvertiser;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Build;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Message;
+import android.os.ParcelUuid;
+import android.util.Log;
+import android.widget.Toast;
+
+import com.android.cts.verifier.R;
+
+import java.io.IOException;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Set;
+import java.util.Timer;
+import java.util.UUID;
+
+public class BleCocServerService extends Service {
+
+    public static final boolean DEBUG = true;
+    public static final String TAG = "BleCocServerService";
+
+    public static final int COMMAND_ADD_SERVICE = 0;
+    public static final int COMMAND_WRITE_CHARACTERISTIC = 1;
+    public static final int COMMAND_WRITE_DESCRIPTOR = 2;
+
+    public static final int TEST_DATA_EXCHANGE_BUFSIZE = 8 * 1024;
+
+    public static final String BLE_BLUETOOTH_MISMATCH_SECURE =
+            "com.android.cts.verifier.bluetooth.BLE_BLUETOOTH_MISMATCH_SECURE";
+    public static final String BLE_BLUETOOTH_MISMATCH_INSECURE =
+            "com.android.cts.verifier.bluetooth.BLE_BLUETOOTH_MISMATCH_INSECURE";
+    public static final String BLE_BLUETOOTH_DISABLED =
+            "com.android.cts.verifier.bluetooth.BLE_BLUETOOTH_DISABLED";
+
+    public static final String BLE_ACTION_COC_SERVER_INSECURE =
+            "com.android.cts.verifier.bluetooth.BLE_ACTION_COC_SERVER_INSECURE";
+    public static final String BLE_ACTION_COC_SERVER_SECURE =
+            "com.android.cts.verifier.bluetooth.BLE_ACTION_COC_SERVER_SECURE";
+
+    public static final String BLE_ACTION_SERVER_SECURE =
+            "com.android.cts.verifier.bluetooth.BLE_ACTION_SERVER_SECURE";
+    public static final String BLE_ACTION_SERVER_NON_SECURE =
+            "com.android.cts.verifier.bluetooth.BLE_ACTION_SERVER_NON_SECURE";
+
+    public static final String BLE_LE_CONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_LE_CONNECTED";
+    public static final String BLE_COC_LISTENER_CREATED =
+            "com.android.cts.verifier.bluetooth.BLE_COC_LISTENER_CREATED";
+    public static final String BLE_PSM_READ =
+            "com.android.cts.verifier.bluetooth.BLE_PSM_READ";
+    public static final String BLE_COC_CONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_COC_CONNECTED";
+    public static final String BLE_CONNECTION_TYPE_CHECKED =
+            "com.android.cts.verifier.bluetooth.BLE_CONNECTION_TYPE_CHECKED";
+    public static final String BLE_DATA_8BYTES_READ =
+            "com.android.cts.verifier.bluetooth.BLE_DATA_8BYTES_READ";
+    public static final String BLE_DATA_LARGEBUF_READ =
+            "com.android.cts.verifier.bluetooth.BLE_DATA_LARGEBUF_READ";
+    public static final String BLE_DATA_8BYTES_SENT =
+            "com.android.cts.verifier.bluetooth.BLE_DATA_8BYTES_SENT";
+    public static final String BLE_LE_DISCONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_LE_DISCONNECTED";
+    public static final String BLE_COC_SERVER_ACTION_SEND_DATA_8BYTES =
+            "com.android.cts.verifier.bluetooth.BLE_COC_SERVER_ACTION_SEND_DATA_8BYTES";
+    public static final String BLE_COC_SERVER_ACTION_EXCHANGE_DATA =
+            "com.android.cts.verifier.bluetooth.BLE_COC_SERVER_ACTION_EXCHANGE_DATA";
+    public static final String BLE_COC_SERVER_ACTION_DISCONNECT =
+            "com.android.cts.verifier.bluetooth.BLE_COC_SERVER_ACTION_DISCONNECT";
+
+    public static final String BLE_SERVER_DISCONNECTED =
+            "com.android.cts.verifier.bluetooth.BLE_SERVER_DISCONNECTED";
+    public static final String BLE_OPEN_FAIL =
+            "com.android.cts.verifier.bluetooth.BLE_OPEN_FAIL";
+    public static final String BLE_ADVERTISE_UNSUPPORTED =
+            "com.android.cts.verifier.bluetooth.BLE_ADVERTISE_UNSUPPORTED";
+    public static final String BLE_ADD_SERVICE_FAIL =
+            "com.android.cts.verifier.bluetooth.BLE_ADD_SERVICE_FAIL";
+
+    private static final UUID SERVICE_UUID =
+            UUID.fromString("00009999-0000-1000-8000-00805f9b34fb");
+    private static final UUID CHARACTERISTIC_UUID =
+            UUID.fromString("00009998-0000-1000-8000-00805f9b34fb");
+    private static final UUID CHARACTERISTIC_RESULT_UUID =
+            UUID.fromString("00009974-0000-1000-8000-00805f9b34fb");
+    private static final UUID UPDATE_CHARACTERISTIC_UUID =
+            UUID.fromString("00009997-0000-1000-8000-00805f9b34fb");
+    private static final UUID DESCRIPTOR_UUID =
+            UUID.fromString("00009996-0000-1000-8000-00805f9b34fb");
+    public static final UUID ADV_COC_SERVICE_UUID=
+            UUID.fromString("00003334-0000-1000-8000-00805f9b34fb");
+
+    private static final UUID SERVICE_UUID_ADDITIONAL =
+            UUID.fromString("00009995-0000-1000-8000-00805f9b34fb");
+    private static final UUID SERVICE_UUID_INCLUDED =
+            UUID.fromString("00009994-0000-1000-8000-00805f9b34fb");
+
+    // Variable for registration permission of Descriptor
+    private static final UUID DESCRIPTOR_NO_READ_UUID =
+            UUID.fromString("00009973-0000-1000-8000-00805f9b34fb");
+    private static final UUID DESCRIPTOR_NO_WRITE_UUID =
+            UUID.fromString("00009972-0000-1000-8000-00805f9b34fb");
+    private static final UUID DESCRIPTOR_NEED_ENCRYPTED_READ_UUID =
+            UUID.fromString("00009969-0000-1000-8000-00805f9b34fb");
+    private static final UUID DESCRIPTOR_NEED_ENCRYPTED_WRITE_UUID =
+            UUID.fromString("00009968-0000-1000-8000-00805f9b34fb");
+
+    private static final int CONN_INTERVAL = 150;   // connection interval 150ms
+
+    private static final int EXECUTION_DELAY = 1500;
+
+    // Delay of notification when secure test failed to start.
+    private static final long NOTIFICATION_DELAY_OF_SECURE_TEST_FAILURE = 5 * 1000;
+
+    public static final String WRITE_VALUE = "SERVER_TEST";
+    private static final String NOTIFY_VALUE = "NOTIFY_TEST";
+    private static final String INDICATE_VALUE = "INDICATE_TEST";
+    public static final String READ_NO_PERMISSION = "READ_NO_CHAR";
+    public static final String WRITE_NO_PERMISSION = "WRITE_NO_CHAR";
+    public static final String DESCRIPTOR_READ_NO_PERMISSION = "READ_NO_DESC";
+    public static final String DESCRIPTOR_WRITE_NO_PERMISSION = "WRITE_NO_DESC";
+
+    private BluetoothManager mBluetoothManager;
+    private BluetoothGattServer mGattServer;
+    private BluetoothGattService mService;
+    private BluetoothDevice mDevice;
+    private Handler mHandler;
+    private BluetoothLeAdvertiser mAdvertiser;
+    private boolean mSecure;
+    private int mMtuSize = -1;
+
+    private BluetoothServerSocket mServerSocket;
+    private int mPsm = -1;
+    private BluetoothGattCharacteristic mLePsmCharacteristic;
+    BluetoothChatService mChatService;
+
+    private int mNextReadExpectedLen = -1;
+    private String mNextReadCompletionIntent;
+    private int mTotalReadLen = 0;
+    private byte mNextReadByte;
+    private int mNextWriteExpectedLen = -1;
+    private String mNextWriteCompletionIntent = null;
+
+    // Handler for communicating task with peer.
+    private TestTaskQueue mTaskQueue;
+
+    // current test category
+    private String mCurrentAction;
+
+    // Task to notify failure of starting secure test.
+    //   Secure test calls BluetoothDevice#createBond() when devices were not paired.
+    //   createBond() causes onConnectionStateChange() twice, and it works as strange sequence.
+    //   At the first onConnectionStateChange(), target device is not paired (bond state is
+    //   BluetoothDevice.BOND_NONE).
+    //   At the second onConnectionStateChange(), target devices is paired (bond state is
+    //   BluetoothDevice.BOND_BONDED).
+    //   CTS Verifier will perform lazy check of bond state. Verifier checks bond state
+    //   after NOTIFICATION_DELAY_OF_SECURE_TEST_FAILURE from the first onConnectionStateChange().
+    private Runnable mNotificationTaskOfSecureTestStartFailure;
+
+    @Override
+    public void onCreate() {
+        super.onCreate();
+
+        mTaskQueue = new TestTaskQueue(getClass().getName() + "_taskHandlerThread");
+
+        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
+        mAdvertiser = mBluetoothManager.getAdapter().getBluetoothLeAdvertiser();
+        mGattServer = mBluetoothManager.openGattServer(this, mCallbacks);
+
+        mService = createService();
+
+        mDevice = null;
+
+        mHandler = new Handler();
+        if (!mBluetoothManager.getAdapter().isEnabled()) {
+            notifyBluetoothDisabled();
+        } else if (mGattServer == null) {
+            notifyOpenFail();
+        } else if (mAdvertiser == null) {
+            notifyAdvertiseUnsupported();
+        } else {
+            // start adding services
+            mSecure = false;
+            if (!mGattServer.addService(mService)) {
+                notifyAddServiceFail();
+            }
+        }
+    }
+
+    private void notifyBluetoothDisabled() {
+        Intent intent = new Intent(BLE_BLUETOOTH_DISABLED);
+        sendBroadcast(intent);
+    }
+
+    private void notifyMismatchSecure() {
+        Intent intent = new Intent(BLE_BLUETOOTH_MISMATCH_SECURE);
+        sendBroadcast(intent);
+    }
+
+    @Override
+    public int onStartCommand(Intent intent, int flags, int startId) {
+        String action = intent.getAction();
+        if (action != null) {
+            if (DEBUG) {
+                Log.d(TAG, "onStartCommand: action=" + action);
+            }
+            mTaskQueue.addTask(new Runnable() {
+                @Override
+                public void run() {
+                    onTestFinish(intent.getAction());
+                }
+            }, EXECUTION_DELAY);
+        }
+        return START_NOT_STICKY;
+    }
+
+    private void startServerTest(boolean secure) {
+        mSecure = secure;
+
+        if (mBluetoothManager.getAdapter().isEnabled() && (mChatService == null)) {
+            createChatService();
+        }
+
+        if (mBluetoothManager.getAdapter().isEnabled() && (mAdvertiser != null)) {
+            startAdvertise();
+        }
+    }
+
+    private void sendMessage(byte[] buf) {
+        mChatService.write(buf);
+    }
+
+    private void sendData8bytes() {
+        if (DEBUG) Log.d(TAG, "sendData8bytes");
+
+        final byte[] buf = new byte[]{1,2,3,4,5,6,7,8};
+        mNextWriteExpectedLen = 8;
+        mNextWriteCompletionIntent = BLE_DATA_8BYTES_SENT;
+        sendMessage(buf);
+    }
+
+    private void sendDataLargeBuf() {
+        final int len = BleCocServerService.TEST_DATA_EXCHANGE_BUFSIZE;
+        if (DEBUG) Log.d(TAG, "sendDataLargeBuf of size=" + len);
+
+        byte[] buf = new byte[len];
+        for (int i = 0; i < len; i++) {
+            buf[i] = (byte)(i + 1);
+        }
+        mNextWriteExpectedLen = len;
+        mNextWriteCompletionIntent = null;
+        sendMessage(buf);
+    }
+
+    private void onTestFinish(String action) {
+        mCurrentAction = action;
+        if (mCurrentAction != null) {
+            switch (mCurrentAction) {
+                case BLE_ACTION_COC_SERVER_INSECURE:
+                    startServerTest(false);
+                    break;
+                case BLE_ACTION_COC_SERVER_SECURE:
+                    startServerTest(true);
+                    break;
+                case BLE_COC_SERVER_ACTION_SEND_DATA_8BYTES:
+                    sendData8bytes();
+                    break;
+                case BLE_COC_SERVER_ACTION_EXCHANGE_DATA:
+                    sendDataLargeBuf();
+                    readDataLargeBuf();
+                    break;
+                case BLE_COC_SERVER_ACTION_DISCONNECT:
+                    if (mChatService != null) {
+                        mChatService.stop();
+                    }
+                    break;
+                default:
+                    Log.e(TAG, "Error: Unhandled or invalid action=" + mCurrentAction);
+            }
+        }
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return null;
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+
+        if (mChatService != null) {
+            mChatService.stop();
+        }
+
+        cancelNotificationTaskOfSecureTestStartFailure();
+        stopAdvertise();
+
+        mTaskQueue.quit();
+
+        if (mGattServer == null) {
+           return;
+        }
+        if (mDevice != null) {
+            mGattServer.cancelConnection(mDevice);
+        }
+        mGattServer.clearServices();
+        mGattServer.close();
+    }
+
+    private void notifyOpenFail() {
+        if (DEBUG) {
+            Log.d(TAG, "notifyOpenFail");
+        }
+        Intent intent = new Intent(BLE_OPEN_FAIL);
+        sendBroadcast(intent);
+    }
+
+    private void notifyAddServiceFail() {
+        if (DEBUG) {
+            Log.d(TAG, "notifyAddServiceFail");
+        }
+        Intent intent = new Intent(BLE_ADD_SERVICE_FAIL);
+        sendBroadcast(intent);
+    }
+
+    private void notifyAdvertiseUnsupported() {
+        if (DEBUG) {
+            Log.d(TAG, "notifyAdvertiseUnsupported");
+        }
+        Intent intent = new Intent(BLE_ADVERTISE_UNSUPPORTED);
+        sendBroadcast(intent);
+    }
+
+    private void notifyConnected() {
+        if (DEBUG) {
+            Log.d(TAG, "notifyConnected");
+        }
+        Intent intent = new Intent(BLE_LE_CONNECTED);
+        sendBroadcast(intent);
+    }
+
+    private void notifyDisconnected() {
+        if (DEBUG) {
+            Log.d(TAG, "notifyDisconnected");
+        }
+        Intent intent = new Intent(BLE_SERVER_DISCONNECTED);
+        sendBroadcast(intent);
+    }
+
+    private BluetoothGattService createService() {
+        BluetoothGattService service =
+                new BluetoothGattService(SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY);
+        BluetoothGattCharacteristic characteristic =
+                new BluetoothGattCharacteristic(CHARACTERISTIC_UUID, 0x0A, 0x11);
+        characteristic.setValue(WRITE_VALUE.getBytes());
+
+        BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(DESCRIPTOR_UUID, 0x11);
+        descriptor.setValue(WRITE_VALUE.getBytes());
+        characteristic.addDescriptor(descriptor);
+
+        BluetoothGattDescriptor descriptor_permission =
+            new BluetoothGattDescriptor(DESCRIPTOR_NO_READ_UUID, 0x10);
+        characteristic.addDescriptor(descriptor_permission);
+
+        descriptor_permission = new BluetoothGattDescriptor(DESCRIPTOR_NO_WRITE_UUID, 0x01);
+        characteristic.addDescriptor(descriptor_permission);
+
+        service.addCharacteristic(characteristic);
+
+        // Registered the characteristic of PSM Value
+        mLePsmCharacteristic =
+                new BluetoothGattCharacteristic(BleCocClientService.LE_PSM_CHARACTERISTIC_UUID,
+                                                BluetoothGattCharacteristic.PROPERTY_READ,
+                                                BluetoothGattCharacteristic.PERMISSION_READ);
+        service.addCharacteristic(mLePsmCharacteristic);
+
+        return service;
+    }
+
+    private void showMessage(final String msg) {
+        mHandler.post(new Runnable() {
+            public void run() {
+                Toast.makeText(BleCocServerService.this, msg, Toast.LENGTH_SHORT).show();
+            }
+        });
+    }
+
+    private synchronized void cancelNotificationTaskOfSecureTestStartFailure() {
+        if (mNotificationTaskOfSecureTestStartFailure != null) {
+            mHandler.removeCallbacks(mNotificationTaskOfSecureTestStartFailure);
+            mNotificationTaskOfSecureTestStartFailure = null;
+        }
+    }
+
+    private final BluetoothGattServerCallback mCallbacks = new BluetoothGattServerCallback() {
+        @Override
+        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
+            if (DEBUG) {
+                Log.d(TAG, "onConnectionStateChange: newState=" + newState);
+            }
+
+            if (status == BluetoothGatt.GATT_SUCCESS) {
+                if (newState == BluetoothProfile.STATE_CONNECTED) {
+                    mDevice = device;
+                    boolean bonded = false;
+                    Set<BluetoothDevice> pairedDevices =
+                        mBluetoothManager.getAdapter().getBondedDevices();
+                    if (pairedDevices.size() > 0) {
+                        for (BluetoothDevice target : pairedDevices) {
+                            if (target.getAddress().equals(device.getAddress())) {
+                                bonded = true;
+                                break;
+                            }
+                        }
+                    }
+
+                    if (mSecure && ((device.getBondState() == BluetoothDevice.BOND_NONE) ||
+                                    !bonded)) {
+                        // not pairing and execute Secure Test
+                        Log.e(TAG, "BluetoothGattServerCallback.onConnectionStateChange: "
+                              + "Not paired but execute secure test");
+                        cancelNotificationTaskOfSecureTestStartFailure();
+                    } else if (!mSecure && ((device.getBondState() != BluetoothDevice.BOND_NONE)
+                                            || bonded)) {
+                        // already pairing and execute Insecure Test
+                        Log.e(TAG, "BluetoothGattServerCallback.onConnectionStateChange: "
+                              + "Paired but execute insecure test");
+                    } else {
+                        cancelNotificationTaskOfSecureTestStartFailure();
+                    }
+                    notifyConnected();
+                } else if (status == BluetoothProfile.STATE_DISCONNECTED) {
+                    notifyDisconnected();
+                    mDevice = null;
+                }
+            }
+        }
+
+        @Override
+        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset,
+                BluetoothGattCharacteristic characteristic) {
+            if (mGattServer == null) {
+                if (DEBUG) {
+                    Log.d(TAG, "GattServer is null, return");
+                }
+                return;
+            }
+            if (DEBUG) {
+                Log.d(TAG, "onCharacteristicReadRequest()");
+            }
+
+            boolean finished = false;
+            byte[] value = null;
+            if (mMtuSize > 0) {
+                byte[] buf = characteristic.getValue();
+                if (buf != null) {
+                    int len = Math.min((buf.length - offset), mMtuSize);
+                    if (len > 0) {
+                        value = Arrays.copyOfRange(buf, offset, (offset + len));
+                    }
+                    finished = ((offset + len) >= buf.length);
+                    if (finished) {
+                        Log.d(TAG, "sent whole data: " + (new String(characteristic.getValue())));
+                    }
+                }
+            } else {
+                value = characteristic.getValue();
+                finished = true;
+            }
+
+            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
+
+            UUID uid = characteristic.getUuid();
+            if (uid.equals(BleCocClientService.LE_PSM_CHARACTERISTIC_UUID)) {
+                Log.d(TAG, "onCharacteristicReadRequest: reading PSM");
+            }
+        }
+
+    };
+
+    private void leCheckConnectionType() {
+        if (mChatService == null) {
+            Log.e(TAG, "leCheckConnectionType: no LE Coc connection");
+            return;
+        }
+        int type = mChatService.getSocketConnectionType();
+        if (type != BluetoothSocket.TYPE_L2CAP) {
+            Log.e(TAG, "leCheckConnectionType: invalid connection type=" + type);
+            return;
+        }
+        showMessage("LE CoC Connection Type Checked");
+        Intent intent = new Intent(BLE_CONNECTION_TYPE_CHECKED);
+        sendBroadcast(intent);
+    }
+
+    private void readData8bytes() {
+        mNextReadExpectedLen = 8;
+        mTotalReadLen = 0;
+        mNextReadCompletionIntent = BLE_DATA_8BYTES_READ;
+        mNextReadByte = 1;
+    }
+
+    private void readDataLargeBuf() {
+        mNextReadExpectedLen = BleCocServerService.TEST_DATA_EXCHANGE_BUFSIZE;
+        mTotalReadLen = 0;
+        mNextReadCompletionIntent = BLE_DATA_LARGEBUF_READ;
+        mNextReadByte = 1;
+    }
+
+    private void processChatStateChange(int newState) {
+        Intent intent;
+        if (DEBUG) {
+            Log.d(TAG, "processChatStateChange: newState=" + newState);
+        }
+        switch (newState) {
+        case BluetoothChatService.STATE_LISTEN:
+            intent = new Intent(BLE_COC_LISTENER_CREATED);
+            sendBroadcast(intent);
+            break;
+        case BluetoothChatService.STATE_CONNECTED:
+            intent = new Intent(BLE_COC_CONNECTED);
+            sendBroadcast(intent);
+
+            // Check the connection type
+            leCheckConnectionType();
+
+            // Prepare the next data read
+            readData8bytes();
+            break;
+        }
+    }
+
+    private boolean checkReadBufContent(byte[] buf, int len) {
+        // Check that the content is correct
+        for (int i = 0; i < len; i++) {
+            if (buf[i] != mNextReadByte) {
+                Log.e(TAG, "handleMessageRead: Error: wrong byte content. buf["
+                      + i + "]=" + buf[i] + " not equal to " + mNextReadByte);
+                return false;
+            }
+            mNextReadByte++;
+        }
+        return true;
+    }
+
+    private void handleMessageRead(Message msg) {
+        byte[] buf = (byte[])msg.obj;
+        int len = msg.arg1;
+        if (len <= 0) {
+            return;
+        }
+        mTotalReadLen += len;
+        if (DEBUG) {
+            Log.d(TAG, "handleMessageRead: receive buffer of length=" + len + ", mTotalReadLen="
+                  + mTotalReadLen + ", mNextReadExpectedLen=" + mNextReadExpectedLen);
+        }
+
+        if (mNextReadExpectedLen == mTotalReadLen) {
+            if (!checkReadBufContent(buf, len)) {
+                mNextReadExpectedLen = -1;
+                return;
+            }
+            showMessage("Read " + len + " bytes");
+            if (DEBUG) {
+                Log.d(TAG, "handleMessageRead: broadcast intent " + mNextReadCompletionIntent);
+            }
+            Intent intent = new Intent(mNextReadCompletionIntent);
+            sendBroadcast(intent);
+            mNextReadExpectedLen = -1;
+            mNextReadCompletionIntent = null;
+            mTotalReadLen = 0;
+        } else if (mNextReadExpectedLen > mTotalReadLen) {
+            if (!checkReadBufContent(buf, len)) {
+                mNextReadExpectedLen = -1;
+                return;
+            }
+        } else if (mNextReadExpectedLen < mTotalReadLen) {
+            Log.e(TAG, "handleMessageRead: Unexpected receive buffer of length=" + len
+                  + ", expected len=" + mNextReadExpectedLen);
+        }
+    }
+
+    private void handleMessageWrite(Message msg) {
+        byte[] buffer = (byte[]) msg.obj;
+        int len = buffer.length;
+        showMessage("LE CoC Server wrote " + len + " bytes" + ", mNextWriteExpectedLen="
+                    + mNextWriteExpectedLen);
+        if (len == mNextWriteExpectedLen) {
+            if (mNextWriteCompletionIntent != null) {
+                Intent intent = new Intent(mNextWriteCompletionIntent);
+                sendBroadcast(intent);
+            }
+        } else {
+            Log.d(TAG, "handleMessageWrite: unrecognized length=" + len);
+        }
+        mNextWriteCompletionIntent = null;
+        mNextWriteExpectedLen = -1;
+    }
+
+    private class ChatHandler extends Handler {
+        @Override
+        public void handleMessage(Message msg) {
+            super.handleMessage(msg);
+            if (DEBUG) {
+                Log.d(TAG, "ChatHandler.handleMessage: msg=" + msg);
+            }
+            switch (msg.what) {
+                case BluetoothChatService.MESSAGE_STATE_CHANGE:
+                    processChatStateChange(msg.arg1);
+                    break;
+                case BluetoothChatService.MESSAGE_READ:
+                    handleMessageRead(msg);
+                    break;
+                case BluetoothChatService.MESSAGE_WRITE:
+                    handleMessageWrite(msg);
+                    break;
+            }
+        }
+    }
+
+    /* Start the Chat Service to create the Bluetooth Server Socket for LE CoC */
+    private void createChatService() {
+
+        mChatService = new BluetoothChatService(this, new ChatHandler(), true);
+        mChatService.start(mSecure);
+        mPsm = mChatService.getPsm(mSecure);
+        if (DEBUG) {
+            Log.d(TAG, "createChatService: assigned PSM=" + mPsm);
+        }
+        if (mPsm > 0x00ff) {
+            Log.e(TAG, "createChatService: Invalid PSM=" + mPsm);
+        }
+        // Notify that the PSM is read
+        Intent intent = new Intent(BLE_PSM_READ);
+        sendBroadcast(intent);
+
+        // Set the PSM value in the PSM characteristics in the GATT Server.
+        mLePsmCharacteristic.setValue(mPsm, BluetoothGattCharacteristic.FORMAT_UINT8, 0);
+    }
+
+    private void startAdvertise() {
+        if (DEBUG) {
+            Log.d(TAG, "startAdvertise");
+        }
+        AdvertiseData data = new AdvertiseData.Builder()
+            .addServiceData(new ParcelUuid(ADV_COC_SERVICE_UUID), new byte[]{1,2,3})
+            .addServiceUuid(new ParcelUuid(ADV_COC_SERVICE_UUID))
+            .build();
+        AdvertiseSettings setting = new AdvertiseSettings.Builder()
+            .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
+            .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
+            .setConnectable(true)
+            .build();
+        mAdvertiser.startAdvertising(setting, data, mAdvertiseCallback);
+    }
+
+    private void stopAdvertise() {
+        if (DEBUG) {
+            Log.d(TAG, "stopAdvertise");
+        }
+        if (mAdvertiser != null) {
+            mAdvertiser.stopAdvertising(mAdvertiseCallback);
+        }
+    }
+
+    private final AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback(){
+        @Override
+        public void onStartFailure(int errorCode) {
+            // Implementation for API Test.
+            super.onStartFailure(errorCode);
+            if (DEBUG) {
+                Log.d(TAG, "onStartFailure");
+            }
+
+            if (errorCode == ADVERTISE_FAILED_FEATURE_UNSUPPORTED) {
+                notifyAdvertiseUnsupported();
+            } else {
+                notifyOpenFail();
+            }
+        }
+
+        @Override
+        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
+            // Implementation for API Test.
+            super.onStartSuccess(settingsInEffect);
+            if (DEBUG) {
+                Log.d(TAG, "onStartSuccess");
+            }
+        }
+    };
+
+    /*protected*/ static void dumpService(BluetoothGattService service, int level) {
+        String indent = "";
+        for (int i = 0; i < level; ++i) {
+            indent += "  ";
+        }
+
+        Log.d(TAG, indent + "[service]");
+        Log.d(TAG, indent + "UUID: " + service.getUuid());
+        Log.d(TAG, indent + "  [characteristics]");
+        for (BluetoothGattCharacteristic ch : service.getCharacteristics()) {
+            Log.d(TAG, indent + "    UUID: " + ch.getUuid());
+            Log.d(TAG, indent + "      properties: "
+                  + String.format("0x%02X", ch.getProperties()));
+            Log.d(TAG, indent + "      permissions: "
+                  + String.format("0x%02X", ch.getPermissions()));
+            Log.d(TAG, indent + "      [descriptors]");
+            for (BluetoothGattDescriptor d : ch.getDescriptors()) {
+                Log.d(TAG, indent + "        UUID: " + d.getUuid());
+                Log.d(TAG, indent + "          permissions: "
+                      + String.format("0x%02X", d.getPermissions()));
+            }
+        }
+
+        if (service.getIncludedServices() != null) {
+            Log.d(TAG, indent + "  [included services]");
+            for (BluetoothGattService s : service.getIncludedServices()) {
+                dumpService(s, level + 1);
+            }
+        }
+    }
+}
+
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocServerTestBaseActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocServerTestBaseActivity.java
new file mode 100644
index 0000000..17d1370
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocServerTestBaseActivity.java
@@ -0,0 +1,238 @@
+/*
+ * Copyright 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.verifier.bluetooth;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.util.Log;
+import android.widget.ListView;
+import android.widget.Toast;
+
+public class BleCocServerTestBaseActivity extends PassFailButtons.Activity {
+
+    public static final boolean DEBUG = true;
+    public static final String TAG = "BleCocServerTestBaseActivity";
+
+    private final int TEST_BLE_LE_CONNECTED = 0;
+    private final int TEST_BLE_LISTENER_CREATED = 1;
+    private final int TEST_BLE_PSM_READ = 2;
+    private final int TEST_BLE_COC_CONNECTED = 3;
+    private final int TEST_BLE_CONNECTION_TYPE_CHECKED = 4;
+    private final int TEST_BLE_DATA_8BYTES_READ = 5;
+    private final int TEST_BLE_DATA_8BYTES_SENT = 6;
+    private final int TEST_BLE_DATA_EXCHANGED = 7;
+    private final int TEST_BLE_SERVER_DISCONNECTED = 8;
+    private static final int PASS_FLAG_ALL = 0x01FF;
+
+    private TestAdapter mTestAdapter;
+    private long mPassed;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.ble_server_start);
+        setPassFailButtonClickListeners();
+        setInfoResources(R.string.ble_coc_server_start_name,
+                         R.string.ble_server_start_info, -1);
+        getPassButton().setEnabled(false);
+
+        mTestAdapter = new TestAdapter(this, setupTestList());
+        ListView listView = (ListView) findViewById(R.id.ble_server_tests);
+        listView.setAdapter(mTestAdapter);
+
+        mPassed = 0;
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+
+        IntentFilter filter = new IntentFilter();
+
+        filter.addAction(BleCocServerService.BLE_LE_CONNECTED);
+        filter.addAction(BleCocServerService.BLE_COC_LISTENER_CREATED);
+        filter.addAction(BleCocServerService.BLE_PSM_READ);
+        filter.addAction(BleCocServerService.BLE_COC_CONNECTED);
+        filter.addAction(BleCocServerService.BLE_CONNECTION_TYPE_CHECKED);
+        filter.addAction(BleCocServerService.BLE_DATA_8BYTES_READ);
+        filter.addAction(BleCocServerService.BLE_DATA_8BYTES_SENT);
+        filter.addAction(BleCocServerService.BLE_DATA_LARGEBUF_READ);
+
+        filter.addAction(BleCocServerService.BLE_BLUETOOTH_MISMATCH_SECURE);
+        filter.addAction(BleCocServerService.BLE_BLUETOOTH_MISMATCH_INSECURE);
+        filter.addAction(BleCocServerService.BLE_SERVER_DISCONNECTED);
+
+        filter.addAction(BleCocServerService.BLE_BLUETOOTH_DISABLED);
+        filter.addAction(BleCocServerService.BLE_OPEN_FAIL);
+        filter.addAction(BleCocServerService.BLE_ADVERTISE_UNSUPPORTED);
+        filter.addAction(BleCocServerService.BLE_ADD_SERVICE_FAIL);
+
+        registerReceiver(mBroadcast, filter);
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        unregisterReceiver(mBroadcast);
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+    }
+
+    private List<Integer> setupTestList() {
+        ArrayList<Integer> testList = new ArrayList<Integer>();
+        testList.add(R.string.ble_coc_server_le_connect);
+        testList.add(R.string.ble_coc_server_create_listener);
+        testList.add(R.string.ble_coc_server_psm_read);
+        testList.add(R.string.ble_coc_server_connection);
+        testList.add(R.string.ble_coc_server_check_connection_type);
+        testList.add(R.string.ble_coc_server_receive_data_8bytes);
+        testList.add(R.string.ble_coc_server_send_data_8bytes);
+        testList.add(R.string.ble_coc_server_data_exchange);
+        testList.add(R.string.ble_server_receiving_disconnect);
+        return testList;
+    }
+
+    private void showErrorDialog(int titleId, int messageId, boolean finish) {
+        AlertDialog.Builder builder = new AlertDialog.Builder(this)
+                .setTitle(titleId)
+                .setMessage(messageId);
+        if (finish) {
+            builder.setOnCancelListener(new Dialog.OnCancelListener() {
+                @Override
+                public void onCancel(DialogInterface dialog) {
+                    finish();
+                }
+            });
+        }
+        builder.create().show();
+    }
+
+    private BroadcastReceiver mBroadcast = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            String action = intent.getAction();
+            if (DEBUG) {
+                Log.d(TAG, "BroadcastReceiver.onReceive: action=" + action);
+            }
+            String newAction = null;
+            final Intent startIntent = new Intent(BleCocServerTestBaseActivity.this, BleCocServerService.class);
+
+            switch (action) {
+            case BleCocServerService.BLE_BLUETOOTH_DISABLED:
+                showErrorDialog(R.string.ble_bluetooth_disable_title, R.string.ble_bluetooth_disable_message, true);
+                break;
+            case BleCocServerService.BLE_LE_CONNECTED:
+                mTestAdapter.setTestPass(TEST_BLE_LE_CONNECTED);
+                mPassed |= (1 << TEST_BLE_LE_CONNECTED);
+                break;
+            case BleCocServerService.BLE_COC_LISTENER_CREATED:
+                mTestAdapter.setTestPass(TEST_BLE_LISTENER_CREATED);
+                mPassed |= (1 << TEST_BLE_LISTENER_CREATED);
+                break;
+            case BleCocServerService.BLE_PSM_READ:
+                mTestAdapter.setTestPass(TEST_BLE_PSM_READ);
+                mPassed |= (1 << TEST_BLE_PSM_READ);
+                break;
+            case BleCocServerService.BLE_COC_CONNECTED:
+                mTestAdapter.setTestPass(TEST_BLE_COC_CONNECTED);
+                mPassed |= (1 << TEST_BLE_COC_CONNECTED);
+                break;
+            case BleCocServerService.BLE_CONNECTION_TYPE_CHECKED:
+                mTestAdapter.setTestPass(TEST_BLE_CONNECTION_TYPE_CHECKED);
+                mPassed |= (1 << TEST_BLE_CONNECTION_TYPE_CHECKED);
+                break;
+            case BleCocServerService.BLE_DATA_8BYTES_READ:
+                mTestAdapter.setTestPass(TEST_BLE_DATA_8BYTES_READ);
+                mPassed |= (1 << TEST_BLE_DATA_8BYTES_READ);
+                // send the next action to send 8 bytes
+                newAction = BleCocServerService.BLE_COC_SERVER_ACTION_SEND_DATA_8BYTES;
+                break;
+            case BleCocServerService.BLE_DATA_8BYTES_SENT:
+                mTestAdapter.setTestPass(TEST_BLE_DATA_8BYTES_SENT);
+                mPassed |= (1 << TEST_BLE_DATA_8BYTES_SENT);
+                // send the next action to send 8 bytes
+                newAction = BleCocServerService.BLE_COC_SERVER_ACTION_EXCHANGE_DATA;
+                break;
+            case BleCocServerService.BLE_DATA_LARGEBUF_READ:
+                mTestAdapter.setTestPass(TEST_BLE_DATA_EXCHANGED);
+                mPassed |= (1 << TEST_BLE_DATA_EXCHANGED);
+                // Disconnect
+                newAction = BleCocServerService.BLE_COC_SERVER_ACTION_DISCONNECT;
+                break;
+            case BleCocServerService.BLE_SERVER_DISCONNECTED:
+                mTestAdapter.setTestPass(TEST_BLE_SERVER_DISCONNECTED);
+                mPassed |= (1 << TEST_BLE_SERVER_DISCONNECTED);
+                // all tests done
+                break;
+            case BleCocServerService.BLE_BLUETOOTH_MISMATCH_SECURE:
+                showErrorDialog(R.string.ble_bluetooth_mismatch_title, R.string.ble_bluetooth_mismatch_secure_message, true);
+                break;
+            case BleCocServerService.BLE_BLUETOOTH_MISMATCH_INSECURE:
+                showErrorDialog(R.string.ble_bluetooth_mismatch_title, R.string.ble_bluetooth_mismatch_insecure_message, true);
+                break;
+            case BleCocServerService.BLE_ADVERTISE_UNSUPPORTED:
+                showErrorDialog(R.string.bt_advertise_unsupported_title, R.string.bt_advertise_unsupported_message, true);
+                break;
+            case BleCocServerService.BLE_OPEN_FAIL:
+                setTestResultAndFinish(false);
+                runOnUiThread(new Runnable() {
+                    @Override
+                    public void run() {
+                        Toast.makeText(BleCocServerTestBaseActivity.this, R.string.bt_open_failed_message, Toast.LENGTH_SHORT).show();
+                    }
+                });
+                break;
+            case BleCocServerService.BLE_ADD_SERVICE_FAIL:
+                showErrorDialog(R.string.bt_add_service_failed_title, R.string.bt_add_service_failed_message, true);
+                break;
+            default:
+                if (DEBUG) {
+                    Log.d(TAG, "Note: BroadcastReceiver.onReceive: unhandled action=" + action);
+                }
+            }
+
+            mTestAdapter.notifyDataSetChanged();
+
+            if (newAction != null) {
+                Log.d(TAG, "Starting " + newAction);
+                startIntent.setAction(newAction);
+
+                startService(startIntent);
+            }
+
+            if (mPassed == PASS_FLAG_ALL) {
+                Log.d(TAG, "All Tests Passed.");
+                getPassButton().setEnabled(true);
+            }
+        }
+    };
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
index 6eb587f..f2be547 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothChatService.java
@@ -73,6 +73,9 @@
     private ConnectThread mConnectThread;
     private ConnectedThread mConnectedThread;
     private int mState;
+    private boolean mBleTransport;
+    private int mLePsm;
+    private int mSocketConnectionType = -1;
 
     // Constants that indicate the current connection state
     public static final int STATE_NONE = 0;       // we're doing nothing
@@ -90,6 +93,22 @@
         mState = STATE_NONE;
         mHandler = handler;
         mUuid = uuid;
+        mBleTransport = false;
+    }
+
+    /**
+     * Constructor. Prepares a new BluetoothChat session.
+     * @param context  The UI Activity Context
+     * @param handler  A Handler to send messages back to the UI Activity
+     * @param useBle   A flag to use the BLE transport
+     */
+    public BluetoothChatService(Context context, Handler handler, boolean useBle) {
+        mAdapter = BluetoothAdapter.getDefaultAdapter();
+        mState = STATE_NONE;
+        mHandler = handler;
+        mUuid = null;
+        mBleTransport = useBle;
+        if (D) Log.d(TAG, "Construct BluetoothChatService: useBle=" + useBle);
     }
 
     /**
@@ -136,12 +155,47 @@
     }
 
     /**
+     * Return the assigned PSM value.
+     */
+    public synchronized int getPsm(boolean secure) {
+        if (secure && mSecureAcceptThread != null) {
+            return mSecureAcceptThread.getPsm();
+        }
+        else if (!secure && mInsecureAcceptThread != null) {
+            return mInsecureAcceptThread.getPsm();
+        }
+        Log.e(TAG, "getPsm: Invalid PSM value");
+        return 0;
+    }
+
+    /**
+     * Return the socket Connection Type.
+     */
+    public synchronized int getSocketConnectionType() {
+        return mSocketConnectionType;
+    }
+
+    /**
      * Start the ConnectThread to initiate a connection to a remote device.
-     * @param device  The BluetoothDevice to connect
+     * @param device  The BluetoothDevice to connect to
      * @param secure Socket Security type - Secure (true) , Insecure (false)
      */
     public synchronized void connect(BluetoothDevice device, boolean secure) {
-        if (D) Log.d(TAG, "connect to: " + device);
+        if (!mBleTransport) {
+            connect(device, secure, 0);
+        } else {
+            Log.e(TAG, "connect: Error: LE cannot call this method!");
+        }
+    }
+
+    /**
+     * Start the ConnectThread to initiate a connection to a remote device.
+     * @param device  The BluetoothDevice to connect to
+     * @param secure Socket Security type - Secure (true) , Insecure (false)
+     * @param psm Assigned PSM value
+     */
+    public synchronized void connect(BluetoothDevice device, boolean secure, int psm) {
+        if (D) Log.d(TAG, "connect to: " + device + ", psm: " + psm + ", ble: " + mBleTransport);
 
         // Cancel any thread attempting to make a connection
         if (mState == STATE_CONNECTING) {
@@ -152,7 +206,7 @@
         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
 
         // Start the thread to connect with the given device
-        mConnectThread = new ConnectThread(device, secure);
+        mConnectThread = new ConnectThread(device, secure, psm);
         mConnectThread.start();
         setState(STATE_CONNECTING);
     }
@@ -281,15 +335,31 @@
 
             // Create a new listening server socket
             try {
-                if (secure) {
-                    tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, mUuid);
+                if (mBleTransport) {
+                    if (secure) {
+                        tmp = mAdapter.listenUsingL2capChannel();
+                    } else {
+                        tmp = mAdapter.listenUsingInsecureL2capChannel();
+                    }
                 } else {
-                    tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, mUuid);
+                    if (secure) {
+                        tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, mUuid);
+                    } else {
+                        tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, mUuid);
+                    }
                 }
             } catch (IOException e) {
-                Log.e(TAG, "Socket Type: " + mSocketType + " listen() failed", e);
+                Log.e(TAG, "Socket Type: " + mSocketType + ", le: " + mBleTransport + " listen() failed", e);
             }
             mmServerSocket = tmp;
+            if (mBleTransport) {
+                // Get the assigned PSM value
+                mLePsm = mmServerSocket.getPsm();
+            }
+        }
+
+        public int getPsm() {
+            return mLePsm;
         }
 
         public void run() {
@@ -317,6 +387,7 @@
                         case STATE_LISTEN:
                         case STATE_CONNECTING:
                             // Situation normal. Start the connected thread.
+                            mSocketConnectionType = socket.getConnectionType();
                             connected(socket, socket.getRemoteDevice(),
                                     mSocketType);
                             break;
@@ -335,8 +406,10 @@
                     Log.i(TAG, "Got null socket");
                 }
             }
-            if (D) Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);
-
+            if (D) {
+                Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType
+                         + ", SocketConnectionType: " + mSocketConnectionType);
+            }
         }
 
         public void cancel() {
@@ -361,26 +434,50 @@
         private String mSocketType;
 
         public ConnectThread(BluetoothDevice device, boolean secure) {
+            if (mBleTransport) {
+                Log.e(TAG, "ConnectThread: Error: LE should not call this constructor");
+            }
             mmDevice = device;
+            mmSocket = connectThreadCommon(device, secure, 0);
+        }
+
+        public ConnectThread(BluetoothDevice device, boolean secure, int psm) {
+            mmDevice = device;
+            mmSocket = connectThreadCommon(device, secure, psm);
+        }
+
+        private BluetoothSocket connectThreadCommon(BluetoothDevice device, boolean secure, int psm) {
             BluetoothSocket tmp = null;
             mSocketType = secure ? "Secure" : "Insecure";
 
             // Get a BluetoothSocket for a connection with the
             // given BluetoothDevice
             try {
-                if (secure) {
-                    tmp = device.createRfcommSocketToServiceRecord(mUuid);
+                if (mBleTransport) {
+                    if (secure) {
+                        tmp = device.createL2capChannel(psm);
+                    } else {
+                        tmp = device.createInsecureL2capChannel(psm);
+                    }
                 } else {
-                    tmp = device.createInsecureRfcommSocketToServiceRecord(mUuid);
+                    if (secure) {
+                        tmp = device.createRfcommSocketToServiceRecord(mUuid);
+                    } else {
+                        tmp = device.createInsecureRfcommSocketToServiceRecord(mUuid);
+                    }
                 }
             } catch (IOException e) {
                 Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
             }
-            mmSocket = tmp;
+
+            mSocketConnectionType = tmp.getConnectionType();
+
+            return tmp;
         }
 
         public void run() {
-            Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
+            Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType
+                  + ", mSocketConnectionType: " + mSocketConnectionType);
             setName("ConnectThread" + mSocketType);
 
             // Always cancel discovery because it will slow down a connection
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothTestActivity.java
index 3477870..5c0c55e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BluetoothTestActivity.java
@@ -24,6 +24,7 @@
 import com.android.cts.verifier.PassFailButtons;
 import com.android.cts.verifier.R;
 
+
 import java.util.ArrayList;
 import java.util.List;
 
@@ -68,6 +69,10 @@
                   "com.android.cts.verifier.bluetooth.BleScannerTestActivity");
             disabledTestArray.add(
                   "com.android.cts.verifier.bluetooth.BleConnectionPriorityServerBaseActivity");
+            disabledTestArray.add(
+                  "com.android.cts.verifier.bluetooth.BleInsecureServerTestListActivity");
+            disabledTestArray.add(
+                  "com.android.cts.verifier.bluetooth.BleSecureServerTestListActivity");
         }
         setTestListAdapter(new ManifestTestListAdapter(this, getClass().getName(),
                 disabledTestArray.toArray(new String[disabledTestArray.size()])));
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
index b042fed..b627797 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/fov/PhotoCaptureActivity.java
@@ -439,7 +439,7 @@
         try {
             mCamera.setPreviewDisplay(mSurfaceHolder);
         } catch (Throwable t) {
-            Log.e("TAG", "Could not set preview display", t);
+            Log.e(TAG, "Could not set preview display", t);
             Toast.makeText(this, t.getMessage(), Toast.LENGTH_LONG).show();
             return;
         }
@@ -449,8 +449,14 @@
 
         // Either use chosen preview size for current camera or automatically
         // choose preview size based on view dimensions.
-        Size selectedPreviewSize = (mPreviewSizes != null) ? mPreviewSizes[mSelectedResolution.cameraId] :
-            getBestPreviewSize(mSurfaceSize.width, mSurfaceSize.height, params);
+        Size selectedPreviewSize = null;
+        if (mPreviewSizes != null) {
+            selectedPreviewSize = mPreviewSizes[mSelectedResolution.cameraId];
+        } else if (mSurfaceSize != null) {
+            selectedPreviewSize = getBestPreviewSize(
+                    mSurfaceSize.width, mSurfaceSize.height, params);
+        }
+
         if (selectedPreviewSize != null) {
             params.setPreviewSize(selectedPreviewSize.width, selectedPreviewSize.height);
             mCamera.setParameters(params);
@@ -458,7 +464,10 @@
         }
 
         if (startPreviewAfterInit) {
-          startPreview();
+            if (selectedPreviewSize == null) {
+                Log.w(TAG, "Preview started without setting preview size");
+            }
+            startPreview();
         }
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
index 7fa4e1a..d6feb51 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
@@ -77,6 +77,7 @@
     private static final int MAX_SUMMARY_LEN = 200;
 
     private final ResultReceiver mResultsReceiver = new ResultReceiver();
+    private boolean mReceiverRegistered = false;
 
     // Initialized in onCreate
     ArrayList<String> mToBeTestedCameraIds = null;
@@ -401,13 +402,16 @@
             Log.d(TAG, "register ITS result receiver");
             IntentFilter filter = new IntentFilter(ACTION_ITS_RESULT);
             registerReceiver(mResultsReceiver, filter);
+            mReceiverRegistered = true;
         }
     }
 
     @Override
     public void onDestroy() {
         Log.d(TAG, "unregister ITS result receiver");
-        unregisterReceiver(mResultsReceiver);
+        if (mReceiverRegistered) {
+            unregisterReceiver(mResultsReceiver);
+        }
         super.onDestroy();
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/dialer/DialerImplementsTelecomIntentsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/dialer/DialerImplementsTelecomIntentsActivity.java
index bc5cdbc..a7f0a95 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/dialer/DialerImplementsTelecomIntentsActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/dialer/DialerImplementsTelecomIntentsActivity.java
@@ -17,12 +17,15 @@
 package com.android.cts.verifier.dialer;
 
 import android.content.Intent;
+import android.content.Context;
 import android.os.Bundle;
 import android.telecom.TelecomManager;
+import android.telephony.TelephonyManager;
 import android.view.View;
 import android.widget.Button;
 import android.widget.CheckBox;
 import android.widget.CompoundButton;
+
 import com.android.cts.verifier.PassFailButtons;
 import com.android.cts.verifier.R;
 
@@ -37,6 +40,7 @@
   private CheckBox mLaunchCallingAccountsSettingsCheckBox;
   private Button mLaunchAccessibilitySettingsButton;
   private CheckBox mLaunchAccessibilitySettingsCheckBox;
+  private TelephonyManager mTelephonyManager;
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
@@ -50,6 +54,8 @@
     setPassFailButtonClickListeners();
     getPassButton().setEnabled(false);
 
+    mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
+
     mLaunchCallSettingsCheckBox = findViewById(R.id.dialer_telecom_intents_call_settings_check_box);
     mLaunchShortSmsAnswerCheckBox = findViewById(R.id.dialer_telecom_intents_short_sms_check_box);
     mLaunchCallingAccountsSettingsCheckBox =
@@ -85,6 +91,11 @@
     mLaunchAccessibilitySettingsButton.setOnClickListener(
         (View unused) ->
             startActivity(new Intent(TelecomManager.ACTION_SHOW_CALL_ACCESSIBILITY_SETTINGS)));
+    if (!mTelephonyManager.isHearingAidCompatibilitySupported() && !mTelephonyManager.isTtyModeSupported()) {
+        mLaunchAccessibilitySettingsButton.setVisibility(View.INVISIBLE);
+        mLaunchAccessibilitySettingsCheckBox.setVisibility(View.INVISIBLE);
+        mLaunchAccessibilitySettingsCheckBox.setChecked(true);
+    }
   }
 
   private void onCheckedChangeListener() {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/base/EmergencyCallBaseTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/location/base/EmergencyCallBaseTestActivity.java
index 531b40b..e25f758 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/location/base/EmergencyCallBaseTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/location/base/EmergencyCallBaseTestActivity.java
@@ -57,11 +57,19 @@
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
+        // skip current test if device doesn't support cellular
+        if (!EmergencyCallUtil.isPhoneDevice(this)) {
+          String skipInfo = getResources().getString(R.string.emergency_call_skip_info);
+          TestResult.setPassedResult(this, super.getClass().getName(), skipInfo);
+          Toast toast = Toast.makeText(getApplicationContext(), skipInfo, Toast.LENGTH_LONG);
+          toast.show();
+          this.finish();
+          return;
+        }
         // override the test info
         mTextView.setText(R.string.location_emergency_call_test_info);
         EmergencyCallUtil.setDefaultDialer(this, this.getPackageName());
         setPassFailButtonClickListeners();
-
     }
 
     @Override
@@ -74,15 +82,7 @@
 
     @Override
     public void onClick(View target) {
-        // skip current test if device doesn't support cellular
-        if (!EmergencyCallUtil.isPhoneDevice(this)) {
-            String skipInfo = getResources().getString(R.string.emergency_call_skip_info);
-            TestResult.setPassedResult(this, super.getClass().getName(), skipInfo);
-            Toast toast = Toast.makeText(getApplicationContext(), skipInfo, Toast.LENGTH_LONG);
-            toast.show();
-            this.finish();
-            return;
-        }
+
         AlertDialog.Builder builder = new AlertDialog.Builder(this);
         final FrameLayout frameView = new FrameLayout(this);
         builder.setView(frameView);
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 9767530..5f90b66 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -53,6 +53,12 @@
  */
 public class ByodFlowTestActivity extends DialogTestListActivity {
 
+    // Action for delivering sub-test result from the profile.
+    public static final String ACTION_TEST_RESULT =
+            "com.android.cts.verifier.managedprovisioning.BYOD_TEST_RESULT";
+    // Extra for ACTION_TEST_RESULT containing test result.
+    public static final String EXTRA_RESULT = "extra-result";
+
     private static final String TAG = "ByodFlowTestActivity";
     private static ConnectivityManager mCm;
     private static final int REQUEST_MANAGED_PROVISIONING = 0;
@@ -151,10 +157,13 @@
 
     @Override
     protected void onNewIntent(Intent intent) {
-        // This is called when managed provisioning completes successfully without reboot.
         super.onNewIntent(intent);
         if (ByodHelperActivity.ACTION_PROFILE_OWNER_STATUS.equals(intent.getAction())) {
+            // This is called when managed provisioning completes successfully without reboot.
             handleStatusUpdate(RESULT_OK, intent);
+        } else if (ACTION_TEST_RESULT.equals(intent.getAction())) {
+            // Called when subtest cannot communicate test result from the profile via setResult().
+            handleLaunchTestResult(RESULT_OK, intent.getParcelableExtra(EXTRA_RESULT));
         }
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestHelper.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestHelper.java
index 485e4d8..24e0919 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestHelper.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestHelper.java
@@ -2,6 +2,7 @@
 
 import android.content.ComponentName;
 import android.content.Context;
+import android.content.Intent;
 import android.content.pm.PackageManager;
 
 public class ByodFlowTestHelper {
@@ -17,6 +18,23 @@
         setComponentsEnabledState(PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
     }
 
+    /** Reports result to ByodFlowTestActivity if it is impossible via normal setResult. */
+    public void sendResultToPrimary(Intent result) {
+        final Intent intent = new Intent(ByodFlowTestActivity.ACTION_TEST_RESULT);
+        intent.putExtra(ByodFlowTestActivity.EXTRA_RESULT, result);
+        startActivityInPrimary(intent);
+    }
+
+    public void startActivityInPrimary(Intent intent) {
+        // Disable app components in the current profile, so only the counterpart in the other
+        // profile can respond (via cross-profile intent filter)
+        mContext.getPackageManager().setComponentEnabledSetting(
+                new ComponentName(mContext, ByodFlowTestActivity.class),
+                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+                PackageManager.DONT_KILL_APP);
+        mContext.startActivity(intent);
+    }
+
     /**
      * Clean up things. This has to be working even it is called multiple times.
      */
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
index ab2f9d0..9bb9cf8 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
@@ -219,7 +219,7 @@
             // Jump back to CTS verifier with result.
             Intent response = new Intent(ACTION_PROFILE_OWNER_STATUS);
             response.putExtra(EXTRA_PROVISIONED, isProfileOwner());
-            startActivityInPrimary(response);
+            new ByodFlowTestHelper(this).startActivityInPrimary(response);
             // Queried by CtsVerifier in the primary side using startActivityForResult.
         } else if (action.equals(ACTION_QUERY_PROFILE_OWNER)) {
             Intent response = new Intent();
@@ -514,16 +514,6 @@
         }
     }
 
-    private void startActivityInPrimary(Intent intent) {
-        // Disable app components in the current profile, so only the counterpart in the other
-        // profile can respond (via cross-profile intent filter)
-        getPackageManager().setComponentEnabledSetting(new ComponentName(
-                this, ByodFlowTestActivity.class),
-                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
-                PackageManager.DONT_KILL_APP);
-        startActivity(intent);
-    }
-
     private void grantCameraPermissionToSelf() {
         mDevicePolicyManager.setPermissionGrantState(mAdminReceiverComponent, getPackageName(),
                 android.Manifest.permission.CAMERA,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
index d81c155..abad5b5 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
@@ -184,6 +184,7 @@
         filter = new IntentFilter();
         filter.addAction(ByodHelperActivity.ACTION_PROFILE_OWNER_STATUS);
         filter.addAction(ByodHelperActivity.ACTION_DISK_ENCRYPTION_STATUS);
+        filter.addAction(ByodFlowTestActivity.ACTION_TEST_RESULT);
         filter.addAction(CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_PERSONAL);
         filter.addAction(LocationListenerActivity.ACTION_SET_LOCATION_AND_CHECK_UPDATES);
         dpm.addCrossProfileIntentFilter(getWho(context), filter,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/RecentsRedactionActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/RecentsRedactionActivity.java
index d9b6fda..a49985d 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/RecentsRedactionActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/RecentsRedactionActivity.java
@@ -28,6 +28,7 @@
 import com.android.cts.verifier.ArrayTestListAdapter;
 import com.android.cts.verifier.DialogTestListActivity;
 import com.android.cts.verifier.R;
+import com.android.cts.verifier.TestResult;
 
 /**
  * This test verifies that if a work profile is locked with a separate password, Recents views for
@@ -52,10 +53,33 @@
                 /* instructions */ R.string.provisioning_byod_recents_instructions);
     }
 
+    // Default listener will use setResult(), which won't work due to activity being in a new task.
+    private View.OnClickListener clickListener = target -> {
+        final int resultCode;
+        switch (target.getId()) {
+            case R.id.pass_button:
+                resultCode = TestResult.TEST_RESULT_PASSED;
+                break;
+            case R.id.fail_button:
+                resultCode = TestResult.TEST_RESULT_FAILED;
+                break;
+            default:
+                throw new IllegalArgumentException("Unknown id: " + target.getId());
+        }
+        Intent resultIntent = TestResult.createResult(RecentsRedactionActivity.this, resultCode,
+                getTestId(), getTestDetails(), getReportLog());
+
+        new ByodFlowTestHelper(this).sendResultToPrimary(resultIntent);
+        finish();
+    };
+
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
+        findViewById(R.id.pass_button).setOnClickListener(clickListener);
+        findViewById(R.id.fail_button).setOnClickListener(clickListener);
+
         mPrepareTestButton.setText(R.string.provisioning_byod_recents_lock_now);
         mPrepareTestButton.setOnClickListener((View view) -> {
             mDevicePolicyManager.lockNow();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
index 1be781b..90f0dc3 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
@@ -181,8 +181,7 @@
                     UserManager.DISALLOW_CONFIG_DATE_TIME,
                     UserManager.DISALLOW_CONFIG_LOCATION,
                     UserManager.DISALLOW_CONFIG_SCREEN_TIMEOUT,
-                    UserManager.DISALLOW_CONFIG_BRIGHTNESS,
-                    UserManager.DISALLOW_AMBIENT_DISPLAY);
+                    UserManager.DISALLOW_CONFIG_BRIGHTNESS);
 
     public static String getRestrictionLabel(Context context, String restriction) {
         final UserRestrictionItem item = findRestrictionItem(restriction);
diff --git a/build/config.mk b/build/config.mk
index 159dc8d..2f0c7b5 100644
--- a/build/config.mk
+++ b/build/config.mk
@@ -24,4 +24,3 @@
 BUILD_CTS_TARGET_JAVA_LIBRARY := cts/build/test_target_java_library.mk
 BUILD_CTS_SUPPORT_PACKAGE := cts/build/support_package.mk
 BUILD_CTS_DEVICE_INFO_PACKAGE := cts/build/device_info_package.mk
-BUILD_CTS_TARGET_TESTNG_PACKAGE := cts/build/test_target_testng_package.mk
diff --git a/common/Android.mk b/common/Android.mk
deleted file mode 100644
index a8b6af7..0000000
--- a/common/Android.mk
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-include $(call all-subdir-makefiles)
diff --git a/common/device-side/Android.mk b/common/device-side/Android.mk
deleted file mode 100644
index a8b6af7..0000000
--- a/common/device-side/Android.mk
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-include $(call all-subdir-makefiles)
diff --git a/common/device-side/device-info/Android.bp b/common/device-side/device-info/Android.bp
new file mode 100644
index 0000000..583bc85
--- /dev/null
+++ b/common/device-side/device-info/Android.bp
@@ -0,0 +1,41 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "compatibility-device-info",
+
+    srcs: ["src/**/*.java"],
+
+    static_libs: [
+        "compatibility-device-util",
+        "android-support-test",
+        "junit",
+    ],
+
+    libs: [
+        "android.test.base.stubs",
+        "framework-stub-for-compatibility-device-info",
+    ],
+
+    sdk_version: "test_current",
+}
+
+java_library {
+    // This stub library provides some internal APIs (SystemProperties, VintfObject, etc.)
+    // to compatibility-device-info library.
+    name: "framework-stub-for-compatibility-device-info",
+    srcs: ["src_stub/**/*.java"],
+
+    sdk_version: "current",
+}
diff --git a/common/device-side/device-info/Android.mk b/common/device-side/device-info/Android.mk
deleted file mode 100644
index df95d9a..0000000
--- a/common/device-side/device-info/Android.mk
+++ /dev/null
@@ -1,48 +0,0 @@
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util \
-    android-support-test \
-    junit
-
-LOCAL_JAVA_LIBRARIES := \
-    android.test.base.stubs \
-    framework-stub-for-compatibility-device-info
-
-LOCAL_MODULE := compatibility-device-info
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-include $(CLEAR_VARS)
-# This stub library provides some internal APIs (SystemProperties, VintfObject, etc.)
-# to compatibility-device-info library.
-LOCAL_MODULE := framework-stub-for-compatibility-device-info
-LOCAL_SRC_FILES := $(call all-java-files-under, src_stub)
-LOCAL_MODULE_TAGS := optional
-LOCAL_SDK_VERSION := current
-LOCAL_UNINSTALLABLE_MODULE := true
-include $(BUILD_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/common/device-side/device-info/tests/Android.bp b/common/device-side/device-info/tests/Android.bp
new file mode 100644
index 0000000..10f42da
--- /dev/null
+++ b/common/device-side/device-info/tests/Android.bp
@@ -0,0 +1,31 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_test {
+    name: "compatibility-device-info-tests",
+
+    srcs: ["src/**/*.java"],
+
+    static_libs: [
+        "compatibility-device-info",
+        "junit",
+    ],
+
+    libs: [
+        "android.test.runner.stubs",
+        "android.test.base.stubs",
+    ],
+
+    sdk_version: "test_current",
+}
diff --git a/common/device-side/device-info/tests/Android.mk b/common/device-side/device-info/tests/Android.mk
deleted file mode 100644
index cd057962..0000000
--- a/common/device-side/device-info/tests/Android.mk
+++ /dev/null
@@ -1,31 +0,0 @@
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-info junit
-
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE := compatibility-device-info-tests
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/common/device-side/nativetesthelper/Android.bp b/common/device-side/nativetesthelper/Android.bp
new file mode 100644
index 0000000..216fb33
--- /dev/null
+++ b/common/device-side/nativetesthelper/Android.bp
@@ -0,0 +1,21 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "nativetesthelper",
+
+    srcs: ["src/**/*.java"],
+    static_libs: ["compatibility-common-util-devicesidelib"],
+    sdk_version: "current",
+}
diff --git a/common/device-side/nativetesthelper/Android.mk b/common/device-side/nativetesthelper/Android.mk
deleted file mode 100644
index 63b81e1..0000000
--- a/common/device-side/nativetesthelper/Android.mk
+++ /dev/null
@@ -1,26 +0,0 @@
-# Copyright (C) 2017 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-common-util-devicesidelib
-LOCAL_MODULE := nativetesthelper
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/common/device-side/nativetesthelper/jni/Android.bp b/common/device-side/nativetesthelper/jni/Android.bp
new file mode 100644
index 0000000..91eb0ac
--- /dev/null
+++ b/common/device-side/nativetesthelper/jni/Android.bp
@@ -0,0 +1,32 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//
+// This is the shared library included by the JNI test app.
+//
+
+cc_library_static {
+    name: "libnativetesthelper_jni",
+
+    srcs: ["gtest_wrapper.cpp"],
+
+    shared_libs: ["libnativehelper_compat_libc++"],
+    whole_static_libs: ["libgtest_ndk_c++"],
+    sdk_version: "current",
+    stl: "c++_static",
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+}
diff --git a/common/device-side/nativetesthelper/jni/Android.mk b/common/device-side/nativetesthelper/jni/Android.mk
deleted file mode 100644
index f970e8c..0000000
--- a/common/device-side/nativetesthelper/jni/Android.mk
+++ /dev/null
@@ -1,36 +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.
-
-#
-# This is the shared library included by the JNI test app.
-#
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libnativetesthelper_jni
-
-LOCAL_SRC_FILES := \
-        gtest_wrapper.cpp
-
-LOCAL_SHARED_LIBRARIES := libnativehelper_compat_libc++
-LOCAL_WHOLE_STATIC_LIBRARIES := libgtest_ndk_c++
-LOCAL_EXPORT_STATIC_LIBRARY_HEADERS := libgtest_ndk_c++
-LOCAL_SDK_VERSION := current
-LOCAL_NDK_STL_VARIANT := c++_static
-LOCAL_CFLAGS := -Wall -Werror
-LOCAL_MULTILIB := both
-
-include $(BUILD_STATIC_LIBRARY)
diff --git a/common/device-side/preconditions/Android.bp b/common/device-side/preconditions/Android.bp
new file mode 100644
index 0000000..64f0ab0
--- /dev/null
+++ b/common/device-side/preconditions/Android.bp
@@ -0,0 +1,23 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "compatibility-device-preconditions",
+
+    srcs: ["src/**/*.java"],
+
+    static_libs: ["compatibility-common-util-devicesidelib"],
+
+    sdk_version: "current",
+}
diff --git a/common/device-side/preconditions/Android.mk b/common/device-side/preconditions/Android.mk
deleted file mode 100644
index 75c981b..0000000
--- a/common/device-side/preconditions/Android.mk
+++ /dev/null
@@ -1,31 +0,0 @@
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-common-util-devicesidelib
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE := compatibility-device-preconditions
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/common/device-side/test-app/Android.bp b/common/device-side/test-app/Android.bp
new file mode 100644
index 0000000..a4e39e9
--- /dev/null
+++ b/common/device-side/test-app/Android.bp
@@ -0,0 +1,38 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Build an APK which contains the device-side libraries and their tests,
+// this then gets instrumented in order to test the aforementioned libraries.
+
+android_test {
+    name: "CompatibilityTestApp",
+
+    dex_preopt: {
+        enabled: false,
+    },
+    optimize: {
+        enabled: false,
+    },
+
+    static_libs: [
+        "android-support-test",
+        "compatibility-common-util-devicesidelib",
+        "compatibility-device-info-tests",
+        "compatibility-device-info",
+        "compatibility-device-util-tests",
+        "compatibility-device-util",
+    ],
+
+    sdk_version: "test_current",
+}
diff --git a/common/device-side/test-app/Android.mk b/common/device-side/test-app/Android.mk
deleted file mode 100755
index 6adce97..0000000
--- a/common/device-side/test-app/Android.mk
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Build an APK which contains the device-side libraries and their tests,
-# this then gets instrumented in order to test the aforementioned libraries.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_DEX_PREOPT := false
-LOCAL_PROGUARD_ENABLED := disabled
-# don't include this package in any target
-LOCAL_MODULE_TAGS := optional
-# and when built explicitly put it in the data partition
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-test\
-    compatibility-common-util-devicesidelib\
-    compatibility-device-info-tests\
-    compatibility-device-info\
-    compatibility-device-util-tests\
-    compatibility-device-util
-
-LOCAL_PACKAGE_NAME := CompatibilityTestApp
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_PACKAGE)
diff --git a/common/device-side/util/Android.mk b/common/device-side/util/Android.mk
deleted file mode 100644
index a8b6af7..0000000
--- a/common/device-side/util/Android.mk
+++ /dev/null
@@ -1,15 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-include $(call all-subdir-makefiles)
diff --git a/common/device-side/util/tests/Android.bp b/common/device-side/util/tests/Android.bp
new file mode 100644
index 0000000..e38f0f4
--- /dev/null
+++ b/common/device-side/util/tests/Android.bp
@@ -0,0 +1,26 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_test {
+    name: "compatibility-device-util-tests",
+
+    srcs: ["src/**/*.java"],
+
+    static_libs: [
+        "compatibility-device-util",
+        "junit",
+    ],
+
+    sdk_version: "test_current",
+}
diff --git a/common/device-side/util/tests/Android.mk b/common/device-side/util/tests/Android.mk
deleted file mode 100644
index a073b9a..0000000
--- a/common/device-side/util/tests/Android.mk
+++ /dev/null
@@ -1,29 +0,0 @@
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util junit
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE := compatibility-device-util-tests
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/error_prone_rules.mk b/error_prone_rules.mk
index 7e900e6..4e33114 100644
--- a/error_prone_rules.mk
+++ b/error_prone_rules.mk
@@ -1,3 +1,4 @@
+
 # Copyright (C) 2017 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -13,6 +14,7 @@
 # limitations under the License.
 
 # Set of error prone rules to ensure code quality
+# When updating this list, also update cts_error_prone_rules in Android.bp
 LOCAL_ERROR_PRONE_FLAGS += -Xep:ArrayToString:ERROR \
                            -Xep:BoxedPrimitiveConstructor:ERROR \
                            -Xep:ConstantField:ERROR \
diff --git a/error_prone_rules_tests.mk b/error_prone_rules_tests.mk
index 92c8966..d581a6d 100644
--- a/error_prone_rules_tests.mk
+++ b/error_prone_rules_tests.mk
@@ -13,6 +13,7 @@
 # limitations under the License.
 
 # Set of error prone rules to ensure code quality of tests
+# When updating this list, also update cts_error_prone_rules_tests in Android.bp
 
 # Goal is to eventually merge with error_prone_rules.mk
 LOCAL_ERROR_PRONE_FLAGS += -Xep:ArrayToString:ERROR \
diff --git a/hostsidetests/api/Android.mk b/hostsidetests/api/Android.mk
index 63cb700..d57a0b9 100644
--- a/hostsidetests/api/Android.mk
+++ b/hostsidetests/api/Android.mk
@@ -18,25 +18,53 @@
 
 LOCAL_MODULE := CtsUnofficialApisUsageTestCases
 LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 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 \
+LOCAL_STATIC_JAVA_LIBRARIES := dexlib2 doclava jsilver guava 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_files := $(addprefix frameworks/base/,\
+  api/current.txt:current.txt \
+  api/system-current.txt:system-current.txt \
+  test-base/api/current.txt:android-test-base-current.txt \
+  test-runner/api/current.txt:android-test-runner-current.txt \
+  test-mock/api/current.txt:android-test-mock-current.txt)
+
+define define-api-files
+  $(eval tw := $(subst :, ,$(strip $(1)))) \
+  $(eval $(call copy-one-file,$(word 1,$(tw)),$(2)/$(word 2,$(tw)))) \
+  $(eval LOCAL_JAVA_RESOURCE_FILES += $(2)/$(word 2,$(tw)))
+endef
+
+dest := $(call intermediates-dir-for,JAVA_LIBRARIES,$(LOCAL_MODULE),true,COMMON)
+
+$(foreach f,$(api_files),\
+  $(call define-api-files,$(f),$(dest)))
+
+api_files :=
+dest :=
 
 # API 27 is added since some support libraries are using old APIs
 LOCAL_JAVA_RESOURCE_FILES += prebuilts/sdk/27/public/api/android.txt
 
+# org.apache.http.legacy is considered as approved APIs
+LOCAL_JAVA_RESOURCE_FILES += \
+    $(call local-intermediates-dir)/org-apache-http-legacy-current.txt \
+    $(call local-intermediates-dir)/org-apache-http-legacy-system-current.txt
+
+$(call local-intermediates-dir)/org-apache-http-legacy-current.txt\
+: external/apache-http/api/current.txt
+	cp $< $@
+
+$(call local-intermediates-dir)/org-apache-http-legacy-system-current.txt\
+: external/apache-http/api/system-current.txt
+	cp $< $@
+
 include $(BUILD_HOST_JAVA_LIBRARY)
 
 include $(CLEAR_VARS)
diff --git a/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java b/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java
index 443d02b..84fc73c 100644
--- a/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java
+++ b/hostsidetests/api/src/com/android/cts/api/UnofficialApisUsageTest.java
@@ -179,7 +179,9 @@
             "/android-test-base-current.txt",
             "/android-test-runner-current.txt",
             "/android-test-mock-current.txt",
-            "/android.txt"
+            "/android.txt",
+            "/org-apache-http-legacy-current.txt",
+            "/org-apache-http-legacy-system-current.txt"
         }).map(name -> new File(name));
 
         approvedApis = new ApprovedApis(apiFiles);
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/ApplicationVisibilityTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/ApplicationVisibilityTest.java
index 08d965c..aac5bd1 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/ApplicationVisibilityTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/ApplicationVisibilityTest.java
@@ -47,7 +47,7 @@
 
     @Before
     public void setUpPackage() throws Exception {
-        mUsers = Utils.prepareMultipleUsers(getDevice(), 3);
+        mUsers = Utils.prepareMultipleUsers(getDevice(), 2);
         mOldVerifierValue =
                 getDevice().executeShellCommand("settings get global package_verifier_enable");
         getDevice().executeShellCommand("settings put global package_verifier_enable 0");
@@ -68,8 +68,8 @@
             return;
         }
 
-        final int installUserId = mUsers[1];
-        final int testUserId = mUsers[2];
+        final int installUserId = getInstallUserId();
+        final int testUserId = getTestUserId();
 
         installTestAppForUser(TINY_APK, installUserId);
         installTestAppForUser(TEST_WITH_PERMISSION_APK, testUserId);
@@ -99,8 +99,8 @@
             return;
         }
 
-        final int installUserId = mUsers[1];
-        final int testUserId = mUsers[2];
+        final int installUserId = getInstallUserId();
+        final int testUserId = getTestUserId();
 
         installTestAppForUser(TINY_APK, installUserId);
         installTestAppForUser(TEST_WITH_PERMISSION_APK, testUserId);
@@ -126,8 +126,8 @@
             return;
         }
 
-        final int installUserId = mUsers[1];
-        final int testUserId = mUsers[2];
+        final int installUserId = getInstallUserId();
+        final int testUserId = getTestUserId();
         final Map<String, String> testArgs = new HashMap<>();
         testArgs.put("testUser", Integer.toString(installUserId));
 
@@ -154,8 +154,8 @@
             return;
         }
 
-        final int installUserId = mUsers[1];
-        final int testUserId = mUsers[2];
+        final int installUserId = getInstallUserId();
+        final int testUserId = getTestUserId();
         final Map<String, String> testArgs = new HashMap<>();
         testArgs.put("testUser", Integer.toString(installUserId));
 
@@ -178,8 +178,8 @@
             return;
         }
 
-        final int installUserId = mUsers[1];
-        final int testUserId = mUsers[2];
+        final int installUserId = getInstallUserId();
+        final int testUserId = getTestUserId();
 
         installTestAppForUser(TINY_APK, installUserId);
         installTestAppForUser(TEST_WITH_PERMISSION_APK, testUserId);
@@ -209,8 +209,8 @@
             return;
         }
 
-        final int installUserId = mUsers[1];
-        final int testUserId = mUsers[2];
+        final int installUserId = getInstallUserId();
+        final int testUserId = getTestUserId();
 
         installTestAppForUser(TINY_APK, installUserId);
         installTestAppForUser(TEST_WITH_PERMISSION_APK, testUserId);
@@ -236,8 +236,8 @@
             return;
         }
 
-        final int installUserId = mUsers[1];
-        final int testUserId = mUsers[2];
+        final int installUserId = getInstallUserId();
+        final int testUserId = getTestUserId();
         final Map<String, String> testArgs = new HashMap<>();
         testArgs.put("testUser", Integer.toString(installUserId));
 
@@ -264,8 +264,8 @@
             return;
         }
 
-        final int installUserId = mUsers[1];
-        final int testUserId = mUsers[2];
+        final int installUserId = getInstallUserId();
+        final int testUserId = getTestUserId();
         final Map<String, String> testArgs = new HashMap<>();
         testArgs.put("testUser", Integer.toString(installUserId));
 
@@ -280,4 +280,12 @@
                 testUserId,
                 testArgs);
     }
+
+    private int getInstallUserId() {
+        return mUsers[0];
+    }
+
+    private int getTestUserId() {
+        return mUsers[1];
+    }
 }
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTestCase.java b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTestCase.java
index 7038685..d2eea34 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTestCase.java
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTestCase.java
@@ -152,6 +152,11 @@
         return true;
     }
 
+    protected boolean isTelevision() {
+        final PackageManager pm = getInstrumentation().getContext().getPackageManager();
+        return pm.hasSystemFeature("android.hardware.type.television");
+    }
+
     protected void assertActivityFailed() {
         final Result result = mActivity.getResult();
         assertEquals(REQUEST_CODE, result.requestCode);
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/ScopedDirectoryAccessClientTest.java b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/ScopedDirectoryAccessClientTest.java
index 466dabf..135a0f7 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/ScopedDirectoryAccessClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/ScopedDirectoryAccessClientTest.java
@@ -32,6 +32,7 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.net.Uri;
 import android.os.storage.StorageManager;
 import android.os.storage.StorageVolume;
@@ -352,17 +353,18 @@
         final boolean gotIt = mDevice.wait(Until.hasObject(By.text(dir)), TIMEOUT);
         assertTrue("object with text'(" + dir + "') not visible yet", gotIt);
         // TODO: find a better way to get the toggle rather then getting all
-        final List<UiObject2> toggles = mDevice.findObjects(By.res("android:id/switch_widget"));
-        assertEquals("should have just one toggle: " + toggles, 1, toggles.size());
-        final UiObject2 toggle = toggles.get(0);
+        UiObject2 toggle = getUniqueToggle();
         assertFalse("toggle for '" + dir + "' should not be checked", toggle.isChecked());
         toggle.click();
+        toggle = getUniqueToggle();
         assertTrue("toggle for '" + dir + "' should be checked", toggle.isChecked());
 
         // Close app screen.
         mDevice.pressBack();
-        // Close main screen.
-        mDevice.pressBack();
+        if (!isTelevision()) {
+            // Close main screen.
+            mDevice.pressBack();
+        }
 
         // Finally, make sure it's reset by requesting it again.
         sendOpenExternalDirectoryIntent(volume, dir);
@@ -392,23 +394,30 @@
         final boolean gotIt = mDevice.wait(Until.hasObject(By.text(dir)), TIMEOUT);
         assertTrue("object with text'(" + dir + "') not visible yet", gotIt);
         // TODO: find a better way to get the toggle rather then getting all
-        final List<UiObject2> toggles = mDevice.findObjects(By.res("android:id/switch_widget"));
-        assertEquals("should have just one toggle: " + toggles, 1, toggles.size());
-        final UiObject2 toggle = toggles.get(0);
+        UiObject2 toggle = getUniqueToggle();
         assertTrue("toggle for '" + dir + "' should be checked", toggle.isChecked());
         toggle.click();
+        toggle = getUniqueToggle();
         assertFalse("toggle for '" + dir + "' should not be checked", toggle.isChecked());
 
         // Close app screen.
         mDevice.pressBack();
-        // Close main screen.
-        mDevice.pressBack();
+        if (!isTelevision()) {
+            // Close main screen.
+            mDevice.pressBack();
+        }
 
         // Then tries again - should be denied.
         sendOpenExternalDirectoryIntent(volume, dir);
         assertActivityFailed();
     }
 
+    private UiObject2 getUniqueToggle() {
+        List<UiObject2> toggles = mDevice.findObjects(By.res("android:id/switch_widget"));
+        assertEquals("should have just one toggle: " + toggles, 1, toggles.size());
+        return toggles.get(0);
+    }
+
     private void launchDirectoryAccessSettingsScreenAndSelectApp() {
         final Intent intent = new Intent(Settings.ACTION_STORAGE_VOLUME_ACCESS_SETTINGS)
                 .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
index d219c6c..c26caba 100755
--- a/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionApp23/src/com/android/cts/usepermission/BasePermissionsTest.java
@@ -478,7 +478,9 @@
                     return result;
                 }
                 try {
-                    while (child.getActionList().contains(AccessibilityAction.ACTION_SCROLL_FORWARD)) {
+                    while (child.getActionList().contains(
+                            AccessibilityAction.ACTION_SCROLL_FORWARD) || child.getActionList()
+                            .contains(AccessibilityAction.ACTION_SCROLL_DOWN)) {
                         scrollForward(child);
                         result = getNodeTimed(() -> findByText(child, text), false);
                         if (result != null) {
diff --git a/hostsidetests/compilation/Android.mk b/hostsidetests/compilation/Android.mk
index 09c8507..c63c341 100644
--- a/hostsidetests/compilation/Android.mk
+++ b/hostsidetests/compilation/Android.mk
@@ -29,7 +29,7 @@
 
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
 
-LOCAL_STATIC_JAVA_LIBRARIES := guavalib
+LOCAL_STATIC_JAVA_LIBRARIES := guava
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.mk b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.mk
index 020d0bd..d1a2d21 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.mk
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.mk
@@ -32,7 +32,7 @@
 
 LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/src
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit android.test.base.stubs
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit android.test.base.stubs
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner compatibility-device-util
 
@@ -57,7 +57,7 @@
 
 LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/src
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit android.test.base.stubs
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit android.test.base.stubs
 
 LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner compatibility-device-util
 
diff --git a/hostsidetests/devicepolicy/app/CrossProfileAppsTest/Android.mk b/hostsidetests/devicepolicy/app/CrossProfileAppsTest/Android.mk
index 8ff609d..64034b9 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileAppsTest/Android.mk
+++ b/hostsidetests/devicepolicy/app/CrossProfileAppsTest/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := cts-junit
+LOCAL_JAVA_LIBRARIES := junit
 
 LOCAL_STATIC_JAVA_LIBRARIES = \
 	androidx.legacy_legacy-support-v4 \
diff --git a/hostsidetests/devicepolicy/app/DelegateApp/Android.mk b/hostsidetests/devicepolicy/app/DelegateApp/Android.mk
index 1d0be1d..711c44b 100644
--- a/hostsidetests/devicepolicy/app/DelegateApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/DelegateApp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit android.test.base.stubs
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit android.test.base.stubs
 
 LOCAL_STATIC_JAVA_LIBRARIES = \
     androidx.legacy_legacy-support-v4 \
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
index 214eebb..39dbf0a 100755
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
@@ -372,7 +372,8 @@
         Attestation attestationRecord = new Attestation((X509Certificate) leaf);
         AuthorizationList teeAttestation = attestationRecord.getTeeEnforced();
         assertNotNull(teeAttestation);
-        assertEquals(Build.BRAND, teeAttestation.getBrand());
+
+        validateBrandAttestationRecord(teeAttestation);
         assertEquals(Build.DEVICE, teeAttestation.getDevice());
         assertEquals(Build.PRODUCT, teeAttestation.getProduct());
         assertEquals(Build.MANUFACTURER, teeAttestation.getManufacturer());
@@ -382,6 +383,15 @@
         assertEquals(expectedMeid, teeAttestation.getMeid());
     }
 
+    private void validateBrandAttestationRecord(AuthorizationList teeAttestation) {
+        if (!Build.MODEL.equals("Pixel 2")) {
+            assertEquals(Build.BRAND, teeAttestation.getBrand());
+        } else {
+            assertTrue(teeAttestation.getBrand().equals(Build.BRAND)
+                    || teeAttestation.getBrand().equals("htc"));
+        }
+    }
+
     private void validateAttestationRecord(List<Certificate> attestation,
             byte[] providedChallenge) throws CertificateParsingException {
         assertNotNull(attestation);
@@ -445,6 +455,18 @@
             KeyGenParameterSpec spec = specBuilder.build();
             AttestedKeyPair generated = mDevicePolicyManager.generateKeyPair(
                     getWho(), keyAlgorithm, spec, deviceIdAttestationFlags);
+            // Bail out early if StrongBox was requested and generation failed.
+            // Note the underlying assumption that StrongBox supports key attestation _and_
+            // Device ID attestation (i.e. no StrongBox implementations that do not implement
+            // Device ID attestation).
+            // If generation has failed and StrongBox was requested, it is then a failure
+            // regardless of the kind of attestation requested.
+            if (useStrongBox && generated == null) {
+                assertFalse("StrongBox-backed key attestation must not fail if the device " +
+                        "declares support for StrongBox", hasStrongBox());
+                return null;
+            }
+
             // If Device ID attestation was requested, check it succeeded if and only if device ID
             // attestation is supported.
             if (isDeviceIdAttestationRequested(deviceIdAttestationFlags)) {
@@ -496,14 +518,10 @@
 
     public void testCanGenerateKeyPairWithKeyAttestationUsingStrongBox() throws Exception {
         for (SupportedKeyAlgorithm supportedKey: SUPPORTED_KEY_ALGORITHMS) {
-            Certificate attestation = generateKeyAndCheckAttestation(
+            generateKeyAndCheckAttestation(
                     supportedKey.keyAlgorithm, supportedKey.signatureAlgorithm,
                     supportedKey.signaturePaddingSchemes, true /* useStrongBox */,
                     0 /* idAttestationFlags */);
-            if (attestation == null) {
-                assertFalse("StrongBox-backed key attestation must not fail if the device " +
-                        "declares support for StrongBox", hasStrongBox());
-            }
         }
     }
 
@@ -557,6 +575,7 @@
                     // but StrongBox is not available on the device.
                     if (attestation == null && useStrongBox) {
                         assertFalse(hasStrongBox());
+                        continue;
                     }
                     assertNotNull(String.format(
                             "Attestation should be valid for key %s with attestation modes %s",
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk b/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
index c3f6d124..a76cace 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/Android.mk
@@ -30,7 +30,7 @@
 
 LOCAL_JAVA_LIBRARIES := \
     android.test.runner.stubs \
-    cts-junit \
+    junit \
     android.test.base.stubs \
     bouncycastle
 
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AirplaneModeRestrictionTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AirplaneModeRestrictionTest.java
old mode 100644
new mode 100755
index 2ea9598..393e62b
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AirplaneModeRestrictionTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AirplaneModeRestrictionTest.java
@@ -35,16 +35,19 @@
  */
 public class AirplaneModeRestrictionTest extends BaseDeviceOwnerTest {
     private static final int TIMEOUT_SEC = 5;
+    private static final int SLEEP_MS = 3000;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
         mDevicePolicyManager.clearUserRestriction(getWho(), UserManager.DISALLOW_AIRPLANE_MODE);
+        Thread.sleep(SLEEP_MS);
     }
 
     @Override
     protected void tearDown() throws Exception {
         mDevicePolicyManager.clearUserRestriction(getWho(), UserManager.DISALLOW_AIRPLANE_MODE);
+        Thread.sleep(SLEEP_MS);
         super.tearDown();
     }
 
@@ -74,15 +77,15 @@
     }
 
     public void testAirplaneModeCannotBeTurnedOnWithRestrictionOn()
-            throws SettingNotFoundException {
+            throws Exception {
         mDevicePolicyManager.addUserRestriction(getWho(), UserManager.DISALLOW_AIRPLANE_MODE);
+        Thread.sleep(SLEEP_MS);
         Settings.Global.putInt(mContext.getContentResolver(), AIRPLANE_MODE_ON, 1);
         assertEquals(0, Settings.Global.getInt(
                 mContext.getContentResolver(), AIRPLANE_MODE_ON));
     }
 
     public void testAirplaneModeCanBeTurnedOnWithRestrictionOff() throws SettingNotFoundException {
-        mDevicePolicyManager.clearUserRestriction(getWho(), UserManager.DISALLOW_AIRPLANE_MODE);
         Settings.Global.putInt(mContext.getContentResolver(), AIRPLANE_MODE_ON, 1);
         assertEquals(1, Settings.Global.getInt(
                 mContext.getContentResolver(), AIRPLANE_MODE_ON));
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java
index 1627961..65ede0a 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java
@@ -173,7 +173,7 @@
         mContext.startActivity(createRegularConfig);
 
         // Give some time for the other app to finish the action
-        Thread.sleep(2000);
+        Thread.sleep(5000);
     }
 
     private boolean areMatchingSsids(String s1, String s2) {
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
index 0475e30..e37617e 100644
--- a/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
+++ b/hostsidetests/devicepolicy/app/LauncherTests/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := cts-junit android.test.base.stubs
+LOCAL_JAVA_LIBRARIES := junit android.test.base.stubs
 
 LOCAL_STATIC_JAVA_LIBRARIES = \
 	androidx.legacy_legacy-support-v4 \
diff --git a/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk b/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
index 932f691..ead09a4 100644
--- a/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
+++ b/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := cts-junit
+LOCAL_JAVA_LIBRARIES := junit
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
index 6a02fd1..e876054 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit android.test.base.stubs
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit android.test.base.stubs
 
 LOCAL_USE_AAPT2 := true
 
diff --git a/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk b/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
index dd76558..8a024f8 100644
--- a/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/Android.mk
@@ -27,7 +27,7 @@
 
 LOCAL_JAVA_LIBRARIES := \
     android.test.runner.stubs \
-    cts-junit \
+    junit \
     android.test.base.stubs \
 
 
diff --git a/hostsidetests/devicepolicy/app/SingleAdminApp/Android.mk b/hostsidetests/devicepolicy/app/SingleAdminApp/Android.mk
index 4cdbeee..a385e1c 100644
--- a/hostsidetests/devicepolicy/app/SingleAdminApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/SingleAdminApp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES = \
     androidx.legacy_legacy-support-v4 \
diff --git a/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/Android.mk b/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/Android.mk
index 8f39155..7064258 100644
--- a/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     androidx.legacy_legacy-support-v4 \
diff --git a/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/Android.mk b/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/Android.mk
index aeacb40..14f6ab5 100644
--- a/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/Android.mk
+++ b/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     androidx.legacy_legacy-support-v4 \
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTestApi25.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTestApi25.java
index 23324a3..fd5b2bf 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTestApi25.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTestApi25.java
@@ -79,6 +79,9 @@
             return;
         }
 
+        // Make sure user initialization is complete before proceeding.
+        waitForBroadcastIdle();
+
         // Lock FBE and verify resetPassword is disabled
         executeDeviceTestMethod(FBE_HELPER_CLASS, "testSetPassword");
         rebootAndWaitUntilReady();
diff --git a/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk b/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
index c6e8104..c5c846b 100644
--- a/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
+++ b/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := cts-junit
+LOCAL_JAVA_LIBRARIES := junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.mk b/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.mk
index dd0fb9c..a0af404 100644
--- a/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.mk
+++ b/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/dumpsys/apps/storagedapp/Android.mk b/hostsidetests/dumpsys/apps/storagedapp/Android.mk
index 6364855..f163691 100644
--- a/hostsidetests/dumpsys/apps/storagedapp/Android.mk
+++ b/hostsidetests/dumpsys/apps/storagedapp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/dumpsys/src/android/dumpsys/cts/BatteryStatsDumpsysTest.java b/hostsidetests/dumpsys/src/android/dumpsys/cts/BatteryStatsDumpsysTest.java
index 0614db6..cad8a67 100644
--- a/hostsidetests/dumpsys/src/android/dumpsys/cts/BatteryStatsDumpsysTest.java
+++ b/hostsidetests/dumpsys/src/android/dumpsys/cts/BatteryStatsDumpsysTest.java
@@ -17,6 +17,7 @@
 package android.dumpsys.cts;
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.log.LogUtil.CLog;
 
 import java.io.BufferedReader;
 import java.io.File;
@@ -54,155 +55,160 @@
                 }
 
 
-                // With a default limit of 0, empty strings at the end are discarded.
-                // We still consider the empty string as a valid value in some cases.
-                // Using any negative number for the limit will preserve a trailing empty string.
-                // @see String#split(String, int)
-                String[] parts = line.split(",", -1);
-                assertInteger(parts[0]); // old version
-                assertInteger(parts[1]); // UID
-                switch (parts[2]) { // aggregation type
-                    case "i":
-                    case "l":
-                    case "c":
-                    case "u":
-                        break;
-                    default:
-                        fail("malformed stat: " + parts[2]);
-                }
-                assertNotNull(parts[3]);
-                seenTags.add(parts[3]);
+                try {
+                    // With a default limit of 0, empty strings at the end are discarded.
+                    // We still consider the empty string as a valid value in some cases.
+                    // Using any negative number for the limit will preserve a trailing empty string.
+                    // @see String#split(String, int)
+                    String[] parts = line.split(",", -1);
+                    assertInteger(parts[0]); // old version
+                    assertInteger(parts[1]); // UID
+                    switch (parts[2]) { // aggregation type
+                        case "i":
+                        case "l":
+                        case "c":
+                        case "u":
+                            break;
+                        default:
+                            fail("malformed stat: " + parts[2]);
+                    }
+                    assertNotNull(parts[3]);
+                    seenTags.add(parts[3]);
 
-                // Note the time fields are measured in milliseconds by default.
-                switch (parts[3]) {
-                    case "vers":
-                        checkVersion(parts);
-                        break;
-                    case "uid":
-                        checkUid(parts);
-                        break;
-                    case "apk":
-                        checkApk(parts);
-                        break;
-                    case "pr":
-                        checkProcess(parts);
-                        break;
-                    case "sr":
-                        checkSensor(parts);
-                        break;
-                    case "vib":
-                        checkVibrator(parts);
-                        break;
-                    case "fg":
-                        checkForegroundActivity(parts);
-                        break;
-                    case "fgs":
-                        checkForegroundService(parts);
-                        break;
-                    case "st":
-                        checkStateTime(parts);
-                        break;
-                    case "wl":
-                        checkWakelock(parts);
-                        break;
-                    case "awl":
-                        checkAggregatedWakelock(parts);
-                        break;
-                    case "sy":
-                        checkSync(parts);
-                        break;
-                    case "jb":
-                        checkJob(parts);
-                        break;
-                    case "jbc":
-                        checkJobCompletion(parts);
-                        break;
-                    case "jbd":
-                        checkJobsDeferred(parts);
-                        break;
-                    case "kwl":
-                        checkKernelWakelock(parts);
-                        break;
-                    case "wr":
-                        checkWakeupReason(parts);
-                        break;
-                    case "nt":
-                        checkNetwork(parts);
-                        break;
-                    case "ua":
-                        checkUserActivity(parts);
-                        break;
-                    case "bt":
-                        checkBattery(parts);
-                        break;
-                    case "dc":
-                        checkBatteryDischarge(parts);
-                        break;
-                    case "lv":
-                        checkBatteryLevel(parts);
-                        break;
-                    case "wfl":
-                        checkWifi(parts);
-                        break;
-                    case "m":
-                        checkMisc(parts);
-                        break;
-                    case "gn":
-                        checkGlobalNetwork(parts);
-                        break;
-                    case "br":
-                        checkScreenBrightness(parts);
-                        break;
-                    case "sgt":
-                    case "sgc":
-                        checkSignalStrength(parts);
-                        break;
-                    case "sst":
-                        checkSignalScanningTime(parts);
-                        break;
-                    case "dct":
-                    case "dcc":
-                        checkDataConnection(parts);
-                        break;
-                    case "wst":
-                    case "wsc":
-                        checkWifiState(parts);
-                        break;
-                    case "wsst":
-                    case "wssc":
-                        checkWifiSupplState(parts);
-                        break;
-                    case "wsgt":
-                    case "wsgc":
-                        checkWifiSignalStrength(parts);
-                        break;
-                    case "bst":
-                    case "bsc":
-                        checkBluetoothState(parts);
-                        break;
-                    case "blem":
-                        checkBluetoothMisc(parts);
-                        break;
-                    case "pws":
-                        checkPowerUseSummary(parts);
-                        break;
-                    case "pwi":
-                        checkPowerUseItem(parts);
-                        break;
-                    case "dsd":
-                    case "csd":
-                        checkChargeDischargeStep(parts);
-                        break;
-                    case "dtr":
-                        checkDischargeTimeRemain(parts);
-                        break;
-                    case "ctr":
-                        checkChargeTimeRemain(parts);
-                        break;
-                    case "cpu":
-                        checkUidCpuUsage(parts);
-                    default:
-                        break;
+                    // Note the time fields are measured in milliseconds by default.
+                    switch (parts[3]) {
+                        case "vers":
+                            checkVersion(parts);
+                            break;
+                        case "uid":
+                            checkUid(parts);
+                            break;
+                        case "apk":
+                            checkApk(parts);
+                            break;
+                        case "pr":
+                            checkProcess(parts);
+                            break;
+                        case "sr":
+                            checkSensor(parts);
+                            break;
+                        case "vib":
+                            checkVibrator(parts);
+                            break;
+                        case "fg":
+                            checkForegroundActivity(parts);
+                            break;
+                        case "fgs":
+                            checkForegroundService(parts);
+                            break;
+                        case "st":
+                            checkStateTime(parts);
+                            break;
+                        case "wl":
+                            checkWakelock(parts);
+                            break;
+                        case "awl":
+                            checkAggregatedWakelock(parts);
+                            break;
+                        case "sy":
+                            checkSync(parts);
+                            break;
+                        case "jb":
+                            checkJob(parts);
+                            break;
+                        case "jbc":
+                            checkJobCompletion(parts);
+                            break;
+                        case "jbd":
+                            checkJobsDeferred(parts);
+                            break;
+                        case "kwl":
+                            checkKernelWakelock(parts);
+                            break;
+                        case "wr":
+                            checkWakeupReason(parts);
+                            break;
+                        case "nt":
+                            checkNetwork(parts);
+                            break;
+                        case "ua":
+                            checkUserActivity(parts);
+                            break;
+                        case "bt":
+                            checkBattery(parts);
+                            break;
+                        case "dc":
+                            checkBatteryDischarge(parts);
+                            break;
+                        case "lv":
+                            checkBatteryLevel(parts);
+                            break;
+                        case "wfl":
+                            checkWifi(parts);
+                            break;
+                        case "m":
+                            checkMisc(parts);
+                            break;
+                        case "gn":
+                            checkGlobalNetwork(parts);
+                            break;
+                        case "br":
+                            checkScreenBrightness(parts);
+                            break;
+                        case "sgt":
+                        case "sgc":
+                            checkSignalStrength(parts);
+                            break;
+                        case "sst":
+                            checkSignalScanningTime(parts);
+                            break;
+                        case "dct":
+                        case "dcc":
+                            checkDataConnection(parts);
+                            break;
+                        case "wst":
+                        case "wsc":
+                            checkWifiState(parts);
+                            break;
+                        case "wsst":
+                        case "wssc":
+                            checkWifiSupplState(parts);
+                            break;
+                        case "wsgt":
+                        case "wsgc":
+                            checkWifiSignalStrength(parts);
+                            break;
+                        case "bst":
+                        case "bsc":
+                            checkBluetoothState(parts);
+                            break;
+                        case "blem":
+                            checkBluetoothMisc(parts);
+                            break;
+                        case "pws":
+                            checkPowerUseSummary(parts);
+                            break;
+                        case "pwi":
+                            checkPowerUseItem(parts);
+                            break;
+                        case "dsd":
+                        case "csd":
+                            checkChargeDischargeStep(parts);
+                            break;
+                        case "dtr":
+                            checkDischargeTimeRemain(parts);
+                            break;
+                        case "ctr":
+                            checkChargeTimeRemain(parts);
+                            break;
+                        case "cpu":
+                            checkUidCpuUsage(parts);
+                        default:
+                            break;
+                    }
+                } catch (AssertionError e) {
+                    CLog.e("Assert fail for line <" + line + ">");
+                    throw e;
                 }
             }
         }
diff --git a/hostsidetests/edi/Android.mk b/hostsidetests/edi/Android.mk
index c3b07ec..a403cde 100644
--- a/hostsidetests/edi/Android.mk
+++ b/hostsidetests/edi/Android.mk
@@ -21,7 +21,7 @@
 LOCAL_MODULE_TAGS := tests
 
 # tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
 
 LOCAL_MODULE := CtsEdiHostTestCases
 
@@ -29,4 +29,4 @@
 
 include $(BUILD_HOST_JAVA_LIBRARY)
 
-include $(call all-makefiles-under,$(LOCAL_PATH))
\ No newline at end of file
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/incident/apps/batterystatsapp/Android.mk b/hostsidetests/incident/apps/batterystatsapp/Android.mk
index e1518ef..b057049 100644
--- a/hostsidetests/incident/apps/batterystatsapp/Android.mk
+++ b/hostsidetests/incident/apps/batterystatsapp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit org.apache.http.legacy
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit org.apache.http.legacy
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/incident/apps/boundwidgetapp/Android.mk b/hostsidetests/incident/apps/boundwidgetapp/Android.mk
index 0b6a884..291fcd1 100644
--- a/hostsidetests/incident/apps/boundwidgetapp/Android.mk
+++ b/hostsidetests/incident/apps/boundwidgetapp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit android.test.base.stubs
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit android.test.base.stubs
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/incident/apps/errorsapp/Android.mk b/hostsidetests/incident/apps/errorsapp/Android.mk
index ec80ba8..17897d0 100644
--- a/hostsidetests/incident/apps/errorsapp/Android.mk
+++ b/hostsidetests/incident/apps/errorsapp/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_MULTILIB := both
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 # Includes the jni code as a shared library
 LOCAL_JNI_SHARED_LIBRARIES := libcrash-jni
diff --git a/hostsidetests/incident/apps/graphicsstatsapp/Android.mk b/hostsidetests/incident/apps/graphicsstatsapp/Android.mk
index ebcea6b..ac3e0fa 100644
--- a/hostsidetests/incident/apps/graphicsstatsapp/Android.mk
+++ b/hostsidetests/incident/apps/graphicsstatsapp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/incident/apps/netstatsapp/Android.mk b/hostsidetests/incident/apps/netstatsapp/Android.mk
index 158fb35..1130668 100644
--- a/hostsidetests/incident/apps/netstatsapp/Android.mk
+++ b/hostsidetests/incident/apps/netstatsapp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/incident/apps/notificationsapp/Android.mk b/hostsidetests/incident/apps/notificationsapp/Android.mk
index af1619e..b45505a 100644
--- a/hostsidetests/incident/apps/notificationsapp/Android.mk
+++ b/hostsidetests/incident/apps/notificationsapp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/incident/apps/procstatsapp/Android.mk b/hostsidetests/incident/apps/procstatsapp/Android.mk
index 47b9c77..43159a4 100644
--- a/hostsidetests/incident/apps/procstatsapp/Android.mk
+++ b/hostsidetests/incident/apps/procstatsapp/Android.mk
@@ -24,7 +24,7 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
diff --git a/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java b/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
index e48aeb1..c038eb2 100644
--- a/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/BatteryIncidentTest.java
@@ -28,7 +28,7 @@
     private static final String LEANBACK_FEATURE = "android.software.leanback";
 
     public void testBatteryServiceDump() throws Exception {
-        if (hasBattery(getDevice())) {
+        if (!hasBattery(getDevice())) {
             return;
         }
 
diff --git a/hostsidetests/inputmethodservice/common/Android.mk b/hostsidetests/inputmethodservice/common/Android.mk
index 94b59c9..a118474 100644
--- a/hostsidetests/inputmethodservice/common/Android.mk
+++ b/hostsidetests/inputmethodservice/common/Android.mk
@@ -41,7 +41,7 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_JAVA_LIBRARIES := junit-host
+LOCAL_JAVA_LIBRARIES := junit
 
 LOCAL_MODULE_TAGS := tests
 
diff --git a/hostsidetests/jvmti/base/app/Android.mk b/hostsidetests/jvmti/base/app/Android.mk
index 1c9b276..fe544d2 100644
--- a/hostsidetests/jvmti/base/app/Android.mk
+++ b/hostsidetests/jvmti/base/app/Android.mk
@@ -20,7 +20,7 @@
 LOCAL_SRC_FILES := $(call all-subdir-java-files)
 LOCAL_SDK_VERSION := current
 LOCAL_DEX_PREOPT := false
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 LOCAL_STATIC_JAVA_LIBRARIES := \
     ctstestrunner \
     compatibility-device-util \
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 89f1132..e623635 100644
--- a/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
+++ b/hostsidetests/jvmti/base/host/src/android/jvmti/cts/JvmtiHostTest.java
@@ -57,6 +57,12 @@
             mandatory = true)
     private String mTestApk = null;
 
+    @Option(name = "hidden-api-checks",
+            description = "If we should enable hidden api checks. Default 'true'. Set to 'false' " +
+            "to disable hiddenapi.",
+            mandatory = false)
+    private String mHiddenApiChecksEnabled = null;
+
     private CompatibilityBuildHelper mBuildHelper;
     private IAbi mAbi;
 
@@ -90,6 +96,23 @@
             throw new IllegalStateException("Incorrect configuration");
         }
 
+        if (null != mHiddenApiChecksEnabled &&
+            !"false".equals(mHiddenApiChecksEnabled) &&
+            !"true".equals(mHiddenApiChecksEnabled)) {
+          throw new IllegalStateException(
+              "option hidden-api-checks must be 'true' or 'false' if present.");
+        }
+        boolean disable_hidden_api =
+            mHiddenApiChecksEnabled != null && "false".equals(mHiddenApiChecksEnabled);
+        String old_p_apps_setting = null;
+        String old_pre_p_apps_setting = null;
+        if (disable_hidden_api) {
+            old_p_apps_setting = device.getSetting("global", "hidden_api_policy_p_apps");
+            old_pre_p_apps_setting = device.getSetting("global", "hidden_api_policy_pre_p_apps");
+            device.setSetting("global", "hidden_api_policy_p_apps", "1");
+            device.setSetting("global", "hidden_api_policy_pre_p_apps", "1");
+        }
+
         RemoteAndroidTestRunner runner = new RemoteAndroidTestRunner(mTestPackageName, RUNNER,
                 device.getIDevice());
         // set a max deadline limit to avoid hanging forever
@@ -103,6 +126,11 @@
 
         assertTrue(tr.getErrors(), tr.hasStarted());
         assertFalse(tr.getErrors(), tr.hasFailed());
+
+        if (disable_hidden_api) {
+            device.setSetting("global", "hidden_api_policy_p_apps", old_p_apps_setting);
+            device.setSetting("global", "hidden_api_policy_pre_p_apps", old_pre_p_apps_setting);
+        }
     }
 
     private String getDeviceBaseArch(ITestDevice device) throws Exception {
diff --git a/hostsidetests/jvmti/base/run-test-based-app/Android.mk b/hostsidetests/jvmti/base/run-test-based-app/Android.mk
index f1fa480..f3883a9 100644
--- a/hostsidetests/jvmti/base/run-test-based-app/Android.mk
+++ b/hostsidetests/jvmti/base/run-test-based-app/Android.mk
@@ -25,7 +25,7 @@
 
 LOCAL_SDK_VERSION := current
 LOCAL_DEX_PREOPT := false
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit
 LOCAL_STATIC_JAVA_LIBRARIES := CtsJvmtiDeviceAppBase
 LOCAL_STATIC_JAVA_LIBRARIES += run-test-jvmti-java
 LOCAL_PROGUARD_ENABLED := disabled
diff --git a/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml b/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml
index d13dbc9..1227f06 100644
--- a/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml
+++ b/hostsidetests/jvmti/run-tests/test-944/AndroidTest.xml
@@ -24,6 +24,7 @@
         <option name="jar" value="CtsJvmtiRunTest944HostTestCases.jar" />
         <option name="set-option" value="test-file-name:CtsJvmtiRunTest944DeviceApp.apk" />
         <option name="set-option" value="package-name:android.jvmti.cts.run_test_944" />
+        <option name="set-option" value="hidden-api-checks:false" />
         <option name="runtime-hint" value="8s"/>
     </test>
 </configuration>
diff --git a/hostsidetests/security/Android.mk b/hostsidetests/security/Android.mk
index e25b96c..cdf71dc 100644
--- a/hostsidetests/security/Android.mk
+++ b/hostsidetests/security/Android.mk
@@ -18,8 +18,6 @@
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
-LOCAL_JAVA_RESOURCE_DIRS := res
-
 LOCAL_MODULE_TAGS := optional
 
 # tag this module as a cts test artifact
diff --git a/hostsidetests/security/AndroidTest.xml b/hostsidetests/security/AndroidTest.xml
index 1282bd02..17921bf 100755
--- a/hostsidetests/security/AndroidTest.xml
+++ b/hostsidetests/security/AndroidTest.xml
@@ -16,137 +16,6 @@
 <configuration description="Config for the CTS Security host tests">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="security" />
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
-        <option name="cleanup" value="true" />
-        <option name="push" value="CVE-2016-8460->/data/local/tmp/CVE-2016-8460" />
-        <option name="push" value="CVE-2016-8482->/data/local/tmp/CVE-2016-8482" />
-        <option name="push" value="CVE-2016-6730->/data/local/tmp/CVE-2016-6730" />
-        <option name="push" value="CVE-2016-6731->/data/local/tmp/CVE-2016-6731" />
-        <option name="push" value="CVE-2016-6732->/data/local/tmp/CVE-2016-6732" />
-        <option name="push" value="CVE-2016-6733->/data/local/tmp/CVE-2016-6733" />
-        <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" />
-        <option name="push" value="CVE-2016-8428->/data/local/tmp/CVE-2016-8428" />
-        <option name="push" value="CVE-2016-8429->/data/local/tmp/CVE-2016-8429" />
-        <option name="push" value="CVE-2016-8430->/data/local/tmp/CVE-2016-8430" />
-        <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 -->
-        <option name="push" value="CVE-2016-0844->/data/local/tmp/CVE-2016-0844" />
-        <option name="push" value="CVE-2016-2419->/data/local/tmp/CVE-2016-2419" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-05 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-2460->/data/local/tmp/CVE-2016-2460" />
-
-        <!--__________________-->
-        <!-- 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 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-2471->/data/local/tmp/CVE-2016-2471" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-10 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2016-11 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2016-12 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-01 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-02 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-0426->/data/local/tmp/CVE-2017-0426" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-03 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-0479->/data/local/tmp/CVE-2017-0479" />
-        <option name="push" value="CVE-2017-0334->/data/local/tmp/CVE-2017-0334" />
-        <option name="push" value="CVE-2016-8479->/data/local/tmp/CVE-2016-8479" />
-        <option name="push" value="CVE-2017-0508->/data/local/tmp/CVE-2017-0508" />
-        <option name="push" value="CVE-2017-0333->/data/local/tmp/CVE-2017-0333" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-04 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-10229->/data/local/tmp/CVE-2016-10229" />
-        <option name="push" value="CVE-2014-3145->/data/local/tmp/CVE-2014-3145"/>
-        <option name="push" value="CVE-2017-0553->/data/local/tmp/CVE-2017-0553"/>
-
-        <!--__________________-->
-        <!-- Bulletin 2017-05 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-06 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-07 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-2109->/data/local/tmp/CVE-2016-2109"/>
-
-        <!--__________________-->
-        <!-- Bulletin 2017-08 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-09 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="Bug-38195738->/data/local/tmp/Bug-38195738" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-10 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-11 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-12 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-6262->/data/local/tmp/CVE-2017-6262" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-01 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2018-02 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-13232->/data/local/tmp/CVE-2017-13232" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-03 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-13253->/data/local/tmp/CVE-2017-13253" />
-
-        <option name="append-bitness" value="true" />
-    </target_preparer>
 
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsSecurityHostTestCases.jar" />
diff --git a/hostsidetests/security/res/add-debug.apk b/hostsidetests/security/res/add-debug.apk
deleted file mode 100644
index dff9cb6..0000000
--- a/hostsidetests/security/res/add-debug.apk
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/security/res/crash_mod.apk b/hostsidetests/security/res/crash_mod.apk
deleted file mode 100644
index 4991294..0000000
--- a/hostsidetests/security/res/crash_mod.apk
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/security/res/poc b/hostsidetests/security/res/poc
deleted file mode 100644
index 8b6f012..0000000
--- a/hostsidetests/security/res/poc
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/security/res/test-case b/hostsidetests/security/res/test-case
deleted file mode 100644
index bac4af1..0000000
--- a/hostsidetests/security/res/test-case
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
index cb189b8..bdf87a9 100644
--- a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
+++ b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
@@ -928,7 +928,7 @@
     public void testNoBugreportDenials() throws Exception {
         // Take a bugreport and get its logcat output.
         mDevice.executeAdbCommand("logcat", "-c");
-        mDevice.executeAdbCommand("bugreport");
+        mDevice.getBugreport();
         String log = mDevice.executeAdbCommand("logcat", "-d");
         // Find all the dumpstate-related types and make a regex that will match them.
         Set<String> types = sepolicyAnalyzeGetTypesAssociatedWithAttribute("hal_dumpstate_server");
@@ -1110,9 +1110,9 @@
     /* Init is always there */
     @CddTest(requirement="9.7")
     public void testInitDomain() throws DeviceNotAvailableException {
-        assertDomainHasExecutable("u:r:init:s0", "/init");
-        assertDomainHasExecutable("u:r:vendor_init:s0", "/init");
-        assertExecutableHasDomain("/init", "u:r:init:s0", "u:r:vendor_init:s0");
+        assertDomainHasExecutable("u:r:init:s0", "/system/bin/init");
+        assertDomainHasExecutable("u:r:vendor_init:s0", "/system/bin/init");
+        assertExecutableHasDomain("/system/bin/init", "u:r:init:s0", "u:r:vendor_init:s0");
     }
 
     /* Ueventd is always there */
diff --git a/hostsidetests/securitybulletin/Android.mk b/hostsidetests/securitybulletin/Android.mk
new file mode 100644
index 0000000..a07fbbd
--- /dev/null
+++ b/hostsidetests/securitybulletin/Android.mk
@@ -0,0 +1,39 @@
+# Copyright (C) 2014 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_JAVA_RESOURCE_DIRS := res
+
+LOCAL_MODULE_TAGS := optional
+
+# tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+# Must match the package name in CtsTestCaseList.mk
+LOCAL_MODULE := CtsSecurityBulletinHostTestCases
+
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+
+LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
+
+LOCAL_CTS_TEST_PACKAGE := android.host.security
+
+include $(BUILD_CTS_HOST_JAVA_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/hostsidetests/securitybulletin/AndroidTest.xml b/hostsidetests/securitybulletin/AndroidTest.xml
new file mode 100644
index 0000000..0c9ebe3
--- /dev/null
+++ b/hostsidetests/securitybulletin/AndroidTest.xml
@@ -0,0 +1,155 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Config for the CTS Security bulletin host tests">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="security" />
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CVE-2016-8460->/data/local/tmp/CVE-2016-8460" />
+        <option name="push" value="CVE-2016-8482->/data/local/tmp/CVE-2016-8482" />
+        <option name="push" value="CVE-2016-6730->/data/local/tmp/CVE-2016-6730" />
+        <option name="push" value="CVE-2016-6731->/data/local/tmp/CVE-2016-6731" />
+        <option name="push" value="CVE-2016-6732->/data/local/tmp/CVE-2016-6732" />
+        <option name="push" value="CVE-2016-6733->/data/local/tmp/CVE-2016-6733" />
+        <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" />
+        <option name="push" value="CVE-2016-8428->/data/local/tmp/CVE-2016-8428" />
+        <option name="push" value="CVE-2016-8429->/data/local/tmp/CVE-2016-8429" />
+        <option name="push" value="CVE-2016-8430->/data/local/tmp/CVE-2016-8430" />
+        <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 -->
+        <option name="push" value="CVE-2016-0844->/data/local/tmp/CVE-2016-0844" />
+        <option name="push" value="CVE-2016-2419->/data/local/tmp/CVE-2016-2419" />
+
+        <!--__________________-->
+        <!-- Bulletin 2016-05 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2016-2460->/data/local/tmp/CVE-2016-2460" />
+
+        <!--__________________-->
+        <!-- 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 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2016-2471->/data/local/tmp/CVE-2016-2471" />
+
+        <!--__________________-->
+        <!-- Bulletin 2016-10 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2016-11 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2016-12 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2017-01 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2017-02 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2017-0426->/data/local/tmp/CVE-2017-0426" />
+
+        <!--__________________-->
+        <!-- Bulletin 2017-03 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2017-0479->/data/local/tmp/CVE-2017-0479" />
+        <option name="push" value="CVE-2017-0334->/data/local/tmp/CVE-2017-0334" />
+        <option name="push" value="CVE-2016-8479->/data/local/tmp/CVE-2016-8479" />
+        <option name="push" value="CVE-2017-0508->/data/local/tmp/CVE-2017-0508" />
+        <option name="push" value="CVE-2017-0333->/data/local/tmp/CVE-2017-0333" />
+
+        <!--__________________-->
+        <!-- Bulletin 2017-04 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2016-10229->/data/local/tmp/CVE-2016-10229" />
+        <option name="push" value="CVE-2014-3145->/data/local/tmp/CVE-2014-3145"/>
+        <option name="push" value="CVE-2017-0553->/data/local/tmp/CVE-2017-0553"/>
+
+        <!--__________________-->
+        <!-- Bulletin 2017-05 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2017-06 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2017-07 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2016-2109->/data/local/tmp/CVE-2016-2109"/>
+
+        <!--__________________-->
+        <!-- Bulletin 2017-08 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2017-09 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="Bug-38195738->/data/local/tmp/Bug-38195738" />
+
+        <!--__________________-->
+        <!-- Bulletin 2017-10 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2017-11 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2017-12 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2017-6262->/data/local/tmp/CVE-2017-6262" />
+
+        <!--__________________-->
+        <!-- Bulletin 2018-01 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+
+        <!--__________________-->
+        <!-- Bulletin 2018-02 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2017-13232->/data/local/tmp/CVE-2017-13232" />
+
+        <!--__________________-->
+        <!-- Bulletin 2018-03 -->
+        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
+        <option name="push" value="CVE-2017-13253->/data/local/tmp/CVE-2017-13253" />
+
+        <option name="append-bitness" value="true" />
+    </target_preparer>
+
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsSecurityBulletinHostTestCases.jar" />
+        <option name="runtime-hint" value="8m40s" />
+    </test>
+</configuration>
diff --git a/hostsidetests/security/res/cve_2016_3916.apk b/hostsidetests/securitybulletin/res/cve_2016_3916.apk
similarity index 100%
rename from hostsidetests/security/res/cve_2016_3916.apk
rename to hostsidetests/securitybulletin/res/cve_2016_3916.apk
Binary files differ
diff --git a/hostsidetests/security/res/cve_2017_0859.mp4 b/hostsidetests/securitybulletin/res/cve_2017_0859.mp4
similarity index 100%
rename from hostsidetests/security/res/cve_2017_0859.mp4
rename to hostsidetests/securitybulletin/res/cve_2017_0859.mp4
Binary files differ
diff --git a/hostsidetests/security/securityPatch/Android.mk b/hostsidetests/securitybulletin/securityPatch/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/Android.mk
diff --git a/hostsidetests/security/securityPatch/Bug-38195738/Android.mk b/hostsidetests/securitybulletin/securityPatch/Bug-38195738/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/Bug-38195738/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/Bug-38195738/Android.mk
diff --git a/hostsidetests/security/securityPatch/Bug-38195738/poc.c b/hostsidetests/securitybulletin/securityPatch/Bug-38195738/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/Bug-38195738/poc.c
rename to hostsidetests/securitybulletin/securityPatch/Bug-38195738/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2014-3145/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2014-3145/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2014-3145/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2014-3145/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2014-3145/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2014-3145/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2014-3145/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2014-3145/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-0844/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-0844/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-0844/local_poc.h b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/local_poc.h
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-0844/local_poc.h
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/local_poc.h
diff --git a/hostsidetests/security/securityPatch/CVE-2016-0844/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-0844/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-10229/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-10229/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-10229/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-10229/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-10229/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-10229/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-10229/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-10229/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2109/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2109/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2109/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2109/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2109/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2109/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2109/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2109/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2419/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2419/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2419/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2419/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2419/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2419/poc.cpp
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2419/poc.cpp
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2419/poc.cpp
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2460/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2460/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2460/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2460/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2460/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2460/poc.cpp
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2460/poc.cpp
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2460/poc.cpp
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2471/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2471/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2471/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2471/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2471/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2471/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2471/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2471/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-2504/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/Android.mk
similarity index 93%
rename from hostsidetests/security/securityPatch/CVE-2016-2504/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/Android.mk
index 51e6dd8..f4c50fe 100644
--- a/hostsidetests/security/securityPatch/CVE-2016-2504/Android.mk
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/Android.mk
@@ -33,6 +33,3 @@
 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/security/securityPatch/CVE-2016-2504/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-2504/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-2504/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-3809/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-3809/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-3809/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-3809/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-3809/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-3818/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3818/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-3818/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-3818/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-3818/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3818/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-3818/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-3818/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6730/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6730/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6730/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6730/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6731/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6731/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6731/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6731/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6732/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6732/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6732/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6732/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6733/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6733/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6733/local_pwn.h b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/local_pwn.h
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6733/local_pwn.h
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/local_pwn.h
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6733/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6733/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6734/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6734/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6734/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6734/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6735/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6735/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6735/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6735/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6736/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6736/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-6736/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-6736/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8424/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8424/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8424/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8424/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8424/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8425/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8425/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8425/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8425/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8426/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8426/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8426/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8426/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8427/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8427/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8427/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8427/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8428/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8428/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8428/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8428/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8429/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8429/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8429/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8429/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8430/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8430/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8431/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8431/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8431/local_poc.h b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/local_poc.h
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8431/local_poc.h
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/local_poc.h
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8431/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8431/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8432/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8432/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8432/local_poc.h b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/local_poc.h
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8432/local_poc.h
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/local_poc.h
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8432/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8432/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8434/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8434/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8434/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8434/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8460/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8460/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8460/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8460/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8479/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8479/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8479/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8479/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8479/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8479/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8479/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8479/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8482/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8482/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8482/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2016-8482/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0333/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0333/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0333/local_poc.h b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/local_poc.h
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0333/local_poc.h
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/local_poc.h
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0333/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0333/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0334/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0334/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0334/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0334/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0334/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0334/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0334/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0334/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0426/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0426/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0426/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0426/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0426/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0426/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0426/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0426/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0479/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0479/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0479/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0479/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0479/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0479/poc.cpp
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0479/poc.cpp
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0479/poc.cpp
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0508/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0508/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0508/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0508/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0508/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0508/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0508/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0508/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0553/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0553/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0553/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0553/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-0553/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0553/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-0553/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-0553/poc.c
diff --git a/hostsidetests/security/securityPatch/CVE-2017-13232/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-13232/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-13232/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/poc.cpp
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-13232/poc.cpp
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/poc.cpp
diff --git a/hostsidetests/security/securityPatch/CVE-2017-13253/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13253/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-13253/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-13253/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-13253/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13253/poc.cpp
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-13253/poc.cpp
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-13253/poc.cpp
diff --git a/hostsidetests/security/securityPatch/CVE-2017-6262/Android.mk b/hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/Android.mk
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-6262/Android.mk
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/Android.mk
diff --git a/hostsidetests/security/securityPatch/CVE-2017-6262/local_poc.h b/hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/local_poc.h
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-6262/local_poc.h
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/local_poc.h
diff --git a/hostsidetests/security/securityPatch/CVE-2017-6262/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/poc.c
similarity index 100%
rename from hostsidetests/security/securityPatch/CVE-2017-6262/poc.c
rename to hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/poc.c
diff --git a/hostsidetests/security/src/android/security/cts/AdbUtils.java b/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/AdbUtils.java
rename to hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc16_04.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_04.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc16_04.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc16_04.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc16_05.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_05.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc16_05.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc16_05.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc16_07.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc16_07.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc16_07.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc16_08.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_08.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc16_08.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc16_08.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc16_09.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_09.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc16_09.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc16_09.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc16_10.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc16_10.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc16_10.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc16_12.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc16_12.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc16_12.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc16_12.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_01.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_01.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_01.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_02.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_02.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_02.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_03.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_03.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_03.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_04.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_04.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_04.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_04.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_05.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_05.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_05.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_05.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_07.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_07.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_07.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_07.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_09.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_09.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_09.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_09.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_11.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_11.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_11.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_11.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_12.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc17_12.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc17_12.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc17_12.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc18_02.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_02.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc18_02.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc18_02.java
diff --git a/hostsidetests/security/src/android/security/cts/Poc18_03.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc18_03.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/Poc18_03.java
rename to hostsidetests/securitybulletin/src/android/security/cts/Poc18_03.java
diff --git a/hostsidetests/security/src/android/security/cts/SecurityTestCase.java b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
similarity index 100%
rename from hostsidetests/security/src/android/security/cts/SecurityTestCase.java
rename to hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
diff --git a/hostsidetests/statsd/apps/statsdapp/Android.mk b/hostsidetests/statsd/apps/statsdapp/Android.mk
index 4de17bb..71d9323 100644
--- a/hostsidetests/statsd/apps/statsdapp/Android.mk
+++ b/hostsidetests/statsd/apps/statsdapp/Android.mk
@@ -27,7 +27,7 @@
 LOCAL_SRC_FILES := \
     $(call all-java-files-under, src)
 
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs cts-junit org.apache.http.legacy
+LOCAL_JAVA_LIBRARIES := android.test.runner.stubs junit org.apache.http.legacy
 
 LOCAL_PRIVILEGED_MODULE := true
 
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
index 225ebf5..02bc735 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
@@ -654,4 +654,11 @@
         return hasIt == requiredAnswer;
     }
 
+    /**
+     * Determines if the device has |file|.
+     */
+    protected boolean doesFileExist(String file) throws Exception {
+        return getDevice().doesFileExist(file);
+    }
+
 }
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
index 71fac10..cc3b47c 100644
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
+++ b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
@@ -31,6 +31,7 @@
 import com.android.os.AtomsProto.RemainingBatteryCapacity;
 import com.android.os.StatsLog.EventMetricData;
 
+import java.io.File;
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
@@ -48,6 +49,10 @@
     private static final String FEATURE_TELEPHONY = "android.hardware.telephony";
     private static final String FEATURE_WATCH = "android.hardware.type.watch";
 
+    // Either file must exist to read kernel wake lock stats.
+    private static final String WAKE_LOCK_FILE = "/proc/wakelocks";
+    private static final String WAKE_SOURCES_FILE = "/d/wakeup_sources";
+
     @Override
     protected void setUp() throws Exception {
         super.setUp();
@@ -382,7 +387,7 @@
     }
 
     public void testKernelWakelock() throws Exception {
-        if (statsdDisabled()) {
+        if (statsdDisabled() || !kernelWakelockStatsExist()) {
             return;
         }
         StatsdConfig.Builder config = getPulledConfig();
@@ -408,6 +413,15 @@
         assertTrue(atom.getKernelWakelock().hasTime());
     }
 
+    // Returns true iff either |WAKE_LOCK_FILE| or |WAKE_SOURCES_FILE| exists.
+    private boolean kernelWakelockStatsExist() {
+      try {
+        return doesFileExist(WAKE_LOCK_FILE) || doesFileExist(WAKE_SOURCES_FILE);
+      } catch(Exception e) {
+        return false;
+      }
+    }
+
     public void testWifiActivityInfo() throws Exception {
         if (statsdDisabled()) {
             return;
diff --git a/libs/Android.mk b/libs/Android.mk
deleted file mode 100644
index 4343259..0000000
--- a/libs/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Copyright (C) 2010 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-include $(call all-subdir-makefiles)
diff --git a/libs/deviceutillegacy/Android.bp b/libs/deviceutillegacy/Android.bp
new file mode 100644
index 0000000..5221c43
--- /dev/null
+++ b/libs/deviceutillegacy/Android.bp
@@ -0,0 +1,29 @@
+// Copyright (C) 2014 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library_static {
+    name: "ctsdeviceutillegacy",
+
+    static_libs: [
+        "compatibility-device-util",
+        "junit",
+    ],
+
+    libs: ["android.test.base.stubs"],
+
+    srcs: ["src/**/*.java"],
+
+    sdk_version: "test_current",
+
+}
diff --git a/libs/deviceutillegacy/Android.mk b/libs/deviceutillegacy/Android.mk
deleted file mode 100644
index 8cfa6d1..0000000
--- a/libs/deviceutillegacy/Android.mk
+++ /dev/null
@@ -1,36 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util \
-    junit
-
-LOCAL_JAVA_LIBRARIES := android.test.base.stubs
-
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under, src)
-
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE := ctsdeviceutillegacy
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/libs/json/Android.bp b/libs/json/Android.bp
new file mode 100644
index 0000000..59a9f3a
--- /dev/null
+++ b/libs/json/Android.bp
@@ -0,0 +1,28 @@
+//
+// Copyright (C) 2010 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+java_library {
+    name: "json",
+    host_supported: true,
+    srcs: ["src/**/*.java"],
+    sdk_version: "current",
+}
+
+// Compatibility version of host library
+java_library_host {
+    name: "jsonlib",
+    static_libs: ["json"],
+}
diff --git a/libs/json/Android.mk b/libs/json/Android.mk
deleted file mode 100644
index d1b2051..0000000
--- a/libs/json/Android.mk
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# Copyright (C) 2010 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH:= $(call my-dir)
-
-# Build the host library
-# ======================
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_MODULE := jsonlib
-LOCAL_MODULE_TAGS := optional
-
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-# Build the target library
-# =======================
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_MODULE := json
-LOCAL_MODULE_TAGS := optional
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
diff --git a/libs/runner/Android.bp b/libs/runner/Android.bp
new file mode 100644
index 0000000..5ec51ef
--- /dev/null
+++ b/libs/runner/Android.bp
@@ -0,0 +1,22 @@
+// Copyright (C) 2012 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "ctstestrunner",
+
+    static_libs: ["cts-test-runner"],
+
+    sdk_version: "current",
+
+}
diff --git a/libs/runner/Android.mk b/libs/runner/Android.mk
deleted file mode 100644
index 15f64a3..0000000
--- a/libs/runner/Android.mk
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright (C) 2012 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT 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_STATIC_JAVA_LIBRARIES := cts-test-runner
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE := ctstestrunner
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/libs/testserver/Android.bp b/libs/testserver/Android.bp
new file mode 100644
index 0000000..14b9ed4
--- /dev/null
+++ b/libs/testserver/Android.bp
@@ -0,0 +1,22 @@
+// Copyright (C) 2012 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_library {
+    name: "ctstestserver",
+
+    srcs: ["src/**/*.java"],
+
+    sdk_version: "16",
+
+}
diff --git a/libs/testserver/Android.mk b/libs/testserver/Android.mk
deleted file mode 100644
index 488af53..0000000
--- a/libs/testserver/Android.mk
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright (C) 2012 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE := ctstestserver
-
-LOCAL_SDK_VERSION := 16
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/libs/view/Android.bp b/libs/view/Android.bp
new file mode 100644
index 0000000..c58c3ca
--- /dev/null
+++ b/libs/view/Android.bp
@@ -0,0 +1,24 @@
+//
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+java_library {
+    name: "cts-view-lib",
+
+    srcs: ["src/**/*.java"],
+
+    sdk_version: "current",
+
+}
diff --git a/libs/view/Android.mk b/libs/view/Android.mk
deleted file mode 100644
index 0b121da..0000000
--- a/libs/view/Android.mk
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_MODULE := cts-view-lib
-LOCAL_MODULE_TAGS := optional
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/libs/vogar-expect/Android.bp b/libs/vogar-expect/Android.bp
new file mode 100644
index 0000000..6a48828
--- /dev/null
+++ b/libs/vogar-expect/Android.bp
@@ -0,0 +1,33 @@
+//
+// Copyright (C) 2010 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+java_library {
+    name: "vogarexpect",
+    host_supported: true,
+    srcs: ["src/**/*.java"],
+
+    sdk_version: "current",
+
+    static_libs: [
+        "guava",
+        "json",
+    ],
+}
+
+java_library_host {
+    name: "vogarexpectlib",
+    static_libs: ["vogarexpect"],
+}
diff --git a/libs/vogar-expect/Android.mk b/libs/vogar-expect/Android.mk
deleted file mode 100644
index f888d26..0000000
--- a/libs/vogar-expect/Android.mk
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# Copyright (C) 2010 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-LOCAL_PATH:= $(call my-dir)
-
-# Build the host library
-# ======================
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_MODULE := vogarexpectlib
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_STATIC_JAVA_LIBRARIES := guavalib jsonlib
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-# Build the target library
-# =======================
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-LOCAL_MODULE := vogarexpect
-LOCAL_MODULE_TAGS := optional
-LOCAL_SDK_VERSION := current
-
-LOCAL_STATIC_JAVA_LIBRARIES := guava json
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
diff --git a/suite/cts/Android.mk b/suite/cts/Android.mk
deleted file mode 100644
index c141484..0000000
--- a/suite/cts/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Copyright (C) 2012 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-include $(call all-subdir-makefiles)
diff --git a/suite/cts/deviceTests/Android.mk b/suite/cts/deviceTests/Android.mk
deleted file mode 100644
index c141484..0000000
--- a/suite/cts/deviceTests/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Copyright (C) 2012 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-include $(call all-subdir-makefiles)
diff --git a/tests/JobScheduler/Android.mk b/tests/JobScheduler/Android.mk
index 9cb148b..622c06e 100755
--- a/tests/JobScheduler/Android.mk
+++ b/tests/JobScheduler/Android.mk
@@ -30,7 +30,7 @@
 LOCAL_SRC_FILES += $(call all-java-files-under, JobTestApp/src)
 
 # Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
+LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
 # Must match the package name in CtsTestCaseList.mk
 LOCAL_PACKAGE_NAME := CtsJobSchedulerTestCases
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
index d535fab..c402330 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
@@ -52,6 +52,7 @@
 import android.os.Process;
 import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.Presubmit;
+import android.support.test.filters.FlakyTest;
 import android.test.suitebuilder.annotation.MediumTest;
 import android.text.TextUtils;
 import android.util.Log;
@@ -300,6 +301,7 @@
         assertNotNull("Did not receive expected event: " + expected, awaitedTextChangeEvent);
     }
 
+    @FlakyTest(bugId = 114543540)
     @MediumTest
     @Presubmit
     public void testTypeWindowStateChangedAccessibilityEvent() throws Throwable {
@@ -337,6 +339,7 @@
         assertNotNull("Did not receive expected event: " + expected, awaitedEvent);
     }
 
+    @FlakyTest(bugId = 114543540)
     @MediumTest
     @AppModeFull
     @SuppressWarnings("deprecation")
@@ -561,6 +564,7 @@
         }
     }
 
+    @FlakyTest(bugId = 114543540)
     @MediumTest
     @Presubmit
     public void testViewHeadingReportedToAccessibility() throws Exception {
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityFocusAndInputFocusSyncTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityFocusAndInputFocusSyncTest.java
index 7cb569c..d812f15 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityFocusAndInputFocusSyncTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityFocusAndInputFocusSyncTest.java
@@ -22,6 +22,7 @@
 import android.app.Instrumentation;
 import android.app.UiAutomation;
 import android.platform.test.annotations.Presubmit;
+import android.support.test.filters.FlakyTest;
 import android.test.suitebuilder.annotation.MediumTest;
 import android.view.View;
 import android.view.accessibility.AccessibilityEvent;
@@ -44,6 +45,7 @@
         super(AccessibilityFocusAndInputFocusSyncActivity.class);
     }
 
+    @FlakyTest(bugId = 114543540)
     @MediumTest
     @Presubmit
     public void testFindAccessibilityFocus() throws Exception {
@@ -206,7 +208,7 @@
             public void run() {
                 // Perform a set focus action and check for success.
                 assertTrue(secondEditText.performAction(ACTION_ACCESSIBILITY_FOCUS));
-                
+
             }
         }, new UiAutomation.AccessibilityEventFilter() {
             @Override
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityMagnificationTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityMagnificationTest.java
index c574541..ebb711b 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityMagnificationTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityMagnificationTest.java
@@ -28,6 +28,7 @@
 import android.accessibilityservice.AccessibilityServiceInfo;
 import android.app.Instrumentation;
 import android.content.Context;
+import android.graphics.Rect;
 import android.graphics.Region;
 import android.platform.test.annotations.AppModeFull;
 import android.test.InstrumentationTestCase;
@@ -89,13 +90,11 @@
 
     public void testSetScaleAndCenter() {
         final MagnificationController controller = mService.getMagnificationController();
-        final WindowManager wm = (WindowManager) mInstrumentation.getContext().getSystemService(
-                Context.WINDOW_SERVICE);
-        final DisplayMetrics metrics = new DisplayMetrics();
-        wm.getDefaultDisplay().getRealMetrics(metrics);
+        final Region region = controller.getMagnificationRegion();
+        final Rect bounds = region.getBounds();
         final float scale = 2.0f;
-        final float x = metrics.widthPixels / 4.0f;
-        final float y = metrics.heightPixels / 4.0f;
+        final float x = bounds.left + (bounds.width() / 4.0f);
+        final float y = bounds.top + (bounds.height() / 4.0f);
         final AtomicBoolean setScale = new AtomicBoolean();
         final AtomicBoolean setCenter = new AtomicBoolean();
         final AtomicBoolean result = new AtomicBoolean();
diff --git a/tests/app/app/AndroidManifest.xml b/tests/app/app/AndroidManifest.xml
index e05b8b4..fe340c9 100644
--- a/tests/app/app/AndroidManifest.xml
+++ b/tests/app/app/AndroidManifest.xml
@@ -51,7 +51,7 @@
                 android:multiArch="true"
                 android:name="android.app.stubs.MockApplication"
                 android:supportsRtl="true"
-                android:usesCleartextTraffic="true">
+                android:networkSecurityConfig="@xml/network_security_config">
         <uses-library android:name="android.test.runner" />
         <uses-library android:name="org.apache.http.legacy" android:required="false" />
 
diff --git a/tests/app/app/res/xml/network_security_config.xml b/tests/app/app/res/xml/network_security_config.xml
new file mode 100644
index 0000000..cb4b34f
--- /dev/null
+++ b/tests/app/app/res/xml/network_security_config.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<network-security-config>
+  <base-config cleartextTrafficPermitted="true">
+  </base-config>
+  <!-- Cleartext traffic is explicitly permitted to example.com and all subdomains -->
+  <domain-config cleartextTrafficPermitted="true">
+      <domain includeSubdomains="true">example.com</domain>
+  </domain-config>
+  <domain-config cleartextTrafficPermitted="true">
+      <domain includeSubdomains="true">localhost</domain>
+  </domain-config>
+</network-security-config>
diff --git a/tests/aslr/AndroidTest.xml b/tests/aslr/AndroidTest.xml
index 87c5dfb..b17bcf6 100644
--- a/tests/aslr/AndroidTest.xml
+++ b/tests/aslr/AndroidTest.xml
@@ -25,7 +25,7 @@
         <option name="native-test-device-path" value="/data/local/tmp" />
         <option name="module-name" value="CtsAslrMallocTestCases" />
         <option name="runtime-hint" value="10m30s" />
-        <!-- test-timeout unit is ms, value = 10 min -->
-        <option name="native-test-timeout" value="600000" />
+        <!-- test-timeout unit is ms, value = 20 min -->
+        <option name="native-test-timeout" value="1200000" />
     </test>
 </configuration>
diff --git a/tests/autofillservice/src/android/autofillservice/cts/EmptyActivity.java b/tests/autofillservice/src/android/autofillservice/cts/EmptyActivity.java
index 679ddd8..87e2b3a 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/EmptyActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/EmptyActivity.java
@@ -18,14 +18,17 @@
 
 import android.app.Activity;
 import android.os.Bundle;
-import androidx.annotation.Nullable;
 import android.view.View;
 
+import androidx.annotation.Nullable;
+
 /**
  * Empty activity
  */
 public class EmptyActivity extends Activity {
 
+    public static final String ID_EMPTY = "empty";
+
     private View mEmptyView;
 
     @Override
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MultiWindowLoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/MultiWindowLoginActivityTest.java
index 0796028..d1a94ec 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/MultiWindowLoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/MultiWindowLoginActivityTest.java
@@ -79,10 +79,10 @@
     /**
      * Put activity1 in TOP, will be followed by amStartActivity()
      */
-    protected void splitWindow(Activity activity1) {
-        mAm.setTaskWindowingModeSplitScreenPrimary(activity1.getTaskId(),
+    protected void splitWindow(Activity activity) throws Exception {
+        mAm.setTaskWindowingModeSplitScreenPrimary(activity.getTaskId(),
                 SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, true, false, null, true);
-
+        mUiBot.waitForWindowSplit();
     }
 
     protected void amStartActivity(Class<? extends Activity> activity2) {
@@ -116,6 +116,10 @@
         amStartActivity(MultiWindowEmptyActivity.class);
         MultiWindowEmptyActivity emptyActivity = MultiWindowEmptyActivity.waitNewInstance();
 
+        // Make sure both activities are showing
+        mUiBot.assertShownByRelativeId(Helper.ID_USERNAME);  // MultiWindowLoginActivity
+        mUiBot.assertShownByRelativeId(MultiWindowEmptyActivity.ID_EMPTY);
+
         // No dataset as LoginActivity loses window focus
         mUiBot.assertNoDatasets();
         // EmptyActivity will have window focus
diff --git a/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java b/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
index a9974f1..6f6b75a 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/OutOfProcessLoginActivity.java
@@ -66,15 +66,28 @@
         super.onStop();
 
         try {
-            getStoppedMarker(this).createNewFile();
+            if (!getStoppedMarker(this).createNewFile()) {
+                Log.e(TAG, "could not write stopped marker");
+            } else {
+                Log.v(TAG, "wrote stopped marker");
+            }
         } catch (IOException e) {
-            Log.e(TAG, "cannot write stopped file: " + e);
+            Log.e(TAG, "could write stopped marker: " + e);
         }
     }
 
     @Override
     protected void onDestroy() {
         Log.i(TAG, "onDestroy()");
+        try {
+            if (!getDestroyedMarker(this).createNewFile()) {
+                Log.e(TAG, "could not write destroyed marker");
+            } else {
+                Log.v(TAG, "wrote destroyed marker");
+            }
+        } catch (IOException e) {
+            Log.e(TAG, "could write destroyed marker: " + e);
+        }
         super.onDestroy();
     }
 
@@ -98,6 +111,16 @@
         return new File(context.getFilesDir(), "started");
     }
 
+   /**
+     * Get the file that signals that the activity has entered {@link Activity#onDestroy()}.
+     *
+     * @param context Context of the app
+     * @return The marker file that is written onDestroy()
+     */
+    @NonNull public static File getDestroyedMarker(@NonNull Context context) {
+        return new File(context.getFilesDir(), "destroyed");
+    }
+
     public static void finishIt() {
         Log.v(TAG, "Finishing " + sInstance);
         if (sInstance != null) {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java b/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
index 01098e9..1ae4418 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/SessionLifecycleTest.java
@@ -22,6 +22,7 @@
 import static android.autofillservice.cts.Helper.assertTextAndValue;
 import static android.autofillservice.cts.Helper.findNodeByResourceId;
 import static android.autofillservice.cts.Helper.getContext;
+import static android.autofillservice.cts.OutOfProcessLoginActivity.getDestroyedMarker;
 import static android.autofillservice.cts.OutOfProcessLoginActivity.getStartedMarker;
 import static android.autofillservice.cts.OutOfProcessLoginActivity.getStoppedMarker;
 import static android.autofillservice.cts.UiBot.LANDSCAPE;
@@ -101,6 +102,11 @@
         runShellCommand("am broadcast --receiver-foreground "
                 + "-n android.autofillservice.cts/.OutOfProcessLoginActivityFinisherReceiver");
         mUiBot.assertGoneByRelativeId(ID_USERNAME, Timeouts.ACTIVITY_RESURRECTION);
+
+        // Waiting for activity to be destroyed (destroy marker appears)
+        eventually("getDestroyedMarker()", () -> {
+            return getDestroyedMarker(getContext()).exists();
+        });
     }
 
     private void killOfProcessLoginActivityProcess() throws Exception {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
index c7cca28..5eefb0d 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/UiBot.java
@@ -99,6 +99,10 @@
     private static final BySelector DATASET_HEADER_SELECTOR =
             By.res("android", RESOURCE_ID_DATASET_HEADER);
 
+    // TODO: figure out a more reliable solution that does not depend on SystemUI resources.
+    private static final String SPLIT_WINDOW_DIVIDER_ID =
+            "com.android.systemui:id/docked_divider_background";
+
     private static final boolean DUMP_ON_ERROR = true;
 
     /** Pass to {@link #setScreenOrientation(int)} to change the display to portrait mode */
@@ -847,4 +851,18 @@
             assertWithMessage("Shouldn't find child with id '%s'", childId).that(child).isNull();
         }
     }
+
+    /**
+     * Waits until the window was split to show multiple activities.
+     */
+    public void waitForWindowSplit() throws Exception {
+        try {
+            assertShownById(SPLIT_WINDOW_DIVIDER_ID);
+        } catch (Exception e) {
+            final long timeout = Timeouts.ACTIVITY_RESURRECTION.ms();
+            Log.e(TAG, "Did not find window divider " + SPLIT_WINDOW_DIVIDER_ID + "; waiting "
+                    + timeout + "ms instead");
+            SystemClock.sleep(timeout);
+        }
+    }
 }
diff --git a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
index cce6171..47020ed 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RobustnessTest.java
@@ -2010,15 +2010,20 @@
                     case RAW: {
                         Size targetSize = (numConfigs == 1) ? maxSizes.maxRawSize :
                                 overridePhysicalCameraSizes.get(j);
-                        ImageReader target = ImageReader.newInstance(
-                            targetSize.getWidth(), targetSize.getHeight(), RAW, numBuffers);
-                        target.setOnImageAvailableListener(imageDropperListener, mHandler);
-                        OutputConfiguration config = new OutputConfiguration(target.getSurface());
-                        if (numConfigs > 1) {
-                            config.setPhysicalCameraId(overridePhysicalCameraIds.get(j));
+                        // targetSize could be null in the logical camera case where only
+                        // physical camera supports RAW stream.
+                        if (targetSize != null) {
+                            ImageReader target = ImageReader.newInstance(
+                                targetSize.getWidth(), targetSize.getHeight(), RAW, numBuffers);
+                            target.setOnImageAvailableListener(imageDropperListener, mHandler);
+                            OutputConfiguration config =
+                                    new OutputConfiguration(target.getSurface());
+                            if (numConfigs > 1) {
+                                config.setPhysicalCameraId(overridePhysicalCameraIds.get(j));
+                            }
+                            outputConfigs.add(config);
+                            rawTargets.add(target);
                         }
-                        outputConfigs.add(config);
-                        rawTargets.add(target);
                         break;
                     }
                     default:
diff --git a/tests/core/runner/Android.bp b/tests/core/runner/Android.bp
new file mode 100644
index 0000000..de3d724
--- /dev/null
+++ b/tests/core/runner/Android.bp
@@ -0,0 +1,48 @@
+// Copyright (C) 2009 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//==========================================================
+// Build the core runner.
+//==========================================================
+
+// Build library
+java_library {
+    name: "cts-core-test-runner",
+
+    srcs: ["src/**/*.java"],
+    static_libs: [
+        "compatibility-device-util",
+        "android-support-test",
+        "vogarexpect",
+        "testng",
+    ],
+
+    libs: ["android.test.runner.stubs"],
+    sdk_version: "test_current",
+
+}
+
+//==========================================================
+// Build the run listener
+//==========================================================
+
+// Build library
+java_library {
+    name: "cts-test-runner",
+
+    srcs: ["src/com/android/cts/runner/**/*.java"],
+    static_libs: ["android-support-test"],
+    sdk_version: "current",
+
+}
diff --git a/tests/core/runner/Android.mk b/tests/core/runner/Android.mk
deleted file mode 100644
index e2d5047..0000000
--- a/tests/core/runner/Android.mk
+++ /dev/null
@@ -1,51 +0,0 @@
-# Copyright (C) 2009 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT 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)
-
-#==========================================================
-# Build the core runner.
-#==========================================================
-
-# Build library
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := $(call all-java-files-under,src)
-LOCAL_MODULE := cts-core-test-runner
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util \
-    android-support-test \
-    vogarexpect \
-    testng
-
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-#==========================================================
-# Build the run listener
-#==========================================================
-
-# Build library
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := $(call all-java-files-under,src/com/android/cts/runner)
-LOCAL_MODULE := cts-test-runner
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/tests/framework/base/activitymanager/app/Android.bp b/tests/framework/base/activitymanager/app/Android.bp
new file mode 100644
index 0000000..41557b4
--- /dev/null
+++ b/tests/framework/base/activitymanager/app/Android.bp
@@ -0,0 +1,18 @@
+// 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.
+
+filegroup {
+    name: "cts-amwm-components",
+    srcs: ["**/Components.java"],
+}
diff --git a/tests/framework/base/activitymanager/app_base/Android.bp b/tests/framework/base/activitymanager/app_base/Android.bp
new file mode 100644
index 0000000..437e8c5
--- /dev/null
+++ b/tests/framework/base/activitymanager/app_base/Android.bp
@@ -0,0 +1,18 @@
+// 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.
+
+filegroup {
+    name: "cts-amwm-components-base",
+    srcs: ["**/ComponentsBase.java"],
+}
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAppConfigurationTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAppConfigurationTests.java
index 44281b2..0d09a2d 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAppConfigurationTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerAppConfigurationTests.java
@@ -526,6 +526,7 @@
         // Request portrait
         executeShellCommand(REQUEST_PORTRAIT_BROADCAST);
         mAmWmState.waitForLastOrientation(SCREEN_ORIENTATION_PORTRAIT);
+        waitForBroadcastActivityReady(SCREEN_ORIENTATION_PORTRAIT);
 
         // Finish activity
         executeShellCommand(FINISH_ACTIVITY_BROADCAST);
@@ -553,6 +554,7 @@
         launchActivityInNewTask(BROADCAST_RECEIVER_ACTIVITY);
         executeShellCommand(REQUEST_LANDSCAPE_BROADCAST);
         mAmWmState.waitForLastOrientation(SCREEN_ORIENTATION_LANDSCAPE);
+        waitForBroadcastActivityReady(SCREEN_ORIENTATION_LANDSCAPE);
         executeShellCommand(FINISH_ACTIVITY_BROADCAST);
 
         // Verify that activity brought to front is in originally requested orientation.
@@ -570,6 +572,7 @@
         launchActivityInNewTask(BROADCAST_RECEIVER_ACTIVITY);
         executeShellCommand(REQUEST_PORTRAIT_BROADCAST);
         mAmWmState.waitForLastOrientation(SCREEN_ORIENTATION_PORTRAIT);
+        waitForBroadcastActivityReady(SCREEN_ORIENTATION_PORTRAIT);
         executeShellCommand(FINISH_ACTIVITY_BROADCAST);
 
         // Verify that activity brought to front is in originally requested orientation.
@@ -694,6 +697,7 @@
         // Request portrait
         executeShellCommand(REQUEST_PORTRAIT_BROADCAST);
         mAmWmState.waitForLastOrientation(SCREEN_ORIENTATION_PORTRAIT);
+        waitForBroadcastActivityReady(SCREEN_ORIENTATION_PORTRAIT);
 
         // Finish activity
         executeShellCommand(MOVE_TASK_TO_BACK_BROADCAST);
@@ -883,6 +887,11 @@
         return display.getDisplayRect();
     }
 
+    private void waitForBroadcastActivityReady(int orientation) {
+        mAmWmState.waitForActivityOrientation(BROADCAST_RECEIVER_ACTIVITY, orientation);
+        mAmWmState.waitForActivityState(BROADCAST_RECEIVER_ACTIVITY, STATE_RESUMED);
+    }
+
     /**
      * Test launching an activity which requests specific UI mode during creation.
      */
diff --git a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerFreeformStackTests.java b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerFreeformStackTests.java
index 4a3370f..73b3988 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerFreeformStackTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/ActivityManagerFreeformStackTests.java
@@ -115,18 +115,22 @@
                 ActivityAndWindowManagersState.dpToPx(TEST_TASK_SIZE_DP_2, densityDpi);
 
         resizeActivityTask(TEST_ACTIVITY,
-                TEST_TASK_OFFSET, TEST_TASK_OFFSET, testTaskSize1, testTaskSize2);
+                TEST_TASK_OFFSET, TEST_TASK_OFFSET,
+                TEST_TASK_OFFSET + testTaskSize1, TEST_TASK_OFFSET + testTaskSize2);
         resizeActivityTask(NO_RELAUNCH_ACTIVITY,
-                TEST_TASK_OFFSET_2, TEST_TASK_OFFSET_2, testTaskSize1, testTaskSize2);
+                TEST_TASK_OFFSET_2, TEST_TASK_OFFSET_2,
+                TEST_TASK_OFFSET_2 + testTaskSize1, TEST_TASK_OFFSET_2 + testTaskSize2);
 
         mAmWmState.computeState(new WaitForValidActivityState.Builder(TEST_ACTIVITY).build(),
                 new WaitForValidActivityState.Builder(NO_RELAUNCH_ACTIVITY).build());
 
         final LogSeparator logSeparator = separateLogs();
         resizeActivityTask(TEST_ACTIVITY,
-                TEST_TASK_OFFSET, TEST_TASK_OFFSET, testTaskSize2, testTaskSize1);
+                TEST_TASK_OFFSET, TEST_TASK_OFFSET,
+                TEST_TASK_OFFSET + testTaskSize2, TEST_TASK_OFFSET + testTaskSize1);
         resizeActivityTask(NO_RELAUNCH_ACTIVITY,
-                TEST_TASK_OFFSET_2, TEST_TASK_OFFSET_2, testTaskSize2, testTaskSize1);
+                TEST_TASK_OFFSET_2, TEST_TASK_OFFSET_2,
+                TEST_TASK_OFFSET_2 + testTaskSize2, TEST_TASK_OFFSET_2 + testTaskSize1);
         mAmWmState.computeState(TEST_ACTIVITY, NO_RELAUNCH_ACTIVITY);
 
         assertActivityLifecycle(TEST_ACTIVITY, true /* relaunched */, logSeparator);
diff --git a/tests/framework/base/activitymanager/src/android/server/am/AnimationBackgroundTests.java b/tests/framework/base/activitymanager/src/android/server/am/AnimationBackgroundTests.java
index 563ce91..8022c87 100644
--- a/tests/framework/base/activitymanager/src/android/server/am/AnimationBackgroundTests.java
+++ b/tests/framework/base/activitymanager/src/android/server/am/AnimationBackgroundTests.java
@@ -16,6 +16,7 @@
 
 package android.server.am;
 
+import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.server.am.Components.ANIMATION_TEST_ACTIVITY;
 import static android.server.am.Components.LAUNCHING_ACTIVITY;
@@ -23,6 +24,10 @@
 
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeFalse;
+
+import android.content.ComponentName;
+import android.server.am.WindowManagerState.Display;
 
 import org.junit.Test;
 
@@ -40,11 +45,16 @@
                 .setWaitForLaunched(false)
                 .execute();
 
+        // Make sure we're testing an activity that runs on fullscreen display. This animation API
+        // doesn't make much sense in freeform displays.
+        assumeActivityNotInFreeformDisplay(ANIMATION_TEST_ACTIVITY);
+
         // Make sure we are in the middle of the animation.
         mAmWmState.waitForWithWmState(state -> state
                 .getStandardStackByWindowingMode(WINDOWING_MODE_FULLSCREEN)
                         .isWindowAnimationBackgroundSurfaceShowing(),
                 "***Waiting for animation background showing");
+
         assertTrue("window animation background needs to be showing", mAmWmState.getWmState()
                 .getStandardStackByWindowingMode(WINDOWING_MODE_FULLSCREEN)
                 .isWindowAnimationBackgroundSurfaceShowing());
@@ -56,8 +66,21 @@
         getLaunchActivityBuilder().setTargetActivity(ANIMATION_TEST_ACTIVITY).execute();
         mAmWmState.computeState(ANIMATION_TEST_ACTIVITY);
         mAmWmState.waitForAppTransitionIdle();
+
+        // Make sure we're testing an activity that runs on fullscreen display. This animation API
+        // doesn't make much sense in freeform displays.
+        assumeActivityNotInFreeformDisplay(ANIMATION_TEST_ACTIVITY);
+
         assertFalse("window animation background needs to be gone", mAmWmState.getWmState()
                 .getStandardStackByWindowingMode(WINDOWING_MODE_FULLSCREEN)
                 .isWindowAnimationBackgroundSurfaceShowing());
     }
+
+    private void assumeActivityNotInFreeformDisplay(ComponentName activity) throws Exception {
+        mAmWmState.waitForValidState(activity);
+        final int displayId = mAmWmState.getAmState().getDisplayByActivity(activity);
+        final Display display = mAmWmState.getWmState().getDisplay(displayId);
+        assumeFalse("Animation test activity is in freeform display. It may not run "
+                + "cross-task animations.", display.getWindowingMode() == WINDOWING_MODE_FREEFORM);
+    }
 }
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 a381d04..9903653 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
@@ -152,6 +152,10 @@
 
         getLifecycleLog().clear();
         try (final RotationSession rotationSession = new RotationSession()) {
+            if (!supportsLockedUserRotation(
+                    rotationSession, translucentActivity.getDisplay().getDisplayId())) {
+                return;
+            }
             final int current = rotationSession.get();
             // Set new rotation to cause a configuration change.
             switch (current) {
diff --git a/tests/framework/base/activitymanager/util/Android.bp b/tests/framework/base/activitymanager/util/Android.bp
new file mode 100644
index 0000000..f71603b
--- /dev/null
+++ b/tests/framework/base/activitymanager/util/Android.bp
@@ -0,0 +1,31 @@
+// Copyright (C) 2012 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+java_test {
+    name: "cts-amwm-util",
+
+    srcs: [
+        "src/**/*.java",
+        ":cts-amwm-components",
+        ":cts-amwm-components-base",
+    ],
+
+    static_libs: [
+        "platformprotosnano",
+        "compatibility-device-util",
+        "android-support-test",
+    ],
+
+    sdk_version: "test_current",
+}
diff --git a/tests/framework/base/activitymanager/util/Android.mk b/tests/framework/base/activitymanager/util/Android.mk
deleted file mode 100644
index 22dfa02..0000000
--- a/tests/framework/base/activitymanager/util/Android.mk
+++ /dev/null
@@ -1,37 +0,0 @@
-# Copyright (C) 2012 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests optional
-
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under, src) \
-    $(call all-named-files-under,Components.java, ../app) \
-    $(call all-named-files-under,ComponentsBase.java, ../app_base)
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    platformprotosnano \
-    compatibility-device-util \
-    android-support-test
-
-LOCAL_MODULE := cts-amwm-util
-
-LOCAL_SDK_VERSION := test_current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tests/framework/base/activitymanager/util/src/android/server/am/ActivityAndWindowManagersState.java b/tests/framework/base/activitymanager/util/src/android/server/am/ActivityAndWindowManagersState.java
index fe1f588..f503f98 100644
--- a/tests/framework/base/activitymanager/util/src/android/server/am/ActivityAndWindowManagersState.java
+++ b/tests/framework/base/activitymanager/util/src/android/server/am/ActivityAndWindowManagersState.java
@@ -269,6 +269,19 @@
                 "***Waiting for LastOrientation: " + orientation);
     }
 
+    /**
+     * Wait for orientation for the Activity
+     */
+    void waitForActivityOrientation(ComponentName activityName, int orientation) {
+        waitForWithAmState(amState -> {
+            final ActivityTask task = amState.getTaskByActivity(activityName);
+            if (task == null) {
+                return false;
+            }
+            return task.mFullConfiguration.orientation == orientation;
+        }, "***Waiting for Activity orientation: " + orientation);
+    }
+
     void waitForDisplayUnfrozen() {
         waitForWithWmState(state -> !state.isDisplayFrozen(),
                 "***Waiting for Display unfrozen");
diff --git a/tests/jdwp/runner/host-side/Android.mk b/tests/jdwp/runner/host-side/Android.mk
index 32abf79..5fb12a2 100644
--- a/tests/jdwp/runner/host-side/Android.mk
+++ b/tests/jdwp/runner/host-side/Android.mk
@@ -22,7 +22,7 @@
 
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
 
-LOCAL_STATIC_JAVA_LIBRARIES := vogarexpectlib
+LOCAL_STATIC_JAVA_LIBRARIES := vogarexpect
 
 # don't include these packages in any target
 LOCAL_MODULE_TAGS := optional
diff --git a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
index 324df40..9f545dd 100644
--- a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
+++ b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
@@ -55,6 +55,7 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
@@ -142,11 +143,11 @@
 
     @Option(name = "include-filter",
             description = "The include filters of the test name to run.")
-    private List<String> mIncludeFilters = new ArrayList<>();
+    private Set<String> mIncludeFilters = new LinkedHashSet<>();
 
     @Option(name = "exclude-filter",
             description = "The exclude filters of the test name to run.")
-    private List<String> mExcludeFilters = new ArrayList<>();
+    private Set<String> mExcludeFilters = new LinkedHashSet<>();
 
     @Option(name = "test-file-include-filter",
             description="A file containing a list of line separated test classes and optionally"
@@ -266,6 +267,38 @@
      * {@inheritDoc}
      */
     @Override
+    public Set<String> getIncludeFilters() {
+        return mIncludeFilters;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public Set<String> getExcludeFilters() {
+        return mExcludeFilters;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void clearIncludeFilters() {
+        mIncludeFilters.clear();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    public void clearExcludeFilters() {
+        mExcludeFilters.clear();
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
     public void setIncludeTestFile(File testFile) {
         mIncludeTestFile = testFile;
     }
diff --git a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/LibcoreTest.java b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/LibcoreTest.java
index cc03798..f4021b2 100644
--- a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/LibcoreTest.java
+++ b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/LibcoreTest.java
@@ -18,6 +18,7 @@
 
 import com.android.tradefed.config.Option;
 import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.result.ITestInvocationListener;
 import com.android.tradefed.testtype.AndroidJUnitTest;
 import com.android.tradefed.util.ArrayUtil;
@@ -48,6 +49,16 @@
         if (!mCoreExpectations.isEmpty()) {
             addInstrumentationArg(INSTRUMENTATION_ARG_NAME, ArrayUtil.join(",", mCoreExpectations));
         }
+
+        if (getTestPackageName() != null && getClassName() != null) {
+            // If the test-package is set, we should ignore --class, --method it might cause issue
+            // in more complex libcore suites.
+            setClassName(null);
+            setMethodName(null);
+            CLog.d(
+                    "Setting --class and --method to null to avoid conflict with --test-package "
+                            + "option.");
+        }
         super.run(listener);
     }
 }
diff --git a/tests/vm/Android.mk b/tests/libcore/coreplatformapi/Android.mk
old mode 100755
new mode 100644
similarity index 72%
copy from tests/vm/Android.mk
copy to tests/libcore/coreplatformapi/Android.mk
index 2f70271..9dd2f17
--- a/tests/vm/Android.mk
+++ b/tests/libcore/coreplatformapi/Android.mk
@@ -1,4 +1,4 @@
-# Copyright (C) 2015 The Android Open Source Project
+# 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.
@@ -16,11 +16,16 @@
 
 include $(CLEAR_VARS)
 
-# b/110155920
-LOCAL_ERROR_PRONE_FLAGS := -Xep:ConstantOverflow:OFF
+LOCAL_PACKAGE_NAME := CtsLibcoreCorePlatformApiTestCases
+LOCAL_PRIVATE_PLATFORM_APIS := true
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    cts-core-test-runner \
+    core-platform-api-test
 
 # Don't include this package in any target
 LOCAL_MODULE_TAGS := tests
+
 # When built, explicitly put it in the data partition.
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
@@ -28,15 +33,7 @@
 
 LOCAL_PROGUARD_ENABLED := disabled
 
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util android-support-test
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_PACKAGE_NAME := CtsVmTestCases
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_CTS_PACKAGE)
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/vm/AndroidManifest.xml b/tests/libcore/coreplatformapi/AndroidManifest.xml
old mode 100755
new mode 100644
similarity index 72%
copy from tests/vm/AndroidManifest.xml
copy to tests/libcore/coreplatformapi/AndroidManifest.xml
index cbd2c90..6b582a8
--- a/tests/vm/AndroidManifest.xml
+++ b/tests/libcore/coreplatformapi/AndroidManifest.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
- * Copyright (C) 2015 The Android Open Source Project
+ * 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.
@@ -16,17 +16,16 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.vm.cts">
+    package="android.libcore.cts.coreplatformapi"
+    android:targetSandboxVersion="2">
 
-    <application>
+    <application android:usesCleartextTraffic="true">
         <uses-library android:name="android.test.runner" />
     </application>
 
-    <!--  self-instrumenting test package. -->
     <instrumentation
         android:name="android.support.test.runner.AndroidJUnitRunner"
-        android:label="CTS VM test cases"
-        android:targetPackage="android.vm.cts" >
+        android:label="CTS Libcore core platform API test cases"
+        android:targetPackage="android.libcore.cts.coreplatformapi">
     </instrumentation>
 </manifest>
-
diff --git a/tests/vm/AndroidTest.xml b/tests/libcore/coreplatformapi/AndroidTest.xml
similarity index 69%
copy from tests/vm/AndroidTest.xml
copy to tests/libcore/coreplatformapi/AndroidTest.xml
index 4035349..907fb2d 100644
--- a/tests/vm/AndroidTest.xml
+++ b/tests/libcore/coreplatformapi/AndroidTest.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2015 The Android Open Source Project
+<!-- 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.
@@ -13,15 +13,16 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Config for CTS VM test cases">
+<configuration description="Config for CTS Libcore core platform API test cases">
     <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="art" />
+    <option name="config-descriptor:metadata" key="component" value="libcore" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsVmTestCases.apk" />
+        <option name="test-file-name" value="CtsLibcoreCorePlatformApiTestCases.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
-        <option name="package" value="android.vm.cts" />
-        <option name="runtime-hint" value="20m14s" />
+        <option name="package" value="android.libcore.cts.coreplatformapi" />
+        <option name="runtime-hint" value="1m"/>
+        <option name="hidden-api-checks" value="false"/>
     </test>
 </configuration>
diff --git a/tests/vm/Android.mk b/tests/libcore/simplemmodule/Android.mk
old mode 100755
new mode 100644
similarity index 72%
rename from tests/vm/Android.mk
rename to tests/libcore/simplemmodule/Android.mk
index 2f70271..2e6adc1
--- a/tests/vm/Android.mk
+++ b/tests/libcore/simplemmodule/Android.mk
@@ -1,4 +1,4 @@
-# Copyright (C) 2015 The Android Open Source Project
+# 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.
@@ -16,11 +16,17 @@
 
 include $(CLEAR_VARS)
 
-# b/110155920
-LOCAL_ERROR_PRONE_FLAGS := -Xep:ConstantOverflow:OFF
+LOCAL_PACKAGE_NAME := CtsLibcoreSimpleMModuleTestCases
+LOCAL_PRIVATE_PLATFORM_APIS := true
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+    cts-core-test-runner \
+    core-libart+oj-intra-test \
+    core-simple-intra-test
 
 # Don't include this package in any target
 LOCAL_MODULE_TAGS := tests
+
 # When built, explicitly put it in the data partition.
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
@@ -28,15 +34,7 @@
 
 LOCAL_PROGUARD_ENABLED := disabled
 
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util android-support-test
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_PACKAGE_NAME := CtsVmTestCases
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_CTS_PACKAGE)
+include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/vm/AndroidManifest.xml b/tests/libcore/simplemmodule/AndroidManifest.xml
old mode 100755
new mode 100644
similarity index 73%
rename from tests/vm/AndroidManifest.xml
rename to tests/libcore/simplemmodule/AndroidManifest.xml
index cbd2c90..ed825b3
--- a/tests/vm/AndroidManifest.xml
+++ b/tests/libcore/simplemmodule/AndroidManifest.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!--
- * Copyright (C) 2015 The Android Open Source Project
+ * 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.
@@ -16,17 +16,16 @@
  -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.vm.cts">
+    package="android.libcore.cts.simplemmodule"
+    android:targetSandboxVersion="2">
 
-    <application>
+    <application android:usesCleartextTraffic="true">
         <uses-library android:name="android.test.runner" />
     </application>
 
-    <!--  self-instrumenting test package. -->
     <instrumentation
         android:name="android.support.test.runner.AndroidJUnitRunner"
-        android:label="CTS VM test cases"
-        android:targetPackage="android.vm.cts" >
+        android:label="CTS Libcore simple mmodule test cases"
+        android:targetPackage="android.libcore.cts.simplemmodule">
     </instrumentation>
 </manifest>
-
diff --git a/tests/vm/AndroidTest.xml b/tests/libcore/simplemmodule/AndroidTest.xml
similarity index 69%
copy from tests/vm/AndroidTest.xml
copy to tests/libcore/simplemmodule/AndroidTest.xml
index 4035349..5eb0586 100644
--- a/tests/vm/AndroidTest.xml
+++ b/tests/libcore/simplemmodule/AndroidTest.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2015 The Android Open Source Project
+<!-- 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.
@@ -13,15 +13,16 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Config for CTS VM test cases">
+<configuration description="Config for CTS Libcore simple mmodule test cases">
     <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="art" />
+    <option name="config-descriptor:metadata" key="component" value="libcore" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsVmTestCases.apk" />
+        <option name="test-file-name" value="CtsLibcoreSimpleMModuleTestCases.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
-        <option name="package" value="android.vm.cts" />
-        <option name="runtime-hint" value="20m14s" />
+        <option name="package" value="android.libcore.cts.simplemmodule" />
+        <option name="runtime-hint" value="1m"/>
+        <option name="hidden-api-checks" value="false"/>
     </test>
 </configuration>
diff --git a/tests/mocking/Android.mk b/tests/mocking/Android.mk
index 2afa4d2..13f74fe 100644
--- a/tests/mocking/Android.mk
+++ b/tests/mocking/Android.mk
@@ -23,10 +23,8 @@
 LOCAL_STATIC_JAVA_LIBRARIES = \
     mockito-target \
     android-support-test \
-    ctstestrunner
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under, \
-            ../../../external/dexmaker/dexmaker-mockito-tests/src/androidTest/java)
+    ctstestrunner \
+    dexmaker-mockmaker-tests
 LOCAL_COMPATIBILITY_SUITE := \
     cts vts general-tests
 LOCAL_PACKAGE_NAME := \
diff --git a/tests/mocking/AndroidTest.xml b/tests/mocking/AndroidTest.xml
index 9e53939..c6e4ffe 100644
--- a/tests/mocking/AndroidTest.xml
+++ b/tests/mocking/AndroidTest.xml
@@ -25,6 +25,6 @@
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.mocking.cts" />
-        <option name="runtime-hint" value="5s" />
+        <option name="runtime-hint" value="120s" />
     </test>
 </configuration>
diff --git a/tests/mocking/debuggable/Android.mk b/tests/mocking/debuggable/Android.mk
index 5187811..e72f69f 100644
--- a/tests/mocking/debuggable/Android.mk
+++ b/tests/mocking/debuggable/Android.mk
@@ -23,10 +23,8 @@
 LOCAL_STATIC_JAVA_LIBRARIES = \
     mockito-target \
     android-support-test \
-    ctstestrunner
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under, \
-            ../../../../external/dexmaker/dexmaker-mockito-tests/src/androidTest/java)
+    ctstestrunner \
+    dexmaker-mockmaker-tests
 LOCAL_COMPATIBILITY_SUITE := \
     cts vts general-tests
 LOCAL_PACKAGE_NAME := \
diff --git a/tests/mocking/debuggable/AndroidTest.xml b/tests/mocking/debuggable/AndroidTest.xml
index 135de46..645f2a2 100644
--- a/tests/mocking/debuggable/AndroidTest.xml
+++ b/tests/mocking/debuggable/AndroidTest.xml
@@ -26,6 +26,6 @@
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.mocking.cts.debuggable" />
-        <option name="runtime-hint" value="5s" />
+        <option name="runtime-hint" value="120s" />
     </test>
 </configuration>
diff --git a/tests/mocking/extended/Android.mk b/tests/mocking/extended/Android.mk
new file mode 100644
index 0000000..3fee499
--- /dev/null
+++ b/tests/mocking/extended/Android.mk
@@ -0,0 +1,44 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := \
+    tests
+LOCAL_JAVA_LIBRARIES := \
+    android.test.runner.stubs
+LOCAL_STATIC_JAVA_LIBRARIES = \
+    mockito-target-extended \
+    android-support-test \
+    ctstestrunner \
+    dexmaker-mockmaker-tests \
+    dexmaker-inline-mockmaker-tests \
+    dexmaker-extended-mockmaker-tests \
+    android-support-v4
+LOCAL_MULTILIB := \
+    both
+LOCAL_JNI_SHARED_LIBRARIES := \
+    libdexmakerjvmtiagent \
+    libmultiplejvmtiagentsinterferenceagent \
+    libstaticjvmtiagent
+LOCAL_COMPATIBILITY_SUITE := \
+    cts vts general-tests
+LOCAL_PACKAGE_NAME := \
+    CtsExtendedMockingTestCases
+LOCAL_SDK_VERSION := \
+    current
+include $(BUILD_CTS_PACKAGE)
+
diff --git a/tests/mocking/extended/AndroidManifest.xml b/tests/mocking/extended/AndroidManifest.xml
new file mode 100644
index 0000000..f62d95f
--- /dev/null
+++ b/tests/mocking/extended/AndroidManifest.xml
@@ -0,0 +1,37 @@
+<?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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.extended.mocking.cts">
+
+    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+
+        <activity android:name="com.android.dx.mockito.inline.extended.tests.EmptyActivity" />
+    </application>
+
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.extended.mocking.cts"
+                     android:label="CTS tests for mockito extended mocking">
+        <meta-data android:name="listener"
+            android:value="com.android.cts.runner.CtsTestRunListener" />
+    </instrumentation>
+
+</manifest>
+
diff --git a/tests/mocking/extended/AndroidTest.xml b/tests/mocking/extended/AndroidTest.xml
new file mode 100644
index 0000000..5fcd077
--- /dev/null
+++ b/tests/mocking/extended/AndroidTest.xml
@@ -0,0 +1,34 @@
+<?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 Mockito extended mocking test cases">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="mocking" />
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsExtendedMockingTestCases.apk" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.extended.mocking.cts" />
+        <option name="runtime-hint" value="120s" />
+    </test>
+
+    <!-- Controller that will skip the module if a native bridge situation is detected -->
+    <!-- For example: module wants to run arm32 and device is x86 -->
+    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.NativeBridgeModuleController" />
+</configuration>
diff --git a/tests/mocking/inline/Android.mk b/tests/mocking/inline/Android.mk
index 9fa873d..67b4fb4 100644
--- a/tests/mocking/inline/Android.mk
+++ b/tests/mocking/inline/Android.mk
@@ -23,15 +23,15 @@
 LOCAL_STATIC_JAVA_LIBRARIES = \
     mockito-target-inline \
     android-support-test \
-    ctstestrunner
+    ctstestrunner \
+    dexmaker-mockmaker-tests \
+    dexmaker-inline-mockmaker-tests \
+    android-support-v4
 LOCAL_MULTILIB := \
     both
 LOCAL_JNI_SHARED_LIBRARIES := \
     libdexmakerjvmtiagent \
     libmultiplejvmtiagentsinterferenceagent
-LOCAL_SRC_FILES := \
-    $(call all-java-files-under, \
-            ../../../../external/dexmaker/dexmaker-mockito-inline-tests/src/androidTest/java)
 LOCAL_COMPATIBILITY_SUITE := \
     cts vts general-tests
 LOCAL_PACKAGE_NAME := \
diff --git a/tests/mocking/inline/AndroidTest.xml b/tests/mocking/inline/AndroidTest.xml
index 7158dcb..f7b51fb 100644
--- a/tests/mocking/inline/AndroidTest.xml
+++ b/tests/mocking/inline/AndroidTest.xml
@@ -25,7 +25,7 @@
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.inline.mocking.cts" />
-        <option name="runtime-hint" value="30s" />
+        <option name="runtime-hint" value="120s" />
     </test>
 
     <!-- Controller that will skip the module if a native bridge situation is detected -->
diff --git a/tests/signature/api/Android.mk b/tests/signature/api/Android.mk
index f4f1575..00fbecb 100644
--- a/tests/signature/api/Android.mk
+++ b/tests/signature/api/Android.mk
@@ -39,9 +39,9 @@
 $(eval $(call build_xml_api_file,current.api,frameworks/base/api/current.txt))
 $(eval $(call build_xml_api_file,system-current.api,frameworks/base/api/system-current.txt))
 $(eval $(call build_xml_api_file,system-removed.api,frameworks/base/api/system-removed.txt))
-$(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,android-test-base-current.api,frameworks/base/test-base/api/current.txt))
+$(eval $(call build_xml_api_file,android-test-mock-current.api,frameworks/base/test-mock/api/current.txt))
+$(eval $(call build_xml_api_file,android-test-runner-current.api,frameworks/base/test-runner/api/current.txt))
 $(foreach ver,$(PLATFORM_SYSTEMSDK_VERSIONS),\
   $(if $(call math_is_number,$(ver)),\
     $(eval $(call build_xml_api_file,system-$(ver).api,prebuilts/sdk/$(ver)/system/api/android.txt))\
diff --git a/tests/signature/src/android/signature/cts/DexApiDocumentParser.java b/tests/signature/src/android/signature/cts/DexApiDocumentParser.java
index c199bc0..58be322 100644
--- a/tests/signature/src/android/signature/cts/DexApiDocumentParser.java
+++ b/tests/signature/src/android/signature/cts/DexApiDocumentParser.java
@@ -46,10 +46,11 @@
         private final BufferedReader mReader;
         private int mLineNum;
 
-        private static final Pattern REGEX_CLASS = Pattern.compile("^L[^->]*;$");
-        private static final Pattern REGEX_FIELD = Pattern.compile("^(L[^->]*;)->(.*):(.*)$");
+        // Regex patterns which match DEX signatures of methods and fields.
+        // See comment by next() for more details.
+        private static final Pattern REGEX_FIELD = Pattern.compile("^(L[^>]*;)->(.*):(.*)$");
         private static final Pattern REGEX_METHOD =
-                Pattern.compile("^(L[^->]*;)->(.*)(\\(.*\\).*)$");
+                Pattern.compile("^(L[^>]*;)->(.*)(\\(.*\\).*)$");
 
         DexApiSpliterator(BufferedReader reader) {
             mReader = reader;
@@ -87,15 +88,12 @@
         }
 
         /**
-         * Parses lines of DEX signatures from `mReader`. The following three
+         * Parses lines of DEX signatures from `mReader`. The following two
          * line formats are supported:
-         * 1) [class descriptor]
-         *      - e.g. Lcom/example/MyClass;
-         *      - these lines are ignored
-         * 2) [class descriptor]->[field name]:[field type]
+         * 1) [class descriptor]->[field name]:[field type]
          *      - e.g. Lcom/example/MyClass;->myField:I
          *      - these lines are parsed as field signatures
-         * 3) [class descriptor]->[method name]([method parameter types])[method return type]
+         * 2) [class descriptor]->[method name]([method parameter types])[method return type]
          *      - e.g. Lcom/example/MyClass;->myMethod(Lfoo;Lbar;)J
          *      - these lines are parsed as method signatures
          */
@@ -112,13 +110,11 @@
                 mLineNum = mLineNum + 1;
 
                 // Match line against regex patterns.
-                Matcher matchClass = REGEX_CLASS.matcher(line);
                 Matcher matchField = REGEX_FIELD.matcher(line);
                 Matcher matchMethod = REGEX_METHOD.matcher(line);
 
                 // Check that *exactly* one pattern matches.
-                int matchCount = (matchClass.matches() ? 1 : 0) + (matchField.matches() ? 1 : 0) +
-                        (matchMethod.matches() ? 1 : 0);
+                int matchCount = (matchField.matches() ? 1 : 0) + (matchMethod.matches() ? 1 : 0);
                 if (matchCount == 0) {
                     throw new ParseException("Could not parse: \"" + line + "\"", mLineNum);
                 } else if (matchCount > 1) {
@@ -126,10 +122,7 @@
                 }
 
                 // Extract information from the line.
-                if (matchClass.matches()) {
-                    // We ignore lines describing a class because classes are
-                    // not being hidden.
-                } else if (matchField.matches()) {
+                if (matchField.matches()) {
                     return new DexField(
                             matchField.group(1), matchField.group(2), matchField.group(3));
                 } else if (matchMethod.matches()) {
diff --git a/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java b/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
index cbf0a2f..2bb7dee 100644
--- a/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
+++ b/tests/tests/appwidget/src/android/appwidget/cts/AppWidgetTest.java
@@ -314,12 +314,12 @@
             inOrder.verify(callbacks).onUpdate(any(Context.class),
                     any(AppWidgetManager.class), eq(new int[] {firstAppWidgetId}));
             inOrder.verify(callbacks).onAppWidgetOptionsChanged(any(Context.class),
-                    any(AppWidgetManager.class), same(firstAppWidgetId), argThat(
+                    any(AppWidgetManager.class), eq(firstAppWidgetId), argThat(
                             new OptionsMatcher(firstOptions)));
             inOrder.verify(callbacks).onUpdate(any(Context.class),
                     any(AppWidgetManager.class), eq(new int[] {secondAppWidgetId}));
             inOrder.verify(callbacks).onAppWidgetOptionsChanged(any(Context.class),
-                    any(AppWidgetManager.class), same(secondAppWidgetId), argThat(
+                    any(AppWidgetManager.class), eq(secondAppWidgetId), argThat(
                             new OptionsMatcher(secondOptions)));
             inOrder.verify(callbacks).onDeleted(any(Context.class),
                     argThat(new WidgetIdsMatcher(new int[]{firstAppWidgetId})));
diff --git a/tests/vm/Android.mk b/tests/tests/binder_ndk/Android.mk
old mode 100755
new mode 100644
similarity index 69%
copy from tests/vm/Android.mk
copy to tests/tests/binder_ndk/Android.mk
index 2f70271..686bc02
--- a/tests/vm/Android.mk
+++ b/tests/tests/binder_ndk/Android.mk
@@ -1,4 +1,4 @@
-# Copyright (C) 2015 The Android Open Source Project
+# 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.
@@ -12,30 +12,29 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-LOCAL_PATH:= $(call my-dir)
+LOCAL_PATH := $(call my-dir)
 
 include $(CLEAR_VARS)
 
-# b/110155920
-LOCAL_ERROR_PRONE_FLAGS := -Xep:ConstantOverflow:OFF
+LOCAL_PACKAGE_NAME := CtsNdkBinderTestCases
 
-# Don't include this package in any target
-LOCAL_MODULE_TAGS := tests
+# Don't include this package in any target.
+LOCAL_MODULE_TAGS := optional
+
+# Include both the 32 and 64 bit versions
+LOCAL_MULTILIB := both
+
 # When built, explicitly put it in the data partition.
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_DEX_PREOPT := false
-
-LOCAL_PROGUARD_ENABLED := disabled
-
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util android-support-test
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
 
-LOCAL_PACKAGE_NAME := CtsVmTestCases
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestrunner nativetesthelper
+
+LOCAL_JNI_SHARED_LIBRARIES := libbinder_ndk_test
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_SDK_VERSION := current
 
diff --git a/tests/tests/binder_ndk/AndroidManifest.xml b/tests/tests/binder_ndk/AndroidManifest.xml
new file mode 100644
index 0000000..c0efdd8
--- /dev/null
+++ b/tests/tests/binder_ndk/AndroidManifest.xml
@@ -0,0 +1,32 @@
+<?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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.binder.cts">
+
+    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <!-- This is a self-instrumenting test package. -->
+    <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.binder.cts"
+                     android:label="CTS tests of native binder API">
+    </instrumentation>
+
+</manifest>
+
diff --git a/tests/vm/AndroidTest.xml b/tests/tests/binder_ndk/AndroidTest.xml
similarity index 72%
rename from tests/vm/AndroidTest.xml
rename to tests/tests/binder_ndk/AndroidTest.xml
index 4035349..c627392 100644
--- a/tests/vm/AndroidTest.xml
+++ b/tests/tests/binder_ndk/AndroidTest.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2015 The Android Open Source Project
+<!-- 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.
@@ -13,15 +13,16 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Config for CTS VM test cases">
+<configuration description="Config for CTS NDK Binder test cases">
     <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="art" />
+    <option name="config-descriptor:metadata" key="component" value="devtools" />
+    <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsVmTestCases.apk" />
+        <option name="test-file-name" value="CtsNdkBinderTestCases.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
-        <option name="package" value="android.vm.cts" />
-        <option name="runtime-hint" value="20m14s" />
+        <option name="package" value="android.binder.cts" />
+        <option name="runtime-hint" value="0m30s" />
     </test>
 </configuration>
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp b/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp
new file mode 100644
index 0000000..30b96e7
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp
@@ -0,0 +1,37 @@
+// 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.
+
+cc_library_shared {
+    name: "libbinder_ndk_test",
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+
+    srcs: [
+        "android_binder_cts_ibinder.cpp",
+        "android_binder_cts_parcel.cpp",
+        "utilities.cpp",
+    ],
+
+    shared_libs: [
+        "liblog",
+        "libbinder_ndk",
+    ],
+    whole_static_libs: ["libnativetesthelper_jni"],
+
+    sdk_version: "current",
+    stl: "c++_static",
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_ibinder.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_ibinder.cpp
new file mode 100644
index 0000000..f8169b0
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_ibinder.cpp
@@ -0,0 +1,177 @@
+/*
+ * 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 LOG_TAG "Cts-NdkBinderTest"
+
+#include <android/binder_ibinder.h>
+#include <gtest/gtest.h>
+
+#include "utilities.h"
+
+class NdkBinderTest_AIBinder : public NdkBinderTest {};
+
+TEST_F(NdkBinderTest_AIBinder, Destruction) {
+  bool destroyed = false;
+  AIBinder* binder =
+      SampleData::newBinder(nullptr, [&](SampleData*) { destroyed = true; });
+  EXPECT_FALSE(destroyed);
+  AIBinder_incStrong(binder);  // 1 -> 2
+  EXPECT_FALSE(destroyed);
+  AIBinder_decStrong(binder);  // 2 -> 1
+  EXPECT_FALSE(destroyed);
+  AIBinder_decStrong(binder);  // 1 -> 0
+  EXPECT_TRUE(destroyed);
+}
+
+TEST_F(NdkBinderTest_AIBinder, GetClass) {
+  AIBinder* binder = SampleData::newBinder();
+  // class is already set since this local binder is contructed with it
+  EXPECT_EQ(SampleData::kClass, AIBinder_getClass(binder));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, AssociateClass) {
+  AIBinder* binder = SampleData::newBinder();
+  EXPECT_TRUE(AIBinder_associateClass(binder, SampleData::kClass));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, AssociateWrongClassFails) {
+  AIBinder* binder = SampleData::newBinder();
+  EXPECT_FALSE(AIBinder_associateClass(binder, SampleData::kAnotherClass));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, GetUserData) {
+  // This test can't use the helper utility since SampleData isn't exposed
+  SampleData* data = new SampleData;
+  // Takes ownership of data
+  AIBinder* binder = AIBinder_new(SampleData::kClass, static_cast<void*>(data));
+  EXPECT_EQ(data, AIBinder_getUserData(binder));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, DestructionGivesUserData) {
+  // This test can't use the helper utility since SampleData isn't exposed
+  SampleData* destroyedPointer = nullptr;
+  SampleData* data = new SampleData(
+      nullptr, [&](SampleData* data) { destroyedPointer = data; });
+  // Takes ownership of data
+  AIBinder* binder = AIBinder_new(SampleData::kClass, static_cast<void*>(data));
+  EXPECT_EQ(nullptr, destroyedPointer);
+  AIBinder_decStrong(binder);
+
+  // These pointers no longer reference valid memory locations, but the pointers
+  // themselves are valid
+  EXPECT_EQ(data, destroyedPointer);
+}
+
+TEST_F(NdkBinderTest_AIBinder, DebugRefCount) {
+  AIBinder* binder = SampleData::newBinder();
+  EXPECT_EQ(1, AIBinder_debugGetRefCount(binder));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, WeakPointerCanPromote) {
+  AIBinder* binder = SampleData::newBinder();
+  AIBinder_Weak* weak = AIBinder_Weak_new(binder);
+  AIBinder* promoted = AIBinder_Weak_promote(weak);
+  EXPECT_EQ(binder, promoted);
+  AIBinder_Weak_delete(weak);
+  AIBinder_decStrong(binder);
+  AIBinder_decStrong(promoted);
+}
+
+TEST_F(NdkBinderTest_AIBinder, WeakPointerCanNotPromote) {
+  AIBinder* binder = SampleData::newBinder();
+  AIBinder_Weak* weak = AIBinder_Weak_new(binder);
+  AIBinder_decStrong(binder);
+
+  AIBinder* promoted = AIBinder_Weak_promote(weak);
+  EXPECT_EQ(nullptr, promoted);
+}
+
+TEST_F(NdkBinderTest_AIBinder, LocalIsLocal) {
+  AIBinder* binder = SampleData::newBinder();
+  EXPECT_FALSE(AIBinder_isRemote(binder));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, IsAlive) {
+  AIBinder* binder = SampleData::newBinder();
+  EXPECT_TRUE(AIBinder_isAlive(binder));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, CanPing) {
+  AIBinder* binder = SampleData::newBinder();
+  EXPECT_OK(AIBinder_ping(binder));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, TransactionHappens) {
+  AIBinder* binder = SampleData::newBinder(TransactionsReturn(STATUS_OK),
+                                           ExpectLifetimeTransactions(1));
+  EXPECT_OK(SampleData::transact(binder, kCode));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, OnewayTransactionHappens) {
+  AIBinder* binder = SampleData::newBinder(TransactionsReturn(STATUS_OK),
+                                           ExpectLifetimeTransactions(1));
+  EXPECT_OK(SampleData::transact(binder, kCode, WriteNothingToParcel,
+                                 ReadNothingFromParcel, FLAG_ONEWAY));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, TransactionCodeMaintained) {
+  AIBinder* binder = SampleData::newBinder(
+      [&](transaction_code_t code, const AParcel*, AParcel*) {
+        EXPECT_EQ(code, kCode);
+        return STATUS_OK;
+      },
+      ExpectLifetimeTransactions(1));
+  EXPECT_OK(SampleData::transact(binder, kCode));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, TransactionCodeRangeRespected) {
+  AIBinder* binder = SampleData::newBinder(TransactionsReturn(STATUS_OK));
+  EXPECT_OK(SampleData::transact(binder, FIRST_CALL_TRANSACTION));
+  EXPECT_OK(SampleData::transact(binder, FIRST_CALL_TRANSACTION + 1));
+  EXPECT_OK(SampleData::transact(binder, LAST_CALL_TRANSACTION - 1));
+  EXPECT_OK(SampleData::transact(binder, LAST_CALL_TRANSACTION));
+
+  EXPECT_EQ(STATUS_UNKNOWN_TRANSACTION,
+            SampleData::transact(binder, FIRST_CALL_TRANSACTION - 1));
+  EXPECT_EQ(STATUS_UNKNOWN_TRANSACTION,
+            SampleData::transact(binder, LAST_CALL_TRANSACTION + 1));
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, UnknownFlagsRejected) {
+  AIBinder* binder =
+      SampleData::newBinder(nullptr, ExpectLifetimeTransactions(0));
+  EXPECT_EQ(STATUS_BAD_VALUE,
+            SampleData::transact(binder, kCode, WriteNothingToParcel,
+                                 ReadNothingFromParcel, +1 + 415));
+  EXPECT_EQ(STATUS_BAD_VALUE,
+            SampleData::transact(binder, kCode, WriteNothingToParcel,
+                                 ReadNothingFromParcel, FLAG_ONEWAY + 1));
+  EXPECT_EQ(STATUS_BAD_VALUE,
+            SampleData::transact(binder, kCode, WriteNothingToParcel,
+                                 ReadNothingFromParcel, ~0));
+  AIBinder_decStrong(binder);
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_parcel.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_parcel.cpp
new file mode 100644
index 0000000..0b72824
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/android_binder_cts_parcel.cpp
@@ -0,0 +1,154 @@
+/*
+ * 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 LOG_TAG "Cts-NdkBinderTest"
+
+#include <android/binder_ibinder.h>
+#include <android/log.h>
+#include <gtest/gtest.h>
+
+#include "utilities.h"
+
+#include <limits>
+#include <vector>
+
+class NdkBinderTest_AParcel : public NdkBinderTest {};
+
+// These reads and writes an array of possible values all of the same type.
+template <typename T, binder_status_t (*write)(AParcel*, const T),
+          binder_status_t (*read)(const AParcel*, T*)>
+void ExpectInOut(std::vector<T> in) {
+  AIBinder* binder = SampleData::newBinder(
+      [](transaction_code_t, const AParcel* in, AParcel* out) {
+        T readTarget;
+        EXPECT_OK(read(in, &readTarget));
+        EXPECT_OK(write(out, readTarget));
+        return STATUS_OK;
+      },
+      ExpectLifetimeTransactions(in.size()));
+
+  for (const auto& value : in) {
+    EXPECT_OK(SampleData::transact(binder, kCode,
+                                   [&](AParcel* in) {
+                                     EXPECT_OK(write(in, value));
+                                     return STATUS_OK;
+                                   },
+                                   [&](const AParcel* out) {
+                                     T readTarget;
+                                     EXPECT_OK(read(out, &readTarget));
+                                     EXPECT_EQ(value, readTarget);
+                                     return STATUS_OK;
+                                   }));
+  }
+
+  AIBinder_decStrong(binder);
+}
+
+template <typename T, binder_status_t (*write)(AParcel*, const T),
+          binder_status_t (*read)(const AParcel*, T*)>
+void ExpectInOutMinMax() {
+  ExpectInOut<T, write, read>(
+      {std::numeric_limits<T>::min(), std::numeric_limits<T>::max()});
+}
+
+TEST_F(NdkBinderTest_AParcel, ReadUnexpectedNullBinder) {
+  AIBinder* binder = SampleData::newBinder(
+      [](transaction_code_t, const AParcel* in, AParcel* /*out*/) {
+        AIBinder* value = nullptr;
+        binder_status_t ret = AParcel_readStrongBinder(in, &value);
+        EXPECT_EQ(nullptr, value);
+        EXPECT_EQ(STATUS_UNEXPECTED_NULL, ret);
+        return ret;
+      },
+      ExpectLifetimeTransactions(1));
+
+  EXPECT_EQ(STATUS_UNEXPECTED_NULL,
+            SampleData::transact(binder, kCode, [&](AParcel* in) {
+              EXPECT_OK(AParcel_writeStrongBinder(in, nullptr));
+              return STATUS_OK;
+            }));
+
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AParcel, BindersInMustComeOut) {
+  AIBinder* binder = SampleData::newBinder();
+
+  ExpectInOut<AIBinder*, AParcel_writeStrongBinder, AParcel_readStrongBinder>(
+      {binder});
+  // copy which is read when this binder is sent in a transaction to this
+  // process
+  AIBinder_decStrong(binder);
+  // copy which is read when this binder is returned in a transaction within
+  // this same process and is read again
+  AIBinder_decStrong(binder);
+
+  ExpectInOut<AIBinder*, AParcel_writeStrongBinder,
+              AParcel_readNullableStrongBinder>({nullptr, binder});
+  // copy which is read when this binder is sent in a transaction to this
+  // process
+  AIBinder_decStrong(binder);
+  // copy which is read when this binder is returned in a transaction within
+  // this same process and is read again
+  AIBinder_decStrong(binder);
+
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AParcel, WhatGoesInMustComeOut) {
+  ExpectInOut<int32_t, AParcel_writeInt32, AParcel_readInt32>(
+      {-7, -1, 0, 1, 45});
+  ExpectInOut<uint32_t, AParcel_writeUint32, AParcel_readUint32>(
+      {0, 1, 2, 100});
+  ExpectInOut<int64_t, AParcel_writeInt64, AParcel_readInt64>(
+      {-7, -1, 0, 1, 45});
+  ExpectInOut<uint64_t, AParcel_writeUint64, AParcel_readUint64>(
+      {0, 1, 2, 100});
+  ExpectInOut<float, AParcel_writeFloat, AParcel_readFloat>(
+      {-1.0f, 0.0f, 1.0f, 0.24975586f, 0.3f});
+  ExpectInOut<double, AParcel_writeDouble, AParcel_readDouble>(
+      {-1.0, 0.0, 1.0, 0.24975586, 0.3});
+
+  ExpectInOut<bool, AParcel_writeBool, AParcel_readBool>({true, false});
+  ExpectInOut<char16_t, AParcel_writeChar, AParcel_readChar>(
+      {L'\0', L'S', L'@', L'\n'});
+  ExpectInOut<int8_t, AParcel_writeByte, AParcel_readByte>({-7, -1, 0, 1, 45});
+}
+
+TEST_F(NdkBinderTest_AParcel, ExtremeValues) {
+  ExpectInOutMinMax<int32_t, AParcel_writeInt32, AParcel_readInt32>();
+  ExpectInOutMinMax<uint32_t, AParcel_writeUint32, AParcel_readUint32>();
+  ExpectInOutMinMax<int64_t, AParcel_writeInt64, AParcel_readInt64>();
+  ExpectInOutMinMax<uint64_t, AParcel_writeUint64, AParcel_readUint64>();
+  ExpectInOutMinMax<float, AParcel_writeFloat, AParcel_readFloat>();
+  ExpectInOutMinMax<double, AParcel_writeDouble, AParcel_readDouble>();
+  ExpectInOutMinMax<bool, AParcel_writeBool, AParcel_readBool>();
+  ExpectInOutMinMax<char16_t, AParcel_writeChar, AParcel_readChar>();
+  ExpectInOutMinMax<int8_t, AParcel_writeByte, AParcel_readByte>();
+}
+
+TEST_F(NdkBinderTest_AParcel, CantReadFromEmptyParcel) {
+  AIBinder* binder = SampleData::newBinder(TransactionsReturn(STATUS_OK),
+                                           ExpectLifetimeTransactions(1));
+
+  EXPECT_OK(SampleData::transact(
+      binder, kCode, WriteNothingToParcel, [&](const AParcel* out) {
+        bool readTarget = false;
+        EXPECT_EQ(STATUS_NOT_ENOUGH_DATA, AParcel_readBool(out, &readTarget));
+        EXPECT_FALSE(readTarget);
+        return STATUS_OK;
+      }));
+  AIBinder_decStrong(binder);
+}
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp
new file mode 100644
index 0000000..714d66f
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.cpp
@@ -0,0 +1,62 @@
+/*
+ * 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 LOG_TAG "Cts-NdkBinderTest"
+
+#include "utilities.h"
+
+#include <android/log.h>
+
+static size_t sNumInstances = 0;
+size_t SampleData::numInstances() { return sNumInstances; }
+
+void* SampleClassOnCreate(void* args) {
+  sNumInstances++;
+  return args;  // SampleData
+}
+
+void SampleClassOnDestroy(void* userData) {
+  SampleData* data = static_cast<SampleData*>(userData);
+  if (data->onDestroy != nullptr) {
+    data->onDestroy(data);
+  }
+  sNumInstances--;
+  delete data;
+}
+
+binder_status_t SampleClassOnTransact(AIBinder* binder, transaction_code_t code,
+                                      const AParcel* in, AParcel* out) {
+  SampleData* data = static_cast<SampleData*>(AIBinder_getUserData(binder));
+  if (data == nullptr) {
+    __android_log_write(ANDROID_LOG_FATAL, LOG_TAG, "null user data");
+  }
+  data->numberTransactions++;
+  if (data->onTransact == nullptr) {
+    ADD_FAILURE() << "onTransact not specified, but transactions called";
+    return STATUS_FAILED_TRANSACTION;
+  }
+  return data->onTransact(code, in, out);
+}
+
+const char* SampleData::kDescriptor = "this-is-arbitrary";
+const AIBinder_Class* SampleData::kClass =
+    AIBinder_Class_define(SampleData::kDescriptor, SampleClassOnCreate,
+                          SampleClassOnDestroy, SampleClassOnTransact);
+
+const char* SampleData::kAnotherDescriptor = "this-is-another-arbitrary-thing";
+const AIBinder_Class* SampleData::kAnotherClass =
+    AIBinder_Class_define(SampleData::kAnotherDescriptor, SampleClassOnCreate,
+                          SampleClassOnDestroy, SampleClassOnTransact);
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h
new file mode 100644
index 0000000..35fe38f
--- /dev/null
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/utilities.h
@@ -0,0 +1,123 @@
+/*
+ * 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.
+ */
+
+#include <android/binder_ibinder.h>
+#include <gtest/gtest.h>
+
+#include <functional>
+
+// Helpers for testing
+
+#define EXPECT_OK(THING) EXPECT_EQ(STATUS_OK, (THING))
+#define ASSERT_OK(THING) ASSERT_EQ(STATUS_OK, (THING))
+
+// placeholder
+constexpr transaction_code_t kCode = +1 + 918;
+
+// Usually, things at this level would be generated by the aidl compiler. This
+// class is merely to make testing the API easier.
+
+struct SampleData;
+
+typedef std::function<void(SampleData*)> OnDestroyFunc;
+typedef std::function<binder_status_t(transaction_code_t code,
+                                      const AParcel* in, AParcel* out)>
+    OnTransactFunc;
+
+typedef std::function<binder_status_t(AParcel*)> WriteParcel;
+typedef std::function<binder_status_t(const AParcel*)> ReadParcel;
+
+static inline binder_status_t WriteNothingToParcel(AParcel*) {
+  return STATUS_OK;
+}
+static inline binder_status_t ReadNothingFromParcel(const AParcel*) {
+  return STATUS_OK;
+}
+
+struct SampleData {
+  static size_t numInstances();
+
+  static const char* kDescriptor;
+  static const AIBinder_Class* kClass;
+
+  static const char* kAnotherDescriptor;
+  static const AIBinder_Class* kAnotherClass;
+
+  SampleData(const OnTransactFunc& oT = nullptr,
+             const OnDestroyFunc& oD = nullptr)
+      : onTransact(oT), onDestroy(oD) {}
+
+  // This is called when the class is transacted on if non-null.
+  // Otherwise, STATUS_FAILED_TRANSACTION is returned.
+  OnTransactFunc onTransact;
+
+  // This is called when the class is destroyed if non-null.
+  OnDestroyFunc onDestroy;
+
+  // Automatically updated by this class whenever a transaction is received.
+  int numberTransactions = 0;
+
+  __attribute__((warn_unused_result)) static AIBinder* newBinder(
+      OnTransactFunc onTransact = nullptr, OnDestroyFunc onDestroy = nullptr) {
+    SampleData* data = new SampleData(onTransact, onDestroy);
+    return AIBinder_new(kClass, static_cast<void*>(data));
+  };
+
+  // Helper method to simplify transaction logic
+  static binder_status_t transact(AIBinder* binder, transaction_code_t code,
+                                  WriteParcel writeFunc = WriteNothingToParcel,
+                                  ReadParcel readFunc = ReadNothingFromParcel,
+                                  binder_flags_t flags = 0) {
+    AParcel* in;
+    binder_status_t status = AIBinder_prepareTransaction(binder, &in);
+    if (status != STATUS_OK) return status;
+
+    status = writeFunc(in);
+    if (status != STATUS_OK) {
+      AParcel_delete(in);
+      return status;
+    }
+
+    AParcel* out;
+    status = AIBinder_transact(binder, code, &in, &out, flags);
+    if (status != STATUS_OK) return status;
+
+    status = readFunc(out);
+    AParcel_delete(out);
+
+    return status;
+  }
+};
+
+static inline OnDestroyFunc ExpectLifetimeTransactions(size_t count) {
+  return [count](SampleData* data) {
+    EXPECT_EQ(count, data->numberTransactions)
+        << "Expected " << count
+        << " transaction(s), but over the lifetime of this object, it received "
+        << data->numberTransactions;
+  };
+}
+
+static inline OnTransactFunc TransactionsReturn(binder_status_t result) {
+  return
+      [result](transaction_code_t, const AParcel*, AParcel*) { return result; };
+}
+
+class NdkBinderTest : public ::testing::Test {
+ public:
+  void SetUp() override { EXPECT_EQ(0, SampleData::numInstances()); }
+  void TearDown() override { EXPECT_EQ(0, SampleData::numInstances()); }
+};
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2Addr_1.java b/tests/tests/binder_ndk/src/android/binder/cts/NdkBinderTest.java
similarity index 65%
rename from tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2Addr_1.java
rename to tests/tests/binder_ndk/src/android/binder/cts/NdkBinderTest.java
index 2536113..d2e416f 100644
--- a/tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2Addr_1.java
+++ b/tests/tests/binder_ndk/src/android/binder/cts/NdkBinderTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * 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.
@@ -14,11 +14,12 @@
  * limitations under the License.
  */
 
-package android.vm.cts.opcodes.add_double_2addr;
+package android.binder.cts;
 
-public class AddDouble2Addr_1 {
+import org.junit.runner.RunWith;
+import com.android.gtestrunner.GtestRunner;
+import com.android.gtestrunner.TargetLibrary;
 
-    public double run(double a, double b) {
-        return a + b;
-    }
-}
+@RunWith(GtestRunner.class)
+@TargetLibrary("binder_ndk_test")
+public class NdkBinderTest {}
diff --git a/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java b/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
index 0ed6395..77d2f82 100644
--- a/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
+++ b/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
@@ -184,24 +184,43 @@
         }
     }
 
-    private RadioAccessSpecifier getRadioAccessSpecifier(CellInfo cellInfo) {
-        RadioAccessSpecifier ras;
-        if (cellInfo instanceof CellInfoLte) {
-            int ranLte = AccessNetworkConstants.AccessNetworkType.EUTRAN;
-            int[] lteChannels = {((CellInfoLte) cellInfo).getCellIdentity().getEarfcn()};
-            ras = new RadioAccessSpecifier(ranLte, null /* bands */, lteChannels);
-        } else if (cellInfo instanceof CellInfoWcdma) {
-            int ranLte = AccessNetworkConstants.AccessNetworkType.UTRAN;
-            int[] wcdmaChannels = {((CellInfoWcdma) cellInfo).getCellIdentity().getUarfcn()};
-            ras = new RadioAccessSpecifier(ranLte, null /* bands */, wcdmaChannels);
-        } else if (cellInfo instanceof CellInfoGsm) {
-            int ranGsm = AccessNetworkConstants.AccessNetworkType.GERAN;
-            int[] gsmChannels = {((CellInfoGsm) cellInfo).getCellIdentity().getArfcn()};
-            ras = new RadioAccessSpecifier(ranGsm, null /* bands */, gsmChannels);
-        } else {
-            ras = null;
+    private List<RadioAccessSpecifier> getRadioAccessSpecifier(List<CellInfo> allCellInfo) {
+        List<RadioAccessSpecifier> radioAccessSpecifier = new ArrayList<>();
+        List<Integer> lteChannels = new ArrayList<>();
+        List<Integer> wcdmaChannels = new ArrayList<>();
+        List<Integer> gsmChannels = new ArrayList<>();
+        for (int i = 0; i < allCellInfo.size(); i++) {
+            CellInfo cellInfo = allCellInfo.get(i);
+            if (cellInfo instanceof CellInfoLte) {
+                lteChannels.add(((CellInfoLte) cellInfo).getCellIdentity().getEarfcn());
+            } else if (cellInfo instanceof CellInfoWcdma) {
+                wcdmaChannels.add(((CellInfoWcdma) cellInfo).getCellIdentity().getUarfcn());
+            } else if (cellInfo instanceof CellInfoGsm) {
+                gsmChannels.add(((CellInfoGsm) cellInfo).getCellIdentity().getArfcn());
+            }
         }
-        return ras;
+        if (!lteChannels.isEmpty()) {
+            Log.d(TAG, "lte channels" + lteChannels.toString());
+            int ranLte = AccessNetworkConstants.AccessNetworkType.EUTRAN;
+            radioAccessSpecifier.add(
+                    new RadioAccessSpecifier(ranLte, null /* bands */,
+                            lteChannels.stream().mapToInt(i->i).toArray()));
+        }
+        if (!wcdmaChannels.isEmpty()) {
+            Log.d(TAG, "wcdma channels" + wcdmaChannels.toString());
+            int ranWcdma = AccessNetworkConstants.AccessNetworkType.UTRAN;
+            radioAccessSpecifier.add(
+                    new RadioAccessSpecifier(ranWcdma, null /* bands */,
+                            wcdmaChannels.stream().mapToInt(i->i).toArray()));
+        }
+        if (!gsmChannels.isEmpty()) {
+            Log.d(TAG, "gsm channels" + gsmChannels.toString());
+            int ranGsm = AccessNetworkConstants.AccessNetworkType.GERAN;
+            radioAccessSpecifier.add(
+                    new RadioAccessSpecifier(ranGsm, null /* bands */,
+                            gsmChannels.stream().mapToInt(i->i).toArray()));
+        }
+        return radioAccessSpecifier;
     }
 
     /**
@@ -228,14 +247,9 @@
         }
 
         // Construct a NetworkScanRequest
-        List<RadioAccessSpecifier> radioAccessSpecifier = new ArrayList<>();
-        for (int i = 0; i < allCellInfo.size(); i++) {
-            RadioAccessSpecifier ras = getRadioAccessSpecifier(allCellInfo.get(i));
-            if (ras != null) {
-                radioAccessSpecifier.add(ras);
-            }
-        }
-        if (radioAccessSpecifier.size() == 0) {
+        List<RadioAccessSpecifier> radioAccessSpecifier = getRadioAccessSpecifier(allCellInfo);
+        Log.d(TAG, "number of radioAccessSpecifier: " + radioAccessSpecifier.size());
+        if (radioAccessSpecifier.isEmpty()) {
             RadioAccessSpecifier gsm = new RadioAccessSpecifier(
                     AccessNetworkConstants.AccessNetworkType.GERAN,
                     null /* bands */,
@@ -301,7 +315,7 @@
      * To test its constructor and getters.
      */
     @Test
-    public void testNetworkScanRequest_ConstructorAndGetters(){
+    public void testNetworkScanRequest_ConstructorAndGetters() {
         NetworkScanRequest networkScanRequest = new NetworkScanRequest(
                 SCAN_TYPE,
                 RADIO_ACCESS_SPECIFIERS,
diff --git a/tests/tests/content/AndroidTest.xml b/tests/tests/content/AndroidTest.xml
index 58305dd..4b22631 100644
--- a/tests/tests/content/AndroidTest.xml
+++ b/tests/tests/content/AndroidTest.xml
@@ -35,6 +35,7 @@
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="runner" value="android.support.test.runner.AndroidJUnitRunner" />
         <option name="package" value="android.content.cts" />
         <option name="runtime-hint" value="21m30s" />
         <option name="hidden-api-checks" value="false" />
diff --git a/tests/tests/dpi/src/android/dpi/cts/ConfigurationScreenLayoutTest.java b/tests/tests/dpi/src/android/dpi/cts/ConfigurationScreenLayoutTest.java
index 3015b07..a7b2692 100644
--- a/tests/tests/dpi/src/android/dpi/cts/ConfigurationScreenLayoutTest.java
+++ b/tests/tests/dpi/src/android/dpi/cts/ConfigurationScreenLayoutTest.java
@@ -20,7 +20,9 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
 import android.content.res.Configuration;
+import android.support.test.InstrumentationRegistry;
 import android.test.ActivityInstrumentationTestCase2;
 import android.util.DisplayMetrics;
 import android.view.Display;
@@ -42,6 +44,19 @@
     }
 
     public void testScreenLayout() throws Exception {
+        if (!supportsRotation()) {
+            // test has no effect if device does not support rotation
+            tearDown();
+            return;
+        }
+        if (isPC()) {
+            // The test skips mainly for Chromebook clamshell mode. For Chromebook clamshell mode
+            // with non-rotated landscape physical screen, the portrait window/activity has special
+            // behavior with black background on both sides to make the window/activity look
+            // portrait, which returns smaller screen layout size.
+            tearDown();
+            return;
+        }
         int expectedScreenLayout = computeScreenLayout();
         int expectedSize = expectedScreenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
         int expectedLong = expectedScreenLayout & Configuration.SCREENLAYOUT_LONG_MASK;
@@ -86,6 +101,12 @@
         return screenLayout;
     }
 
+    private boolean hasDeviceFeature(final String requiredFeature) {
+        return InstrumentationRegistry.getContext()
+                .getPackageManager()
+                .hasSystemFeature(requiredFeature);
+    }
+
     private Activity startOrientationActivity(int orientation) {
         Intent intent = new Intent();
         intent.putExtra(OrientationActivity.EXTRA_ORIENTATION, orientation);
@@ -139,4 +160,20 @@
         }
         return screenLayout;
     }
+
+    /**
+     * Rotation support is indicated by explicitly having both landscape and portrait
+     * features or not listing either at all.
+     */
+    private boolean supportsRotation() {
+        final boolean supportsLandscape = hasDeviceFeature(PackageManager.FEATURE_SCREEN_LANDSCAPE);
+        final boolean supportsPortrait = hasDeviceFeature(PackageManager.FEATURE_SCREEN_PORTRAIT);
+        return (supportsLandscape && supportsPortrait)
+                || (!supportsLandscape && !supportsPortrait);
+    }
+
+    // Check if it is a PC device
+    private boolean isPC() {
+        return hasDeviceFeature(PackageManager.FEATURE_PC);
+    }
 }
diff --git a/tests/tests/graphics/jni/android_graphics_cts_MediaVulkanGpuTest.cpp b/tests/tests/graphics/jni/android_graphics_cts_MediaVulkanGpuTest.cpp
index 9bee99c..fd570a8 100644
--- a/tests/tests/graphics/jni/android_graphics_cts_MediaVulkanGpuTest.cpp
+++ b/tests/tests/graphics/jni/android_graphics_cts_MediaVulkanGpuTest.cpp
@@ -76,9 +76,6 @@
     // Could not initialize Vulkan due to lack of device support, skip test.
     return;
   }
-  VkImageRenderer renderer(&init, kTestImageWidth, kTestImageHeight,
-                           VK_FORMAT_R8G8B8A8_UNORM, 4);
-  ASSERT(renderer.init(env, assetMgr), "Could not init VkImageRenderer.");
 
   // Set up the image reader and media helpers used to get a frames from video.
   ImageReaderHelper imageReader(kTestImageWidth, kTestImageHeight,
@@ -100,9 +97,23 @@
     ret = imageReader.getBufferFromCurrentImage(&buffer);
   }
 
+  // Read the width/height of the produced AHardwareBuffer. AImageReader may round up from our
+  // expected video size.
+  AHardwareBuffer_Desc bufferDesc;
+  AHardwareBuffer_describe(buffer, &bufferDesc);
+  // The AImageReader may round up the size of the AHardwareBuffer returned.
+  ASSERT(bufferDesc.width >= kTestImageWidth, "Unexpectedly small image width read from video.");
+  ASSERT(bufferDesc.height >= kTestImageHeight, "Unexpectedly small image height read from video.");
+
+  // Create a VkImageRenderer with the actual width/height of the AHardwareBuffer.
+  VkImageRenderer renderer(&init, bufferDesc.width, bufferDesc.height,
+                           VK_FORMAT_R8G8B8A8_UNORM, 4);
+  ASSERT(renderer.init(env, assetMgr), "Could not init VkImageRenderer.");
+
   // Import the AHardwareBuffer into Vulkan.
   VkAHardwareBufferImage vkImage(&init);
-  ASSERT(vkImage.init(buffer, true /* useExternalFormat */), "Could not init VkAHardwareBufferImage.");
+  ASSERT(vkImage.init(buffer, true /* useExternalFormat */),
+         "Could not init VkAHardwareBufferImage.");
 
   // Render the AHardwareBuffer using Vulkan and read back the result.
   std::vector<uint32_t> framePixels;
@@ -110,23 +121,24 @@
              vkImage.image(), vkImage.sampler(), vkImage.view(),
              vkImage.semaphore(), vkImage.isSamplerImmutable(), &framePixels),
          "Could not get frame pixels from Vulkan.");
-  ASSERT(framePixels.size() == kTestImageWidth * kTestImageHeight,
+  ASSERT(framePixels.size() == bufferDesc.width * bufferDesc.height,
          "Unexpected number of pixels in frame");
 
   // Ensure that the data we read back matches our reference image.
   size_t referenceSize =
       static_cast<size_t>(env->GetArrayLength(referencePixels));
-  ASSERT(framePixels.size() == referenceSize,
-         "Unexpected number of pixels in frame.");
+  ASSERT(referenceSize == kTestImageWidth * kTestImageHeight,
+         "Unexpected number of pixels in reference image.");
   uint32_t *referenceData = reinterpret_cast<uint32_t *>(
       env->GetIntArrayElements(referencePixels, 0));
   for (uint32_t x = 0; x < kTestImageWidth; ++x) {
     for (uint32_t y = 0; y < kTestImageHeight; ++y) {
-      size_t offset = y * kTestImageWidth + x;
+      size_t frame_offset = y * bufferDesc.width + x;
+      size_t reference_offset = y * kTestImageWidth + x;
       static const int32_t kTolerance = 0x30;
-      uint32_t value1 = framePixels[offset];
+      uint32_t value1 = framePixels[frame_offset];
       // Reference data is BGRA, Vk data is BGRA.
-      uint32_t value2 = swizzleBgraToRgba(referenceData[offset]);
+      uint32_t value2 = swizzleBgraToRgba(referenceData[reference_offset]);
       ASSERT(fuzzyMatch(value1, value2, kTolerance),
              "Expected ~0x%08X at (%i,%i), got 0x%08X", value2, x, y, value1);
     }
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
index 06f92d3..898cc11 100644
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/VulkanPreTransformTest.java
@@ -19,10 +19,13 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
+import android.content.Context;
+import android.content.pm.PackageManager;
 import android.graphics.Bitmap;
 import android.graphics.Color;
 import android.graphics.Rect;
 import android.os.SystemClock;
+import android.support.test.InstrumentationRegistry;
 import android.support.test.rule.ActivityTestRule;
 import android.support.test.runner.AndroidJUnit4;
 import android.test.suitebuilder.annotation.LargeTest;
@@ -75,6 +78,7 @@
     private static final String TAG = "vulkan";
     private static final boolean DEBUG = false;
     private static VulkanPreTransformCtsActivity sActivity = null;
+    private Context mContext;
 
     @Rule
     public ActivityTestRule<VulkanPreTransformCtsActivity> mActivityRule =
@@ -86,11 +90,17 @@
         // Work around for b/77148807
         // Activity was falsely created before ActivityManager set config change to landscape
         SystemClock.sleep(2000);
+        mContext = InstrumentationRegistry.getContext();
     }
 
     @Test
     public void testVulkanPreTransformSetToMatchCurrentTransform() throws Throwable {
         Log.d(TAG, "testVulkanPreTransformSetToMatchCurrentTransform start");
+        if (!hasDeviceFeature(PackageManager.FEATURE_SCREEN_PORTRAIT)
+                || !hasDeviceFeature(PackageManager.FEATURE_SCREEN_LANDSCAPE)) {
+            Log.d(TAG, "Rotation is not supported on this device.");
+            return;
+        }
         sActivity = mActivityRule.launchActivity(null);
         sActivity.testVulkanPreTransform(true);
         sActivity.finish();
@@ -100,12 +110,21 @@
     @Test
     public void testVulkanPreTransformNotSetToMatchCurrentTransform() throws Throwable {
         Log.d(TAG, "testVulkanPreTransformNotSetToMatchCurrentTransform start");
+        if (!hasDeviceFeature(PackageManager.FEATURE_SCREEN_PORTRAIT)
+                || !hasDeviceFeature(PackageManager.FEATURE_SCREEN_LANDSCAPE)) {
+            Log.d(TAG, "Rotation is not supported on this device.");
+            return;
+        }
         sActivity = mActivityRule.launchActivity(null);
         sActivity.testVulkanPreTransform(false);
         sActivity.finish();
         sActivity = null;
     }
 
+    private boolean hasDeviceFeature(final String requiredFeature) {
+        return mContext.getPackageManager().hasSystemFeature(requiredFeature);
+    }
+
     private static Bitmap takeScreenshot() {
         assertNotNull("sActivity should not be null", sActivity);
         Rect srcRect = new Rect();
diff --git a/tests/tests/hardware/src/android/hardware/cts/Egl14Utils.java b/tests/tests/hardware/src/android/hardware/cts/Egl14Utils.java
deleted file mode 100644
index a8026c9..0000000
--- a/tests/tests/hardware/src/android/hardware/cts/Egl14Utils.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.hardware.cts;
-
-import android.opengl.EGL14;
-import android.opengl.EGLConfig;
-import android.opengl.EGLContext;
-import android.opengl.EGLDisplay;
-import android.opengl.EGLExt;
-import android.opengl.GLES20;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Utilities to test EGL APIs.
- */
-final class Egl14Utils {
-    private Egl14Utils() {
-    }
-
-    /**
-     * Returns an initialized default display.
-     */
-    static EGLDisplay createEglDisplay() {
-        EGLDisplay eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
-        if (eglDisplay == EGL14.EGL_NO_DISPLAY) {
-            throw new IllegalStateException("no EGL display");
-        }
-
-        int[] major = new int[1];
-        int[] minor = new int[1];
-        if (!EGL14.eglInitialize(eglDisplay, major, 0, minor, 0)) {
-            throw new IllegalStateException("error in eglInitialize");
-        }
-
-        return eglDisplay;
-    }
-
-    /**
-     * Returns a new GL ES 2.0 context for the specified {@code eglDisplay}.
-     */
-    static EGLContext createEglContext(EGLDisplay eglDisplay) {
-        return createEglContext(eglDisplay, getEglConfig(eglDisplay, 2), 2);
-    }
-
-    /**
-     * Returns a new GL ES context for the specified display, config and version.
-     */
-    static EGLContext createEglContext(EGLDisplay eglDisplay, EGLConfig eglConfig, int version) {
-        int[] contextAttributes = { EGL14.EGL_CONTEXT_CLIENT_VERSION, version, EGL14.EGL_NONE };
-        return EGL14.eglCreateContext(eglDisplay, eglConfig,
-                EGL14.EGL_NO_CONTEXT, contextAttributes, 0);
-    }
-
-    /**
-     * Destroys the GL context identified by {@code eglDisplay} and {@code eglContext}.
-     */
-    static void destroyEglContext(EGLDisplay eglDisplay, EGLContext eglContext) {
-        EGL14.eglMakeCurrent(eglDisplay,
-                EGL14.EGL_NO_SURFACE,
-                EGL14.EGL_NO_SURFACE,
-                EGL14.EGL_NO_CONTEXT);
-        int error = EGL14.eglGetError();
-        if (error != EGL14.EGL_SUCCESS) {
-            throw new RuntimeException("error releasing context: " + error);
-        }
-
-        EGL14.eglDestroyContext(eglDisplay, eglContext);
-        error = EGL14.eglGetError();
-        if (error != EGL14.EGL_SUCCESS) {
-            throw new RuntimeException("error destroying context: " + error);
-        }
-    }
-
-    static void releaseAndTerminate(EGLDisplay eglDisplay) {
-        int error;
-        EGL14.eglReleaseThread();
-        error = EGL14.eglGetError();
-        if (error != EGL14.EGL_SUCCESS) {
-            throw new RuntimeException("error releasing thread: " + error);
-        }
-
-        EGL14.eglTerminate(eglDisplay);
-        error = EGL14.eglGetError();
-        if (error != EGL14.EGL_SUCCESS) {
-            throw new RuntimeException("error terminating display: " + error);
-        }
-    }
-
-    static EGLConfig getEglConfig(EGLDisplay eglDisplay, int version) {
-        // Get an EGLConfig.
-        int renderableType = EGL14.EGL_OPENGL_ES2_BIT;
-        if (version == 3) {
-            renderableType = EGLExt.EGL_OPENGL_ES3_BIT_KHR;
-        }
-        final int RED_SIZE = 8;
-        final int GREEN_SIZE = 8;
-        final int BLUE_SIZE = 8;
-        final int ALPHA_SIZE = 8;
-        final int DEPTH_SIZE = 0;
-        final int STENCIL_SIZE = 0;
-        final int[] DEFAULT_CONFIGURATION = new int[] {
-                EGL14.EGL_RENDERABLE_TYPE, renderableType,
-                EGL14.EGL_RED_SIZE, RED_SIZE,
-                EGL14.EGL_GREEN_SIZE, GREEN_SIZE,
-                EGL14.EGL_BLUE_SIZE, BLUE_SIZE,
-                EGL14.EGL_ALPHA_SIZE, ALPHA_SIZE,
-                EGL14.EGL_DEPTH_SIZE, DEPTH_SIZE,
-                EGL14.EGL_STENCIL_SIZE, STENCIL_SIZE,
-                EGL14.EGL_NONE};
-
-        int[] configsCount = new int[1];
-        EGLConfig[] eglConfigs = new EGLConfig[1];
-        if (!EGL14.eglChooseConfig(
-                eglDisplay, DEFAULT_CONFIGURATION, 0, eglConfigs, 0, 1, configsCount, 0)) {
-            throw new RuntimeException("eglChooseConfig failed");
-        }
-        return eglConfigs[0];
-    }
-
-    /**
-     * Checks for a GL error using {@link GLES20#glGetError()}.
-     *
-     * @throws RuntimeException if there is a GL error
-     */
-    static void checkGlError() {
-        int errorCode;
-        if ((errorCode = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
-            throw new RuntimeException("gl error: " + Integer.toHexString(errorCode));
-        }
-    }
-}
diff --git a/tests/tests/hardware/src/android/hardware/cts/GlUtils.java b/tests/tests/hardware/src/android/hardware/cts/GlUtils.java
deleted file mode 100644
index bd5cecb..0000000
--- a/tests/tests/hardware/src/android/hardware/cts/GlUtils.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hardware.cts;
-
-import android.opengl.GLES20;
-import android.util.Pair;
-
-import java.util.Arrays;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-final class GlUtils {
-    private GlUtils() {
-    }
-
-    static int getMajorVersion() {
-        return getVersion().first;
-    }
-
-    static Pair<Integer, Integer> getVersion() {
-        // Section 6.1.5 of the OpenGL ES specification indicates the GL version
-        // string strictly follows this format:
-        //
-        // OpenGL<space>ES<space><version number><space><vendor-specific information>
-        //
-        // In addition section 6.1.5 describes the version number in the following manner:
-        //
-        // "The version number is either of the form major number.minor number or
-        // major number.minor number.release number, where the numbers all have one
-        // or more digits. The release number and vendor specific information are
-        // optional."
-        String version = GLES20.glGetString(GLES20.GL_VERSION);
-        Pattern pattern = Pattern.compile("OpenGL ES ([0-9]+)\\.([0-9]+)");
-        Matcher matcher = pattern.matcher(version);
-        if (matcher.find()) {
-            return new Pair<>(
-                    Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)));
-        }
-        return new Pair<>(2, 0);
-    }
-
-    static String[] getExtensions() {
-        return GLES20.glGetString(GLES20.GL_EXTENSIONS).split(" ");
-    }
-
-    static boolean hasExtensions(String... extensions) {
-        String[] available = getExtensions();
-        Arrays.sort(available);
-        for (String extension : extensions) {
-            if (Arrays.binarySearch(available, extension) < 0) return false;
-        }
-        return true;
-    }
-}
diff --git a/tests/tests/hardware/src/android/hardware/cts/HardwareBufferTest.java b/tests/tests/hardware/src/android/hardware/cts/HardwareBufferTest.java
index 6276959..74e6857 100644
--- a/tests/tests/hardware/src/android/hardware/cts/HardwareBufferTest.java
+++ b/tests/tests/hardware/src/android/hardware/cts/HardwareBufferTest.java
@@ -16,36 +16,23 @@
 
 package android.hardware.cts;
 
-import android.hardware.HardwareBuffer;
-import android.opengl.EGL14;
-import android.opengl.EGLConfig;
-import android.opengl.EGLContext;
-import android.opengl.EGLDisplay;
-import android.opengl.EGLSurface;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
-import android.util.Pair;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static android.opengl.EGL14.EGL_HEIGHT;
-import static android.opengl.EGL14.EGL_NONE;
-import static android.opengl.EGL14.EGL_NO_CONTEXT;
-import static android.opengl.EGL14.EGL_NO_SURFACE;
-import static android.opengl.EGL14.EGL_WIDTH;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
+import android.graphics.PixelFormat;
+import android.hardware.HardwareBuffer;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 /**
  * Test {@link HardwareBuffer}.
  */
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class HardwareBufferTest {
-    private static boolean sHasFloatBuffers;
-
-    @SuppressWarnings("SameParameterValue")
     private static native HardwareBuffer nativeCreateHardwareBuffer(int width, int height,
             int format, int layers, long usage);
     private static native void nativeReleaseHardwareBuffer(HardwareBuffer hardwareBufferObj);
@@ -54,51 +41,6 @@
         System.loadLibrary("ctshardware_jni");
     }
 
-    @BeforeClass
-    public static void hasFloatBuffers() {
-        EGLDisplay eglDisplay = null;
-        EGLContext eglContext = null;
-        EGLSurface eglSurface = null;
-        try {
-            eglDisplay = Egl14Utils.createEglDisplay();
-            EGLConfig eglConfig = Egl14Utils.getEglConfig(eglDisplay, 2);
-            eglContext = Egl14Utils.createEglContext(eglDisplay, eglConfig, 2);
-
-            eglSurface = EGL14.eglCreatePbufferSurface(eglDisplay, eglConfig, new int[] {
-                    EGL_WIDTH, 1,
-                    EGL_HEIGHT, 1,
-                    EGL_NONE
-            }, 0);
-            EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
-
-            Pair<Integer, Integer> version = GlUtils.getVersion();
-            sHasFloatBuffers = (version.first >= 3 && version.second >= 2) ||
-                    GlUtils.hasExtensions(
-                            "GL_OES_texture_half_float",
-                            "GL_OES_texture_half_float_linear");
-
-            EGL14.eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
-            EGL14.eglDestroySurface(eglDisplay, eglSurface);
-
-            Egl14Utils.destroyEglContext(eglDisplay, eglContext);
-            Egl14Utils.releaseAndTerminate(eglDisplay);
-
-            eglDisplay = null;
-            eglContext = null;
-            eglSurface = null;
-        } finally {
-            if (eglDisplay != null) {
-                if (eglContext != null) {
-                    EGL14.eglDestroyContext(eglDisplay, eglContext);
-                }
-                if (eglSurface != null) {
-                    EGL14.eglDestroySurface(eglDisplay, eglSurface);
-                }
-                EGL14.eglTerminate(eglDisplay);
-            }
-        }
-    }
-
     @Test
     public void testCreate() {
         HardwareBuffer buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGBA_8888, 1,
@@ -122,21 +64,12 @@
         buffer = HardwareBuffer.create(2, 1, HardwareBuffer.BLOB, 1,
                 HardwareBuffer.USAGE_CPU_READ_RARELY);
         assertEquals(HardwareBuffer.BLOB, buffer.getFormat());
-
-        if (sHasFloatBuffers) {
-            buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGBA_FP16, 1,
-                    HardwareBuffer.USAGE_CPU_READ_RARELY);
-            assertEquals(HardwareBuffer.RGBA_FP16, buffer.getFormat());
-            buffer = HardwareBuffer.create(2, 4, HardwareBuffer.RGBA_1010102, 1,
-                    HardwareBuffer.USAGE_CPU_READ_RARELY);
-            assertEquals(HardwareBuffer.RGBA_1010102, buffer.getFormat());
-        }
     }
 
-    @SuppressWarnings("EmptyCatchBlock")
     @Test
     public void testCreateFailsWithInvalidArguments() {
         HardwareBuffer buffer = null;
+        assertEquals(null, buffer);
         try {
             buffer = HardwareBuffer.create(0, 4, HardwareBuffer.RGB_888, 1,
                     HardwareBuffer.USAGE_CPU_READ_RARELY);
@@ -163,20 +96,6 @@
         } catch (IllegalArgumentException e) {}
         assertEquals(null, buffer);
 
-        if (sHasFloatBuffers) {
-            try {
-                buffer = HardwareBuffer.create(0, 4, HardwareBuffer.RGBA_FP16, 1,
-                        HardwareBuffer.USAGE_CPU_READ_RARELY);
-            } catch (IllegalArgumentException e) {
-            }
-            assertEquals(null, buffer);
-            try {
-                buffer = HardwareBuffer.create(0, 4, HardwareBuffer.RGBA_1010102, 1,
-                        HardwareBuffer.USAGE_CPU_READ_RARELY);
-            } catch (IllegalArgumentException e) {
-            }
-            assertEquals(null, buffer);
-        }
     }
 
     @Test
diff --git a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
index c0fbdc3..2992eaf 100644
--- a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
+++ b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
@@ -41,13 +41,14 @@
     private final static String PRODUCT_CONFIG_DIR = "/product/etc/";
     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");
+            "public\\.libraries-([A-Za-z0-9\\-_.]+)\\.txt");
     private final static Pattern EXTENSION_LIBRARY_FILE_PATTERN = Pattern.compile(
-            "lib[^.]+\\.([A-Za-z0-9\\-_]+)\\.so");
+            "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",
         "libandroid.so",
+        "libbinder_ndk.so",
         "libc.so",
         "libcamera2ndk.so",
         "libdl.so",
diff --git a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
index 66404b2..e75a60f 100644
--- a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
@@ -18,6 +18,7 @@
 
 import android.app.KeyguardManager;
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 import android.security.keystore.KeyGenParameterSpec;
@@ -439,9 +440,18 @@
         }
     }
 
+    private boolean isLeanbackOnly() {
+        PackageManager pm = getContext().getPackageManager();
+        return (pm != null && pm.hasSystemFeature("android.software.leanback_only"));
+    }
+
     @Presubmit
     public void testKeyguardLockAndUnlock()
             throws Exception {
+        if (isLeanbackOnly()) {
+            return;
+        }
+
         try (DeviceLockSession dl = new DeviceLockSession()) {
             KeyguardManager keyguardManager = (KeyguardManager)getContext()
                     .getSystemService(Context.KEYGUARD_SERVICE);
@@ -459,6 +469,10 @@
         final boolean isUnlockedDeviceRequired = true;
         final boolean isUserAuthRequired = false;
 
+        if (isLeanbackOnly()) {
+            return;
+        }
+
         try (DeviceLockSession dl = new DeviceLockSession()) {
             KeyguardManager keyguardManager = (KeyguardManager)getContext()
                 .getSystemService(Context.KEYGUARD_SERVICE);
@@ -947,6 +961,10 @@
         final boolean isUnlockedDeviceRequired = false;
         final boolean isUserAuthRequired = true;
 
+        if (isLeanbackOnly()) {
+            return;
+        }
+
         try (DeviceLockSession dl = new DeviceLockSession()) {
             KeyguardManager keyguardManager = (KeyguardManager)getContext().getSystemService(Context.KEYGUARD_SERVICE);
 
@@ -970,6 +988,10 @@
         final boolean isUserAuthRequired = true;
         final boolean isUnlockedDeviceRequired = false;
 
+        if (isLeanbackOnly()) {
+            return;
+        }
+
         KeyguardManager keyguardManager = (KeyguardManager)getContext().getSystemService(Context.KEYGUARD_SERVICE);
         assertFalse(keyguardManager.isDeviceLocked());
 
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index 80e28d1..6b925d4 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -690,6 +690,7 @@
 
                 case 2:
                 case 3:
+                case 4:
                     assertThat(teeEnforcedDigests, is(expectedDigests));
                     break;
 
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
index 570ce47..9fc3bd1 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
@@ -299,6 +299,13 @@
     }
 
     public void testGenerateHonorsRequestedAuthorizations() throws Exception {
+        testGenerateHonorsRequestedAuthorizationsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerateHonorsRequestedAuthorizationsHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testGenerateHonorsRequestedAuthorizationsHelper(boolean useStrongbox) {
         Date keyValidityStart = new Date(System.currentTimeMillis() - TestUtils.DAY_IN_MILLIS);
         Date keyValidityForOriginationEnd =
                 new Date(System.currentTimeMillis() + TestUtils.DAY_IN_MILLIS);
@@ -322,6 +329,7 @@
                         .setKeyValidityStart(keyValidityStart)
                         .setKeyValidityForOriginationEnd(keyValidityForOriginationEnd)
                         .setKeyValidityForConsumptionEnd(keyValidityForConsumptionEnd)
+                        .setIsStrongBoxBacked(useStrongbox)
                         .build());
                 KeyPair keyPair = generator.generateKeyPair();
                 assertEquals(algorithm, keyPair.getPrivate().getAlgorithm());
@@ -353,7 +361,8 @@
                 assertFalse(keyInfo.isUserAuthenticationRequired());
                 assertFalse(keyInfo.isUserAuthenticationRequirementEnforcedBySecureHardware());
             } catch (Throwable e) {
-                throw new RuntimeException("Failed for " + algorithm, e);
+                String specific = useStrongbox ? "Strongbox:" : "";
+                throw new RuntimeException(specific + "Failed for " + algorithm, e);
             }
         }
     }
@@ -562,8 +571,14 @@
                 KeyProperties.SIGNATURE_PADDING_RSA_PKCS1);
     }
 
-    public void testGenerate_ReplacesOldEntryWithSameAlias()
-            throws Exception {
+    public void testGenerate_ReplacesOldEntryWithSameAlias() throws Exception {
+        replacesOldEntryWithSameAliasHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            replacesOldEntryWithSameAliasHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void replacesOldEntryWithSameAliasHelper(boolean useStrongbox) throws Exception {
         // Generate the first key
         {
             KeyPairGenerator generator = getRsaGenerator();
@@ -579,6 +594,7 @@
                     .setCertificateSerialNumber(TEST_SERIAL_1)
                     .setCertificateNotBefore(NOW)
                     .setCertificateNotAfter(NOW_PLUS_10_YEARS)
+                    .setIsStrongBoxBacked(useStrongbox)
                     .build());
             assertGeneratedKeyPairAndSelfSignedCertificate(
                     generator.generateKeyPair(),
@@ -606,6 +622,7 @@
                     .setCertificateSerialNumber(TEST_SERIAL_2)
                     .setCertificateNotBefore(NOW)
                     .setCertificateNotAfter(NOW_PLUS_10_YEARS)
+                    .setIsStrongBoxBacked(useStrongbox)
                     .build());
             assertGeneratedKeyPairAndSelfSignedCertificate(
                     generator.generateKeyPair(),
@@ -619,8 +636,14 @@
         }
     }
 
-    public void testGenerate_DoesNotReplaceOtherEntries()
-            throws Exception {
+    public void testGenerate_DoesNotReplaceOtherEntries() throws Exception {
+        doesNotReplaceOtherEntriesHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            doesNotReplaceOtherEntriesHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void doesNotReplaceOtherEntriesHelper(boolean useStrongbox) throws Exception {
         // Generate the first key
         KeyPairGenerator generator = getRsaGenerator();
         generator.initialize(new KeyGenParameterSpec.Builder(
@@ -635,6 +658,7 @@
                 .setCertificateSerialNumber(TEST_SERIAL_1)
                 .setCertificateNotBefore(NOW)
                 .setCertificateNotAfter(NOW_PLUS_10_YEARS)
+                .setIsStrongBoxBacked(useStrongbox)
                 .build());
         KeyPair keyPair1 = generator.generateKeyPair();
         assertGeneratedKeyPairAndSelfSignedCertificate(
@@ -660,6 +684,7 @@
                 .setCertificateSerialNumber(TEST_SERIAL_2)
                 .setCertificateNotBefore(NOW)
                 .setCertificateNotAfter(NOW_PLUS_10_YEARS)
+                .setIsStrongBoxBacked(useStrongbox)
                 .build());
         KeyPair keyPair2 = generator.generateKeyPair();
         assertGeneratedKeyPairAndSelfSignedCertificate(
@@ -685,10 +710,18 @@
     }
 
     public void testGenerate_EC_ModernSpec_Defaults() throws Exception {
+        testGenerate_EC_ModernSpec_DefaultsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerate_EC_ModernSpec_DefaultsHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testGenerate_EC_ModernSpec_DefaultsHelper(boolean useStrongbox) throws Exception {
         KeyPairGenerator generator = getEcGenerator();
         generator.initialize(new KeyGenParameterSpec.Builder(
                 TEST_ALIAS_1,
                 KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
+                .setIsStrongBoxBacked(useStrongbox)
                 .build());
         KeyPair keyPair = generator.generateKeyPair();
         assertGeneratedKeyPairAndSelfSignedCertificate(
@@ -720,10 +753,18 @@
     }
 
     public void testGenerate_RSA_ModernSpec_Defaults() throws Exception {
+        testGenerate_RSA_ModernSpec_DefaultsHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerate_RSA_ModernSpec_DefaultsHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testGenerate_RSA_ModernSpec_DefaultsHelper(boolean useStrongbox) throws Exception {
         KeyPairGenerator generator = getRsaGenerator();
         generator.initialize(new KeyGenParameterSpec.Builder(
                 TEST_ALIAS_1,
                 KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
+                .setIsStrongBoxBacked(useStrongbox)
                 .build());
         KeyPair keyPair = generator.generateKeyPair();
         assertGeneratedKeyPairAndSelfSignedCertificate(
@@ -818,6 +859,74 @@
         assertEquals(-1, keyInfo.getUserAuthenticationValidityDurationSeconds());
     }
 
+    // Strongbox has more restrictions on key properties than general keystore.
+    // This is a reworking of the generic test to still be as custom as possible while
+    // respecting the spec constraints.
+    // Test fails until the resolution of b/113276806
+    public void testGenerate_EC_ModernSpec_AsCustomAsPossibleStrongbox() throws Exception {
+        KeyPairGenerator generator = getEcGenerator();
+        Date keyValidityStart = new Date(System.currentTimeMillis());
+        Date keyValidityEndDateForOrigination = new Date(System.currentTimeMillis() + 1000000);
+        Date keyValidityEndDateForConsumption = new Date(System.currentTimeMillis() + 10000000);
+
+        Date certNotBefore = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7);
+        Date certNotAfter = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7);
+        BigInteger certSerialNumber = new BigInteger("12345678");
+        X500Principal certSubject = new X500Principal("cn=hello");
+        generator.initialize(new KeyGenParameterSpec.Builder(
+                TEST_ALIAS_1,
+                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY
+                        | KeyProperties.PURPOSE_ENCRYPT)
+                .setKeySize(256)
+                .setDigests(KeyProperties.DIGEST_SHA256)
+                .setKeyValidityStart(keyValidityStart)
+                .setKeyValidityForOriginationEnd(keyValidityEndDateForOrigination)
+                .setKeyValidityForConsumptionEnd(keyValidityEndDateForConsumption)
+                .setCertificateSerialNumber(certSerialNumber)
+                .setCertificateSubject(certSubject)
+                .setCertificateNotBefore(certNotBefore)
+                .setCertificateNotAfter(certNotAfter)
+                .setUnlockedDeviceRequired(true)
+                .setIsStrongBoxBacked(true)
+                .build());
+        KeyPair keyPair = generator.generateKeyPair();
+        assertGeneratedKeyPairAndSelfSignedCertificate(
+                keyPair,
+                TEST_ALIAS_1,
+                "EC",
+                256,
+                certSubject,
+                certSerialNumber,
+                certNotBefore,
+                certNotAfter);
+        TestUtils.assertECParameterSpecEqualsIgnoreSeedIfNotPresent(
+                ECCurves.NIST_P_256_SPEC, ((ECKey) keyPair.getPrivate()).getParams());
+        KeyInfo keyInfo = TestUtils.getKeyInfo(keyPair.getPrivate());
+        assertEquals(256, keyInfo.getKeySize());
+        assertEquals(TEST_ALIAS_1, keyInfo.getKeystoreAlias());
+        assertOneOf(keyInfo.getOrigin(),
+                KeyProperties.ORIGIN_GENERATED, KeyProperties.ORIGIN_UNKNOWN);
+        assertEquals(
+                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY
+                        | KeyProperties.PURPOSE_ENCRYPT,
+                keyInfo.getPurposes());
+        assertEquals(keyValidityStart, keyInfo.getKeyValidityStart());
+        assertEquals(keyValidityEndDateForOrigination, keyInfo.getKeyValidityForOriginationEnd());
+        assertEquals(keyValidityEndDateForConsumption, keyInfo.getKeyValidityForConsumptionEnd());
+        MoreAsserts.assertEmpty(Arrays.asList(keyInfo.getBlockModes()));
+
+        List<String> actualDigests = new ArrayList<String>(Arrays.asList(keyInfo.getDigests()));
+        // Keystore may have added DIGEST_NONE, to allow software digesting.
+        actualDigests.remove(KeyProperties.DIGEST_NONE);
+        TestUtils.assertContentsInAnyOrder(
+                actualDigests, KeyProperties.DIGEST_SHA256);
+
+        MoreAsserts.assertEmpty(Arrays.asList(keyInfo.getSignaturePaddings()));
+        MoreAsserts.assertEmpty(Arrays.asList(keyInfo.getEncryptionPaddings()));
+        assertFalse(keyInfo.isUserAuthenticationRequired());
+        assertEquals(-1, keyInfo.getUserAuthenticationValidityDurationSeconds());
+    }
+
     public void testGenerate_RSA_ModernSpec_AsCustomAsPossible() throws Exception {
         KeyPairGenerator generator = getRsaGenerator();
         Date keyValidityStart = new Date(System.currentTimeMillis());
@@ -900,12 +1009,107 @@
         assertEquals(-1, keyInfo.getUserAuthenticationValidityDurationSeconds());
     }
 
+    // Strongbox has more restrictions on key properties than general keystore.
+    // This is a reworking of the generic test to still be as custom as possible while
+    // respecting the spec constraints.
+    // Test fails until the resolution of b/113276806
+    public void testGenerate_RSA_ModernSpec_AsCustomAsPossibleStrongbox() throws Exception {
+        KeyPairGenerator generator = getRsaGenerator();
+        Date keyValidityStart = new Date(System.currentTimeMillis());
+        Date keyValidityEndDateForOrigination = new Date(System.currentTimeMillis() + 1000000);
+        Date keyValidityEndDateForConsumption = new Date(System.currentTimeMillis() + 10000000);
+
+        Date certNotBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 210);
+        Date certNotAfter = new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 210);
+        BigInteger certSerialNumber = new BigInteger("1234567890");
+        X500Principal certSubject = new X500Principal("cn=hello2");
+        generator.initialize(new KeyGenParameterSpec.Builder(
+                TEST_ALIAS_1,
+                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY
+                        | KeyProperties.PURPOSE_ENCRYPT)
+                .setAlgorithmParameterSpec(
+                        new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F0))
+                .setKeySize(2048)
+                .setDigests(KeyProperties.DIGEST_SHA256)
+                .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PSS,
+                        KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
+                .setBlockModes(KeyProperties.BLOCK_MODE_ECB)
+                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP,
+                        KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
+                .setKeyValidityStart(keyValidityStart)
+                .setKeyValidityForOriginationEnd(keyValidityEndDateForOrigination)
+                .setKeyValidityForConsumptionEnd(keyValidityEndDateForConsumption)
+                .setCertificateSerialNumber(certSerialNumber)
+                .setCertificateSubject(certSubject)
+                .setCertificateNotBefore(certNotBefore)
+                .setCertificateNotAfter(certNotAfter)
+                .setUnlockedDeviceRequired(true)
+                .setIsStrongBoxBacked(true)
+                .build());
+        KeyPair keyPair = generator.generateKeyPair();
+        assertGeneratedKeyPairAndSelfSignedCertificate(
+                keyPair,
+                TEST_ALIAS_1,
+                "RSA",
+                2048,
+                certSubject,
+                certSerialNumber,
+                certNotBefore,
+                certNotAfter);
+        assertEquals(RSAKeyGenParameterSpec.F0,
+                ((RSAPublicKey) keyPair.getPublic()).getPublicExponent());
+        KeyInfo keyInfo = TestUtils.getKeyInfo(keyPair.getPrivate());
+        assertEquals(2048, keyInfo.getKeySize());
+        assertEquals(TEST_ALIAS_1, keyInfo.getKeystoreAlias());
+        assertOneOf(keyInfo.getOrigin(),
+                KeyProperties.ORIGIN_GENERATED, KeyProperties.ORIGIN_UNKNOWN);
+        assertEquals(
+                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY
+                        | KeyProperties.PURPOSE_ENCRYPT,
+                keyInfo.getPurposes());
+        assertEquals(keyValidityStart, keyInfo.getKeyValidityStart());
+        assertEquals(keyValidityEndDateForOrigination, keyInfo.getKeyValidityForOriginationEnd());
+        assertEquals(keyValidityEndDateForConsumption, keyInfo.getKeyValidityForConsumptionEnd());
+
+        List<String> actualDigests =
+	    new ArrayList<String>(Arrays.asList(keyInfo.getDigests()));
+        // Keystore may have added DIGEST_NONE, to allow software digesting.
+        actualDigests.remove(KeyProperties.DIGEST_NONE);
+        TestUtils.assertContentsInAnyOrder(
+                actualDigests, KeyProperties.DIGEST_SHA256);
+
+        TestUtils.assertContentsInAnyOrder(Arrays.asList(keyInfo.getSignaturePaddings()),
+                KeyProperties.SIGNATURE_PADDING_RSA_PKCS1,
+                KeyProperties.SIGNATURE_PADDING_RSA_PSS);
+        MoreAsserts.assertContentsInAnyOrder(Arrays.asList(keyInfo.getBlockModes()),
+                KeyProperties.BLOCK_MODE_ECB);
+
+        List<String> actualEncryptionPaddings =
+                new ArrayList<String>(Arrays.asList(keyInfo.getEncryptionPaddings()));
+        // Keystore may have added ENCRYPTION_PADDING_NONE, to allow software padding.
+        actualEncryptionPaddings.remove(KeyProperties.ENCRYPTION_PADDING_NONE);
+        TestUtils.assertContentsInAnyOrder(actualEncryptionPaddings,
+                KeyProperties.ENCRYPTION_PADDING_RSA_OAEP,
+                KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1);
+
+        assertFalse(keyInfo.isUserAuthenticationRequired());
+        assertEquals(-1, keyInfo.getUserAuthenticationValidityDurationSeconds());
+    }
+
     public void testGenerate_EC_ModernSpec_UsableForTLSPeerAuth() throws Exception {
+        testGenerate_EC_ModernSpec_UsableForTLSPeerAuthHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerate_EC_ModernSpec_UsableForTLSPeerAuthHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testGenerate_EC_ModernSpec_UsableForTLSPeerAuthHelper(boolean useStrongbox) throws Exception {
         KeyPairGenerator generator = getEcGenerator();
         generator.initialize(new KeyGenParameterSpec.Builder(
                 TEST_ALIAS_1,
                 KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                 .setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_SHA384)
+                .setIsStrongBoxBacked(useStrongbox)
                 .build());
         KeyPair keyPair = generator.generateKeyPair();
         assertGeneratedKeyPairAndSelfSignedCertificate(
@@ -972,6 +1176,13 @@
     // that at least one fingerprint is enrolled.
 
     public void testGenerate_EC_ModernSpec_KeyNotYetValid() throws Exception {
+        testGenerate_EC_ModernSpec_KeyNotYetValidHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerate_EC_ModernSpec_KeyNotYetValidHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testGenerate_EC_ModernSpec_KeyNotYetValidHelper(boolean useStrongbox) throws Exception {
         KeyPairGenerator generator = getEcGenerator();
         Date validityStart = new Date(System.currentTimeMillis() + DAY_IN_MILLIS);
         generator.initialize(new KeyGenParameterSpec.Builder(
@@ -980,6 +1191,7 @@
                 .setKeySize(256)
                 .setDigests(KeyProperties.DIGEST_SHA256)
                 .setKeyValidityStart(validityStart)
+                .setIsStrongBoxBacked(useStrongbox)
                 .build());
         KeyPair keyPair = generator.generateKeyPair();
         assertGeneratedKeyPairAndSelfSignedCertificate(
@@ -1025,27 +1237,47 @@
         assertKeyGenUsingECSizeOnlyUsesCorrectCurve(256, ECCurves.NIST_P_256_SPEC);
         assertKeyGenUsingECSizeOnlyUsesCorrectCurve(384, ECCurves.NIST_P_384_SPEC);
         assertKeyGenUsingECSizeOnlyUsesCorrectCurve(521, ECCurves.NIST_P_521_SPEC);
+        if (TestUtils.hasStrongBox(getContext())) {
+                    assertKeyGenUsingECSizeOnlyUsesCorrectCurve(256, ECCurves.NIST_P_256_SPEC, true);
+        }
     }
 
+    //TODO: Fix b/113108008 so this test will pass for strongbox.
     public void testGenerate_EC_ModernSpec_UnsupportedSizesRejected() throws Exception {
         for (int keySizeBits = 0; keySizeBits <= 1024; keySizeBits++) {
+            testGenerate_EC_ModernSpec_UnsupportedSizesRejectedHelper(false, keySizeBits);
+            if (TestUtils.hasStrongBox(getContext())) {
+                testGenerate_EC_ModernSpec_UnsupportedSizesRejectedHelper(true, keySizeBits);
+            }
+        }
+    }
+
+    private void testGenerate_EC_ModernSpec_UnsupportedSizesRejectedHelper(boolean useStrongbox, int keySizeBits) throws Exception {
+        if (!useStrongbox) {
             if ((keySizeBits == 224) || (keySizeBits == 256) || (keySizeBits == 384)
                     || (keySizeBits == 521)) {
                 // Skip supported sizes
-                continue;
+                return;
             }
-            KeyPairGenerator generator = getEcGenerator();
+        } else {
+            // Strongbox only supports 256 bit EC key size
+            if (keySizeBits == 256) {
+                return;
+            }
+        }
+        KeyPairGenerator generator = getEcGenerator();
 
-            try {
-                generator.initialize(new KeyGenParameterSpec.Builder(
-                        TEST_ALIAS_1,
-                        KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
-                        .setKeySize(keySizeBits)
-                        .build());
-                fail("EC KeyPairGenerator initialized with unsupported key size: "
-                        + keySizeBits + " bits");
-            } catch (InvalidAlgorithmParameterException expected) {
-            }
+        try {
+            generator.initialize(new KeyGenParameterSpec.Builder(
+                    TEST_ALIAS_1,
+                    KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
+                    .setKeySize(keySizeBits)
+                    .setIsStrongBoxBacked(useStrongbox)
+                    .build());
+            fail("EC KeyPairGenerator initialized with unsupported key size: "
+                    + keySizeBits + " bits. useStrongbox: " + useStrongbox
+                    + "\nThis test will fail until b/113108008 is resolved");
+        } catch (InvalidAlgorithmParameterException expected) {
         }
     }
 
@@ -1062,6 +1294,15 @@
         assertKeyGenUsingECNamedCurveSupported("prime256v1", ECCurves.NIST_P_256_SPEC);
         assertKeyGenUsingECNamedCurveSupported("PRIME256V1", ECCurves.NIST_P_256_SPEC);
 
+        if (TestUtils.hasStrongBox(getContext())) {
+            assertKeyGenUsingECNamedCurveSupported("P-256", ECCurves.NIST_P_256_SPEC, true);
+            assertKeyGenUsingECNamedCurveSupported("p-256", ECCurves.NIST_P_256_SPEC, true);
+            assertKeyGenUsingECNamedCurveSupported("secp256r1", ECCurves.NIST_P_256_SPEC, true);
+            assertKeyGenUsingECNamedCurveSupported("SECP256R1", ECCurves.NIST_P_256_SPEC, true);
+            assertKeyGenUsingECNamedCurveSupported("prime256v1", ECCurves.NIST_P_256_SPEC, true);
+            assertKeyGenUsingECNamedCurveSupported("PRIME256V1", ECCurves.NIST_P_256_SPEC, true);
+        }
+
         assertKeyGenUsingECNamedCurveSupported("P-384", ECCurves.NIST_P_384_SPEC);
         assertKeyGenUsingECNamedCurveSupported("p-384", ECCurves.NIST_P_384_SPEC);
         assertKeyGenUsingECNamedCurveSupported("secp384r1", ECCurves.NIST_P_384_SPEC);
@@ -1078,6 +1319,9 @@
         assertKeyGenUsingRSASizeOnlySupported(768);
         assertKeyGenUsingRSASizeOnlySupported(1024);
         assertKeyGenUsingRSASizeOnlySupported(2048);
+        if (TestUtils.hasStrongBox(getContext())) {
+            assertKeyGenUsingRSASizeOnlySupported(2048, true);
+        }
         assertKeyGenUsingRSASizeOnlySupported(3072);
         assertKeyGenUsingRSASizeOnlySupported(4096);
 
@@ -1088,8 +1332,16 @@
     }
 
     public void testGenerate_RSA_IndCpaEnforced() throws Exception {
+        testGenerate_RSA_IndCpaEnforcedHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerate_RSA_IndCpaEnforcedHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testGenerate_RSA_IndCpaEnforcedHelper(boolean useStrongbox) throws Exception {
         KeyGenParameterSpec.Builder goodBuilder = new KeyGenParameterSpec.Builder(
                 TEST_ALIAS_1, KeyProperties.PURPOSE_ENCRYPT)
+                .setIsStrongBoxBacked(useStrongbox)
                 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP,
                         KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1);
         assertKeyGenInitSucceeds("RSA", goodBuilder.build());
@@ -1119,8 +1371,16 @@
     }
 
     public void testGenerate_EC_IndCpaEnforced() throws Exception {
+        testGenerate_EC_IndCpaEnforcedHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerate_EC_IndCpaEnforcedHelper(true /* useStrongbox */);
+        }
+    }
+
+    public void testGenerate_EC_IndCpaEnforcedHelper(boolean useStrongbox) throws Exception {
         KeyGenParameterSpec.Builder goodBuilder = new KeyGenParameterSpec.Builder(
-                TEST_ALIAS_2, KeyProperties.PURPOSE_ENCRYPT);
+                TEST_ALIAS_2, KeyProperties.PURPOSE_ENCRYPT)
+                .setIsStrongBoxBacked(useStrongbox);
         assertKeyGenInitSucceeds("EC", goodBuilder.build());
 
         // Should be fine because IND-CPA restriction applies only to encryption keys
@@ -1143,6 +1403,13 @@
 
     // http://b/28384942
     public void testGenerateWithFarsiLocale() throws Exception {
+        testGenerateWithFarsiLocaleHelper(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testGenerateWithFarsiLocaleHelper(true /* useStrongbox */);
+        }
+    }
+
+    private void testGenerateWithFarsiLocaleHelper(boolean useStrongbox) throws Exception {
         Locale defaultLocale = Locale.getDefault();
         // Note that we use farsi here because its number formatter doesn't use
         // arabic digits.
@@ -1159,6 +1426,7 @@
                    TEST_ALIAS_1, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_ECB)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
+                   .setIsStrongBoxBacked(useStrongbox)
                    .build());
 
             keyGenerator.generateKeyPair();
@@ -1184,11 +1452,17 @@
 
     private void assertKeyGenUsingECSizeOnlyUsesCorrectCurve(
             int keySizeBits, ECParameterSpec expectedParams) throws Exception {
+        assertKeyGenUsingECSizeOnlyUsesCorrectCurve(keySizeBits, expectedParams, false);
+    }
+
+    private void assertKeyGenUsingECSizeOnlyUsesCorrectCurve(
+            int keySizeBits, ECParameterSpec expectedParams, boolean useStrongbox) throws Exception {
         KeyPairGenerator generator = getEcGenerator();
         generator.initialize(new KeyGenParameterSpec.Builder(
                 TEST_ALIAS_1,
                 KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                 .setKeySize(keySizeBits)
+                .setIsStrongBoxBacked(useStrongbox)
                 .build(),
                 mRng);
         mRng.resetCounters();
@@ -1214,11 +1488,16 @@
 
     private void assertKeyGenUsingECNamedCurveSupported(
             String curveName, ECParameterSpec expectedParams) throws Exception {
+        assertKeyGenUsingECNamedCurveSupported(curveName, expectedParams, false);
+    }
+    private void assertKeyGenUsingECNamedCurveSupported(
+            String curveName, ECParameterSpec expectedParams, boolean useStrongbox) throws Exception {
         KeyPairGenerator generator = getEcGenerator();
         generator.initialize(new KeyGenParameterSpec.Builder(
                 TEST_ALIAS_1,
                 KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                 .setAlgorithmParameterSpec(new ECGenParameterSpec(curveName))
+                .setIsStrongBoxBacked(useStrongbox)
                 .build(),
                 mRng);
         mRng.resetCounters();
@@ -1243,11 +1522,16 @@
     }
 
     private void assertKeyGenUsingRSASizeOnlySupported(int keySizeBits) throws Exception {
+        assertKeyGenUsingRSASizeOnlySupported(keySizeBits, false);
+    }
+
+    private void assertKeyGenUsingRSASizeOnlySupported(int keySizeBits, boolean useStrongbox) throws Exception {
         KeyPairGenerator generator = getRsaGenerator();
         generator.initialize(new KeyGenParameterSpec.Builder(
                 TEST_ALIAS_1,
                 KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                 .setKeySize(keySizeBits)
+                .setIsStrongBoxBacked(useStrongbox)
                 .build(),
                 mRng);
         mRng.resetCounters();
diff --git a/tests/tests/location/src/android/location/cts/GnssLocationValuesTest.java b/tests/tests/location/src/android/location/cts/GnssLocationValuesTest.java
index d2499a0..2d64612 100644
--- a/tests/tests/location/src/android/location/cts/GnssLocationValuesTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssLocationValuesTest.java
@@ -63,6 +63,13 @@
    * only test them if the hardware is later than 2017
    */
   public void testAccuracyFields() 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.
+    if (!TestMeasurementUtil.canTestRunOnCurrentDevice(mTestLocationManager,
+            TAG, MIN_HARDWARE_YEAR_MEASUREMENTS_REQUIRED, isCtsVerifierTest())) {
+        return;
+    }
+
     SoftAssert softAssert = new SoftAssert(TAG);
     mTestLocationManager.requestLocationUpdates(mLocationListener);
     boolean success = mLocationListener.await();
@@ -122,6 +129,13 @@
    * check whether all fields' value make sense
    */
   public void testLocationRegularFields() 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.
+    if (!TestMeasurementUtil.canTestRunOnCurrentDevice(mTestLocationManager,
+            TAG, MIN_HARDWARE_YEAR_MEASUREMENTS_REQUIRED, isCtsVerifierTest())) {
+        return;
+    }
+
     mTestLocationManager.requestLocationUpdates(mLocationListener);
     boolean success = mLocationListener.await();
     SoftAssert.failOrWarning(isMeasurementTestStrict(),
diff --git a/tests/tests/location/src/android/location/cts/GnssMeasurementWhenNoLocationTest.java b/tests/tests/location/src/android/location/cts/GnssMeasurementWhenNoLocationTest.java
index 5edca64..9af7a7d 100644
--- a/tests/tests/location/src/android/location/cts/GnssMeasurementWhenNoLocationTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssMeasurementWhenNoLocationTest.java
@@ -22,6 +22,8 @@
 import android.platform.test.annotations.AppModeFull;
 import android.util.Log;
 
+import com.android.compatibility.common.util.SystemUtil;
+
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
@@ -100,91 +102,115 @@
             return;
         }
 
-        // Clear A-GPS and skip the test if the operation fails.
-        if (!mTestLocationManager.sendExtraCommand(AGPS_DELETE_COMMAND)) {
-            Log.i(TAG, "A-GPS failed to clear. Skip test.");
-            return;
+        // Set the device in airplane mode so that the GPS assistance data cannot be downloaded.
+        // This results in GNSS measurements being reported before a location is reported.
+        // NOTE: Changing global setting airplane_mode_on is not allowed in CtsVerifier application.
+        //       Hence, airplane mode is turned on only when this test is run as a regular CTS test
+        //       and not when it is invoked through CtsVerifier.
+        boolean isAirplaneModeOffBeforeTest = true;
+        if (!isCtsVerifierTest()) {
+            // Record the state of the airplane mode before the test so that we can restore it
+            // after the test.
+            isAirplaneModeOffBeforeTest = !TestUtils.isAirplaneModeOn();
+            if (isAirplaneModeOffBeforeTest) {
+                TestUtils.setAirplaneModeOn(getContext(), true);
+            }
         }
 
-        // Register for GPS measurements.
-        mMeasurementListener = new TestGnssMeasurementListener(TAG, EVENTS_COUNT);
-        mTestLocationManager.registerGnssMeasurementCallback(mMeasurementListener);
+        try {
+            // Clear A-GPS and skip the test if the operation fails.
+            if (!mTestLocationManager.sendExtraCommand(AGPS_DELETE_COMMAND)) {
+                Log.i(TAG, "A-GPS failed to clear. Skip test.");
+                return;
+            }
 
-        // Register for Gps Status updates.
-        mGpsStatusListener = new TestGpsStatusListener(EVENTS_COUNT, mTestLocationManager);
-        mTestLocationManager.addGpsStatusListener(mGpsStatusListener);
+            // Register for GPS measurements.
+            mMeasurementListener = new TestGnssMeasurementListener(TAG, EVENTS_COUNT);
+            mTestLocationManager.registerGnssMeasurementCallback(mMeasurementListener);
 
-        // Register for location updates.
-        mLocationListener = new TestLocationListener(LOCATIONS_COUNT);
-        mTestLocationManager.requestLocationUpdates(mLocationListener);
+            // Register for Gps Status updates.
+            mGpsStatusListener = new TestGpsStatusListener(EVENTS_COUNT, mTestLocationManager);
+            mTestLocationManager.addGpsStatusListener(mGpsStatusListener);
 
-        mMeasurementListener.awaitStatus();
-        if (!mMeasurementListener.verifyStatus(isMeasurementTestStrict())) {
-            return; // exit peacefully (if not already asserted out inside verifyStatus)
+            // Register for location updates.
+            mLocationListener = new TestLocationListener(LOCATIONS_COUNT);
+            mTestLocationManager.requestLocationUpdates(mLocationListener);
+
+            mMeasurementListener.awaitStatus();
+            if (!mMeasurementListener.verifyStatus(isMeasurementTestStrict())) {
+                return; // exit peacefully (if not already asserted out inside verifyStatus)
+            }
+
+            // Wait for two measurement events - this is better than waiting for a location
+            // calculation because the test generally completes much faster.
+            mMeasurementListener.await();
+
+            Log.i(TAG, "mLocationListener.isLocationReceived(): "
+                    + mLocationListener.isLocationReceived());
+
+            SoftAssert.failOrWarning(isMeasurementTestStrict(),
+                    "No Satellites are visible. Device may be indoors.  Retry outdoors?",
+                    mGpsStatusListener.isGpsStatusReceived());
+
+            List<GnssMeasurementsEvent> events = mMeasurementListener.getEvents();
+            Log.i(TAG, "Number of GPS measurement events received = " + events.size());
+
+            if (events.isEmpty()) {
+                SoftAssert.failOrWarning(isMeasurementTestStrict(),
+                        "No measurement events received",
+                        false);
+                return;  // All of the following checks rely on there being measurements
+            }
+
+            // Ensure that after getting a few (at least 2) measurement events, that we still
+            // don't have location (i.e. that we got measurements before location.)  Fail, if
+            // strict, warn, if not.
+            SoftAssert.failOrWarning(isMeasurementTestStrict(),
+                    "Location was received before " + events.size() +
+                            " GnssMeasurementEvents with measurements were reported. " +
+                            "Test expects at least " + EVENTS_COUNT +
+                            " GnssMeasurementEvents before a location, given the cold start" +
+                            " start. Ensure no other active GPS apps (so the cold start" +
+                            " command works) and retry?",
+                    !mLocationListener.isLocationReceived());
+            if (mLocationListener.isLocationReceived() && !isMeasurementTestStrict()) {
+                return; // allow a (passing) return, if not strict, otherwise continue
+            }
+
+            // If device has received measurements also verify
+            // that mandatory fields of GnssMeasurement are in expected ranges.
+            GnssMeasurementsEvent firstEvent = events.get(0);
+            Collection<GnssMeasurement> gpsMeasurements = firstEvent.getMeasurements();
+            int satelliteCount = gpsMeasurements.size();
+            int[] gpsPrns = new int[satelliteCount];
+            int i = 0;
+            for (GnssMeasurement measurement : gpsMeasurements) {
+                gpsPrns[i] = measurement.getSvid();
+                ++i;
+            }
+            Log.i(TAG, "First GnssMeasurementsEvent with PRNs=" + Arrays.toString(gpsPrns));
+
+            SoftAssert softAssert = new SoftAssert(TAG);
+            long timeInNs = firstEvent.getClock().getTimeNanos();
+            softAssert.assertTrue("GPS measurement satellite count check: ",
+                    timeInNs, // event time in ns
+                    "satelliteCount > 0", // expected value
+                    Integer.toString(satelliteCount), // actual value
+                    satelliteCount > 0); // condition
+
+            TestMeasurementUtil.assertGnssClockFields(firstEvent.getClock(), softAssert, timeInNs);
+
+            // Verify mandatory fields of GnssMeasurement
+            for (GnssMeasurement measurement : gpsMeasurements) {
+                TestMeasurementUtil.assertAllGnssMeasurementMandatoryFields(mTestLocationManager,
+                        measurement, softAssert, timeInNs);
+            }
+            softAssert.assertAll();
+        } finally {
+            // Set the airplane mode back to off if it was off before this test.
+            if (!isCtsVerifierTest() && isAirplaneModeOffBeforeTest) {
+                TestUtils.setAirplaneModeOn(getContext(), false);
+            }
         }
-
-        // Wait for two measurement events - this is better than waiting for a location calculation
-        // because the test generally completes much faster.
-        mMeasurementListener.await();
-
-        Log.i(TAG, "mLocationListener.isLocationReceived(): "
-                + mLocationListener.isLocationReceived());
-
-        SoftAssert.failOrWarning(isMeasurementTestStrict(),
-                "No Satellites are visible. Device may be indoors.  Retry outdoors?",
-                mGpsStatusListener.isGpsStatusReceived());
-
-        List<GnssMeasurementsEvent> events = mMeasurementListener.getEvents();
-        Log.i(TAG, "Number of GPS measurement events received = " + events.size());
-
-        if (events.isEmpty()) {
-            SoftAssert.failOrWarning(isMeasurementTestStrict(), "No measurement events received",
-                    false);
-            return;  // All of the following checks rely on there being measurements
-        }
-
-        // Ensure that after getting a few (at least 2) measurement events, that we still don't have
-        // location (i.e. that we got measurements before location.)  Fail, if strict, warn, if not.
-        SoftAssert.failOrWarning(isMeasurementTestStrict(),
-                "Location was received before " + events.size() +
-                        " GnssMeasurementEvents with measurements were reported. " +
-                        "Test expects at least " + EVENTS_COUNT +
-                        " GnssMeasurementEvents before a location, given the cold start start. " +
-                        "Ensure no other active GPS apps (so the cold start command works) " +
-                        "and retry?",
-                !mLocationListener.isLocationReceived());
-        if (mLocationListener.isLocationReceived() && !isMeasurementTestStrict()) {
-            return; // allow a (passing) return, if not strict, otherwise continue
-        }
-
-        // If device has received measurements also verify
-        // that mandatory fields of GnssMeasurement are in expected ranges.
-        GnssMeasurementsEvent firstEvent = events.get(0);
-        Collection<GnssMeasurement> gpsMeasurements = firstEvent.getMeasurements();
-        int satelliteCount = gpsMeasurements.size();
-        int[] gpsPrns = new int[satelliteCount];
-        int i = 0;
-        for (GnssMeasurement measurement : gpsMeasurements) {
-            gpsPrns[i] = measurement.getSvid();
-            ++i;
-        }
-        Log.i(TAG, "First GnssMeasurementsEvent with PRNs=" + Arrays.toString(gpsPrns));
-
-        SoftAssert softAssert = new SoftAssert(TAG);
-        long timeInNs = firstEvent.getClock().getTimeNanos();
-        softAssert.assertTrue("GPS measurement satellite count check: ",
-                timeInNs, // event time in ns
-                "satelliteCount > 0", // expected value
-                Integer.toString(satelliteCount), // actual value
-                satelliteCount > 0); // condition
-
-        TestMeasurementUtil.assertGnssClockFields(firstEvent.getClock(), softAssert, timeInNs);
-
-        // Verify mandatory fields of GnssMeasurement
-        for (GnssMeasurement measurement : gpsMeasurements) {
-            TestMeasurementUtil.assertAllGnssMeasurementMandatoryFields(mTestLocationManager,
-                    measurement, softAssert, timeInNs);
-        }
-        softAssert.assertAll();
     }
 }
diff --git a/tests/tests/location/src/android/location/cts/GnssTtffTests.java b/tests/tests/location/src/android/location/cts/GnssTtffTests.java
index 335de07..af0e025 100644
--- a/tests/tests/location/src/android/location/cts/GnssTtffTests.java
+++ b/tests/tests/location/src/android/location/cts/GnssTtffTests.java
@@ -86,12 +86,12 @@
    */
   private void ensureNetworkStatus(){
     assertTrue("Device has to connect to Wifi or Cellular to complete this test.",
-        isConnectedToWifiOrCellular(getContext()));
+        TestUtils.isConnectedToWifiOrCellular(getContext()));
 
   }
 
   private boolean hasCellularData() {
-    ConnectivityManager connManager = getConnectivityManager(getContext());
+    ConnectivityManager connManager = TestUtils.getConnectivityManager(getContext());
     NetworkInfo cellularNetworkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
     // check whether the cellular data is ON if the device has cellular capability
     if (cellularNetworkInfo == null) {
@@ -143,44 +143,4 @@
     softAssert.assertTrue("Test case: " + testName +", TTFF should be less than " + threshold
         + " . In current test, TTFF value is: " + ttffTimeMillis, ttffTimeMillis < threshold);
   }
-
-  /**
-   * Returns whether the device is currently connected to a wifi or cellular.
-   *
-   * @param context {@link Context} object
-   * @return {@code true} if connected to Wifi or Cellular; {@code false} otherwise
-   */
-  public static boolean isConnectedToWifiOrCellular(Context context) {
-    NetworkInfo info = getActiveNetworkInfo(context);
-    return info != null
-        && info.isConnected()
-        && (info.getType() == ConnectivityManager.TYPE_WIFI
-                 || info.getType() == ConnectivityManager.TYPE_MOBILE);
-  }
-
-  /**
-   * Gets the active network info.
-   *
-   * @param context {@link Context} object
-   * @return {@link NetworkInfo}
-   */
-  private static NetworkInfo getActiveNetworkInfo(Context context) {
-    ConnectivityManager cm = getConnectivityManager(context);
-    if (cm != null) {
-      return cm.getActiveNetworkInfo();
-    }
-    return null;
-  }
-
-  /**
-   * Gets the connectivity manager.
-   *
-   * @param context {@link Context} object
-   * @return {@link ConnectivityManager}
-   */
-  private static ConnectivityManager getConnectivityManager(Context context) {
-    return (ConnectivityManager) context.getApplicationContext()
-        .getSystemService(Context.CONNECTIVITY_SERVICE);
-  }
-
-}
\ No newline at end of file
+}
diff --git a/tests/tests/location/src/android/location/cts/TestGnssMeasurementListener.java b/tests/tests/location/src/android/location/cts/TestGnssMeasurementListener.java
index 3a64c46..87a3f77 100644
--- a/tests/tests/location/src/android/location/cts/TestGnssMeasurementListener.java
+++ b/tests/tests/location/src/android/location/cts/TestGnssMeasurementListener.java
@@ -37,7 +37,7 @@
     private boolean filterByEventSize = false;
     // Timeout in sec for count down latch wait
     private static final int STATUS_TIMEOUT_IN_SEC = 10;
-    private static final int MEAS_TIMEOUT_IN_SEC = 60;
+    private static final int MEAS_TIMEOUT_IN_SEC = 75;
     private static final int C_TO_N0_THRESHOLD_DB_HZ = 18;
     private volatile int mStatus = -1;
 
diff --git a/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java b/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
index 7852361..940146e 100644
--- a/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
+++ b/tests/tests/location/src/android/location/cts/TestMeasurementUtil.java
@@ -593,6 +593,15 @@
                             "0 >= X <= 7 days",
                             String.valueOf(sv_time_days),
                             sv_time_days >= 0 && sv_time_days <= 7);
+                } else if ((state & GnssMeasurement.STATE_TOW_KNOWN)
+                        == GnssMeasurement.STATE_TOW_KNOWN) {
+                    softAssert.assertTrue(getReceivedSvTimeNsLogMessage(
+                                    "GNSS_MEASUREMENT_STATE_TOW_KNOWN",
+                                    "GnssStatus.CONSTELLATION_BEIDOU"),
+                            timeInNs,
+                            "0 >= X <= 7 days",
+                            String.valueOf(sv_time_days),
+                            sv_time_days >= 0 && sv_time_days <= 7);
                 } else if ((state & GnssMeasurement.STATE_SUBFRAME_SYNC)
                         == GnssMeasurement.STATE_SUBFRAME_SYNC) {
                     softAssert.assertTrue(getReceivedSvTimeNsLogMessage(
@@ -675,6 +684,15 @@
                     "0 >= X <= 7 days",
                     String.valueOf(sv_time_days),
                     sv_time_days >= 0 && sv_time_days <= 7);
+        } else if ((state & GnssMeasurement.STATE_TOW_KNOWN)
+                == GnssMeasurement.STATE_TOW_KNOWN) {
+            softAssert.assertTrue(getReceivedSvTimeNsLogMessage(
+                            "GNSS_MEASUREMENT_STATE_TOW_KNOWN",
+                            constellationType),
+                    timeInNs,
+                    "0 >= X <= 7 days",
+                    String.valueOf(sv_time_days),
+                    sv_time_days >= 0 && sv_time_days <= 7);
         } else if ((state & GnssMeasurement.STATE_SUBFRAME_SYNC)
                 == GnssMeasurement.STATE_SUBFRAME_SYNC) {
             softAssert.assertTrue(getReceivedSvTimeNsLogMessage(
diff --git a/tests/tests/location/src/android/location/cts/TestUtils.java b/tests/tests/location/src/android/location/cts/TestUtils.java
index 3c3f21d..3a0100b 100644
--- a/tests/tests/location/src/android/location/cts/TestUtils.java
+++ b/tests/tests/location/src/android/location/cts/TestUtils.java
@@ -18,16 +18,25 @@
 
 import android.content.Context;
 import android.content.pm.PackageManager;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
 import android.util.Log;
 
+import com.android.compatibility.common.util.SystemUtil;
+
 import java.util.concurrent.Callable;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
 public class TestUtils {
+    private static final String TAG = "LocationTestUtils";
+
     private static final long STANDARD_WAIT_TIME_MS = 50;
     private static final long STANDARD_SLEEP_TIME_MS = 50;
 
+    private static final int DATA_CONNECTION_CHECK_INTERVAL_MS = 500;
+    private static final int DATA_CONNECTION_CHECK_COUNT = 10; // 500 * 10 - Roughly 5 secs wait
+
     public static boolean waitFor(CountDownLatch latch, int timeInSec) throws InterruptedException {
         // Since late 2014, if the main thread has been occupied for long enough, Android will
         // increase its priority. Such new behavior can causes starvation to the background thread -
@@ -67,7 +76,85 @@
         if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) {
             return true;
         }
-        Log.w("LocationTestUtils", "GPS feature not present on device, skipping GPS test.");
+        Log.w(TAG, "GPS feature not present on device, skipping GPS test.");
         return false;
     }
+
+    /**
+     * Returns whether the device is currently connected to a wifi or cellular.
+     *
+     * @param context {@link Context} object
+     * @return {@code true} if connected to Wifi or Cellular; {@code false} otherwise
+     */
+    public static boolean isConnectedToWifiOrCellular(Context context) {
+        NetworkInfo info = getActiveNetworkInfo(context);
+        return info != null
+                && info.isConnected()
+                && (info.getType() == ConnectivityManager.TYPE_WIFI
+                || info.getType() == ConnectivityManager.TYPE_MOBILE);
+    }
+
+    /**
+     * Gets the active network info.
+     *
+     * @param context {@link Context} object
+     * @return {@link NetworkInfo}
+     */
+    private static NetworkInfo getActiveNetworkInfo(Context context) {
+        ConnectivityManager cm = getConnectivityManager(context);
+        if (cm != null) {
+            return cm.getActiveNetworkInfo();
+        }
+        return null;
+    }
+
+    /**
+     * Gets the connectivity manager.
+     *
+     * @param context {@link Context} object
+     * @return {@link ConnectivityManager}
+     */
+    public static ConnectivityManager getConnectivityManager(Context context) {
+        return (ConnectivityManager) context.getApplicationContext()
+                .getSystemService(Context.CONNECTIVITY_SERVICE);
+    }
+
+    /**
+     * Returns {@code true} if the setting {@code airplane_mode_on} is set to 1.
+     */
+    public static boolean isAirplaneModeOn() {
+        return SystemUtil.runShellCommand("settings get global airplane_mode_on")
+                .trim().equals("1");
+    }
+
+    /**
+     * Changes the setting {@code airplane_mode_on} to 1 if {@code enableAirplaneMode}
+     * is {@code true}. Otherwise, it is set to 0.
+     *
+     * <p>Waits for a certain time duration for network connections to turn on/off based on
+     * {@code enableAirplaneMode}.
+     */
+    public static void setAirplaneModeOn(Context context,
+            boolean enableAirplaneMode) throws InterruptedException {
+        Log.i(TAG, "Setting airplane_mode_on to " + enableAirplaneMode);
+        SystemUtil.runShellCommand("cmd connectivity airplane-mode "
+                + (enableAirplaneMode ? "enable" : "disable"));
+
+        // Wait for a few seconds until the airplane mode changes take effect. The airplane mode on
+        // state and the WiFi/cell connected state are opposite. So, we wait while they are the
+        // same or until the specified time interval expires.
+        //
+        // Note that in unusual cases where the WiFi/cell are not in a connected state before
+        // turning on airplane mode, then turning off airplane mode won't restore either of
+        // these connections, and then the wait time below will be wasteful.
+        int dataConnectionCheckCount = DATA_CONNECTION_CHECK_COUNT;
+        while (enableAirplaneMode == isConnectedToWifiOrCellular(context)) {
+            if (--dataConnectionCheckCount <= 0) {
+                Log.w(TAG, "Airplane mode " + (enableAirplaneMode ? "on" : "off")
+                        + " setting did not take effect on WiFi/cell connected state.");
+                return;
+            }
+            Thread.sleep(DATA_CONNECTION_CHECK_INTERVAL_MS);
+        }
+    }
 }
diff --git a/tests/tests/media/src/android/media/cts/VpxEncoderTest.java b/tests/tests/media/src/android/media/cts/VpxEncoderTest.java
index f94a566..38a8403 100644
--- a/tests/tests/media/src/android/media/cts/VpxEncoderTest.java
+++ b/tests/tests/media/src/android/media/cts/VpxEncoderTest.java
@@ -107,10 +107,15 @@
 
             VpxEncodingStatistics statistics = computeEncodingStatistics(bufInfo);
 
-            assertEquals("Stream bitrate " + statistics.mAverageBitrate +
+            /* Allow achieved bitrate to be smaller than target bitrate for
+             * VIDEO_ControlRateVariable mode */
+            if ((params.bitrateType == VIDEO_ControlRateConstant) ||
+                (statistics.mAverageBitrate > targetBitrate)) {
+                assertEquals("Stream bitrate " + statistics.mAverageBitrate +
                     " is different from the target " + targetBitrate,
                     targetBitrate, statistics.mAverageBitrate,
                     MAX_BITRATE_VARIATION * targetBitrate);
+            }
 
             decode(params.outputIvfFilename, null, codecMimeType, FPS, params.forceGoogleEncoder);
         }
diff --git a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
index 96e39bc..36f1b8a 100644
--- a/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
+++ b/tests/tests/nativehardware/jni/AHardwareBufferGLTest.cpp
@@ -702,32 +702,41 @@
     mDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
     eglInitialize(mDisplay, NULL, NULL);
 
+    // Try creating an OpenGL ES 3.x context and fall back to 2.x if that fails.
+    // Create two contexts for cross-context image sharing tests.
     EGLConfig first_config;
-    EGLint const config_attrib_list[] = {
+    EGLint config_attrib_list[] = {
         EGL_RED_SIZE, 8,
         EGL_GREEN_SIZE, 8,
         EGL_BLUE_SIZE, 8,
         EGL_ALPHA_SIZE, 8,
+        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR,
         EGL_NONE
     };
     EGLint num_config = 0;
     eglChooseConfig(mDisplay, config_attrib_list, &first_config, 1, &num_config);
-    ASSERT_LT(0, num_config);
+    if (num_config == 0) {
+        // There are no configs with the ES 3.0 bit, fall back to ES 2.0.
+        config_attrib_list[8] = EGL_NONE;
+        config_attrib_list[9] = EGL_NONE;
+        eglChooseConfig(mDisplay, config_attrib_list, &first_config, 1, &num_config);
+    }
+    ASSERT_GT(num_config, 0);
 
-    // Try creating an OpenGL ES 3.x context and fall back to 2.x if that fails.
-    // Create two contexts for cross-context image sharing tests.
     EGLint context_attrib_list[] = {
         EGL_CONTEXT_CLIENT_VERSION, 3,
         EGL_NONE
     };
-    mContext[0] = eglCreateContext(mDisplay, first_config, EGL_NO_CONTEXT, context_attrib_list);
+    // Try creating an ES 3.0 context, but don't bother if there were no ES 3.0 compatible configs.
+    if (config_attrib_list[9] != EGL_NONE) {
+        mContext[0] = eglCreateContext(mDisplay, first_config, EGL_NO_CONTEXT, context_attrib_list);
+    }
+    // If we don't have a context yet, fall back to ES 2.0.
     if (mContext[0] == EGL_NO_CONTEXT) {
         context_attrib_list[1] = 2;
         mContext[0] = eglCreateContext(mDisplay, first_config, EGL_NO_CONTEXT, context_attrib_list);
-        mContext[1] = eglCreateContext(mDisplay, first_config, EGL_NO_CONTEXT, context_attrib_list);
-    } else {
-        mContext[1] = eglCreateContext(mDisplay, first_config, EGL_NO_CONTEXT, context_attrib_list);
     }
+    mContext[1] = eglCreateContext(mDisplay, first_config, EGL_NO_CONTEXT, context_attrib_list);
     ASSERT_NE(EGL_NO_CONTEXT, mContext[0]);
     ASSERT_NE(EGL_NO_CONTEXT, mContext[1]);
 
@@ -847,6 +856,12 @@
               "GL_EXT_EGL_image_storage");
         return false;
     }
+    if (desc.usage & AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE &&
+        !HasGLExtension("GL_EXT_EGL_image_storage")) {
+        ALOGI("Test skipped: mipmapped hardware buffers require "
+              "GL_EXT_EGL_image_storage");
+        return false;
+    }
 
     int result = AHardwareBuffer_allocate(&desc, &mBuffer);
     // Skip if this format cannot be allocated.
@@ -1067,6 +1082,7 @@
                 GLuint renderbuffer = 0;
                 glGenRenderbuffers(1, &renderbuffer);
                 glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
+                ASSERT_EQ(GLenum{GL_NO_ERROR}, glGetError());
                 if (GetParam().stride & kGlFormat) {
                     glRenderbufferStorage(GL_RENDERBUFFER, GetParam().format, width, height);
                 } else {
@@ -1413,6 +1429,8 @@
     for (int i = 0; i < mContextCount; ++i) {
         MakeCurrent(i);
         SetUpTexture(desc, kTextureUnit);
+        glTexParameteri(mTexTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+        glTexParameteri(mTexTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
     }
     // In the second context, upload opaque red to the texture.
     UploadRedPixels(desc);
@@ -1459,6 +1477,8 @@
     for (int i = 0; i < mContextCount; ++i) {
         MakeCurrent(i);
         SetUpTexture(desc, kTextureUnit);
+        glTexParameteri(mTexTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+        glTexParameteri(mTexTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
     }
 
     // In the second context, draw a checkerboard pattern.
@@ -1767,7 +1787,7 @@
     glFinish();
 
     // Check the rendered pixels. There should be a square in the middle.
-    const GoldenColor kDepth = mGLVersion > 30 ? kRed : kWhite;
+    const GoldenColor kDepth = mGLVersion < 30 ? kWhite : kRed;
     std::vector<GoldenPixel> goldens{
         {5, 35, kZero}, {15, 35, kZero},  {25, 35, kZero},  {35, 35, kZero},
         {5, 25, kZero}, {15, 25, kDepth}, {25, 25, kDepth}, {35, 25, kZero},
@@ -1818,7 +1838,7 @@
         SetUpProgram(kVertexShader, kCubeMapFragmentShader, kQuadPositions, 0.5f, kTextureUnit);
     }
     SetUpFramebuffer(40, 40, 0, kRenderbuffer);
-    const GoldenColor kDepth = mGLVersion > 30 ? kRed : kWhite;
+    const GoldenColor kDepth = mGLVersion < 30 ? kWhite: kRed;
     for (int i = 0; i < 6; ++i) {
         float face_vector[3] = {0.f, 0.f, 0.f};
         face_vector[i / 2] = (i % 2) ? -1.f : 1.f;
diff --git a/tests/tests/os/src/android/os/cts/EnvironmentTest.java b/tests/tests/os/src/android/os/cts/EnvironmentTest.java
index 6f259c3..0f2ac62 100644
--- a/tests/tests/os/src/android/os/cts/EnvironmentTest.java
+++ b/tests/tests/os/src/android/os/cts/EnvironmentTest.java
@@ -81,14 +81,17 @@
         // inodes can result in wasted space.
         final long maxsize = stat.f_blocks * stat.f_frsize;
         final long maxInodes = maxsize / 4096;
-        final long minsize = stat.f_bavail * stat.f_frsize;
-        final long minInodes = minsize / 32768;
+        // Assuming the smallest storage would be 4GB, min # of free inodes
+        // in EXT4/F2FS must be larger than 128k for Android to work properly.
+        final long minInodes = 128 * 1024;
 
-        if (stat.f_ffree >= minInodes && stat.f_ffree <= maxInodes) {
+        if (stat.f_ffree >= minInodes && stat.f_ffree <= maxInodes
+            && stat.f_favail <= stat.f_ffree) {
             // Sweet, sounds great!
         } else {
-            fail("Number of inodes " + stat.f_ffree + " not within sane range for partition of "
-                    + minsize + "," + maxsize + " bytes; expected [" + minInodes + "," + maxInodes + "]");
+            fail("Number of inodes " + stat.f_ffree + "/" + stat.f_favail
+              + " not within sane range for partition of " + maxsize + " bytes; expected ["
+              + minInodes + "," + maxInodes + "]");
         }
     }
 }
diff --git a/tests/tests/permission/src/android/permission/cts/AppOpsTest.java b/tests/tests/permission/src/android/permission/cts/AppOpsTest.java
index 547af7e..745d859 100644
--- a/tests/tests/permission/src/android/permission/cts/AppOpsTest.java
+++ b/tests/tests/permission/src/android/permission/cts/AppOpsTest.java
@@ -235,16 +235,6 @@
     }
 
     @SmallTest
-    public void testAllOpsHaveOpString() {
-        Set<String> opStrs = new HashSet<>();
-        for (String opStr : AppOpsManager.getOpStrs()) {
-            assertNotNull("Each app op must have an operation string defined", opStr);
-            opStrs.add(opStr);
-        }
-        assertEquals("Not all op strings are unique", AppOpsManager._NUM_OP, opStrs.size());
-    }
-
-    @SmallTest
     public void testOpCodesUnique() {
         String[] opStrs = AppOpsManager.getOpStrs();
         Set<Integer> opCodes = new HashSet<>();
diff --git a/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java b/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
old mode 100644
new mode 100755
index 585f9c6..255bdee
--- a/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/PrivappPermissionsTest.java
@@ -29,10 +29,13 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
 import java.util.TreeSet;
+import java.lang.StringBuilder;
 
 import static android.content.pm.PackageManager.GET_PERMISSIONS;
 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
@@ -67,6 +70,8 @@
         List<PackageInfo> installedPackages = pm
                 .getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES);
 
+        Map<String, Set<String>> packagesGrantedNotInWhitelist = new HashMap<>();
+        Map<String, Set<String>> packagesNotGrantedNotInDenylist = new HashMap<>();
         for (PackageInfo pkg : installedPackages) {
             String packageName = pkg.packageName;
             if (!pkg.applicationInfo.isPrivilegedApp()
@@ -116,15 +121,31 @@
                 Set<String> notGrantedNotInDenylist = new TreeSet<>(notGranted);
                 notGrantedNotInDenylist.removeAll(denylist);
 
-                assertTrue("Not whitelisted permissions are granted for package "
-                                + packageName + ": " + grantedNotInWhitelist,
-                        grantedNotInWhitelist.isEmpty());
+                if (!grantedNotInWhitelist.isEmpty()) {
+                    packagesGrantedNotInWhitelist.put(packageName, grantedNotInWhitelist);
+                }
 
-                assertTrue("Requested permissions not granted for package "
-                                + packageName + ": " + notGrantedNotInDenylist,
-                        notGrantedNotInDenylist.isEmpty());
+                if (!notGrantedNotInDenylist.isEmpty()) {
+                    packagesNotGrantedNotInDenylist.put(packageName, notGrantedNotInDenylist);
+                }
             }
         }
+        StringBuilder message = new StringBuilder();
+        if (!packagesGrantedNotInWhitelist.isEmpty()) {
+            message.append("Not whitelisted permissions are granted: "
+                    + packagesGrantedNotInWhitelist.toString());
+        }
+        if (!packagesNotGrantedNotInDenylist.isEmpty()) {
+            if (message.length() != 0) {
+                message.append(", ");
+            }
+            message.append("Requested permissions not granted: "
+                    + packagesNotGrantedNotInDenylist.toString());
+        }
+        if (!packagesGrantedNotInWhitelist.isEmpty()
+                || !packagesNotGrantedNotInDenylist.isEmpty()) {
+            fail(message.toString());
+        }
     }
 
     private Set<String> getPrivAppPermissions(String packageName) throws IOException {
diff --git a/tests/tests/provider/AndroidTest.xml b/tests/tests/provider/AndroidTest.xml
index aaa818c..123931c 100644
--- a/tests/tests/provider/AndroidTest.xml
+++ b/tests/tests/provider/AndroidTest.xml
@@ -21,6 +21,7 @@
         <option name="test-file-name" value="CtsProviderTestCases.apk" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="runner" value="android.support.test.runner.AndroidJUnitRunner" />
         <option name="package" value="android.provider.cts" />
         <option name="runtime-hint" value="7m19s" />
         <option name="hidden-api-checks" value="false" />
diff --git a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_ContactsTest.java b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_ContactsTest.java
index 3c56aba..c5fdc1a 100644
--- a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_ContactsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_ContactsTest.java
@@ -206,8 +206,6 @@
         final TestContact contact = rawContact.getContact().load();
 
         contact.load();
-        assertEquals(0L, contact.getLong(Contacts.TIMES_CONTACTED));
-        assertEquals(0L, contact.getLong(Contacts.LAST_TIME_CONTACTED));
 
         final long now = System.currentTimeMillis();
 
@@ -218,8 +216,6 @@
         ContactUtil.update(mResolver, contact.getId(), values);
 
         contact.load();
-        assertEquals(3L, contact.getLong(Contacts.TIMES_CONTACTED));
-        assertEquals(now / 86400 * 86400, contact.getLong(Contacts.LAST_TIME_CONTACTED));
 
         // This is also the same as markAsContacted().
         values.clear();
@@ -227,8 +223,6 @@
         ContactUtil.update(mResolver, contact.getId(), values);
 
         contact.load();
-        assertEquals(4L, contact.getLong(Contacts.TIMES_CONTACTED));
-        assertEquals(now / 86400 * 86400, contact.getLong(Contacts.LAST_TIME_CONTACTED));
 
         values.clear();
         values.put(Contacts.TIMES_CONTACTED, 10);
@@ -236,27 +230,17 @@
         ContactUtil.update(mResolver, contact.getId(), values);
 
         contact.load();
-        assertEquals(10L, contact.getLong(Contacts.TIMES_CONTACTED));
-        assertEquals(now / 86400 * 86400, contact.getLong(Contacts.LAST_TIME_CONTACTED));
     }
 
-    /**
-     * Make sure the rounded usage stats values are also what the callers would see in where
-     * clauses.
-     *
-     * This tests both contacts and raw_contacts.
-     */
     public void testContactUpdateDelete_usageStats_visibilityInWhere() throws Exception {
         final TestRawContact rawContact = mBuilder.newRawContact().insert().load();
         final TestContact contact = rawContact.getContact().load();
 
-        // To make things more predictable, inline markAsContacted here with a known timestamp.
         final long now = (System.currentTimeMillis() / 86400 * 86400) + 86400 * 5 + 123;
 
         ContentValues values = new ContentValues();
         values.put(Contacts.LAST_TIME_CONTACTED, now);
 
-        // This makes the internal TIMES_CONTACTED 35.  But the visible value is still 30.
         for (int i = 0; i < 35; i++) {
             ContactUtil.update(mResolver, contact.getId(), values);
         }
@@ -264,12 +248,6 @@
         contact.load();
         rawContact.load();
 
-        assertEquals(now / 86400 * 86400, contact.getLong(Contacts.LAST_TIME_CONTACTED));
-        assertEquals(30, contact.getLong(Contacts.TIMES_CONTACTED));
-
-        assertEquals(now / 86400 * 86400, rawContact.getLong(Contacts.LAST_TIME_CONTACTED));
-        assertEquals(30, rawContact.getLong(Contacts.TIMES_CONTACTED));
-
         final ContentValues cv = new ContentValues();
             cv.put(Contacts.STARRED, 1);
 
@@ -277,12 +255,7 @@
                 (Contacts.LAST_TIME_CONTACTED + "=P1 AND " + Contacts.TIMES_CONTACTED + "=P2")
                         .replaceAll("P1", String.valueOf(now / 86400 * 86400))
                         .replaceAll("P2", "30");
-        assertEquals(1, mResolver.update(Contacts.CONTENT_URI, cv, where, null));
-        assertEquals(1, mResolver.update(RawContacts.CONTENT_URI, cv, where, null));
 
-        // Also delete.  This will actually delete the row, so we can test it only for one of the
-        // contact or the raw contact.
-        assertEquals(1, mResolver.delete(RawContacts.CONTENT_URI, where, null));
         rawContact.setAlreadyDeleted();
         contact.setAlreadyDeleted();
     }
diff --git a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DataUsageTest.java b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DataUsageTest.java
index d5ab172..befbeb8 100644
--- a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DataUsageTest.java
+++ b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_DataUsageTest.java
@@ -93,28 +93,20 @@
 
         long[] dataIds = setupRawContactDataItems(ids.mRawContactId);
 
-        assertDataUsageEquals(dataIds, 0, 0, 0, 0);
-
         updateMultipleAndAssertUpdateSuccess(new long[] {dataIds[1], dataIds[2]});
-        assertDataUsageEquals(dataIds, 0, 1, 1, 0);
 
         updateMultipleAndAssertUpdateSuccess(new long[]{dataIds[1], dataIds[2]});
-        assertDataUsageEquals(dataIds, 0, 2, 2, 0);
 
         for (int i = 3; i <= 10; i++) {
             updateMultipleAndAssertUpdateSuccess(new long[]{dataIds[1]});
         }
-        assertDataUsageEquals(dataIds, 0, 10, 2, 0);
 
         updateMultipleAndAssertUpdateSuccess(new long[]{dataIds[0], dataIds[1]});
-        assertDataUsageEquals(dataIds, 1, 10, 2, 0);
 
         for (int i = 12; i <= 19; i++) {
             updateMultipleAndAssertUpdateSuccess(new long[]{dataIds[1]});
-            assertDataUsageEquals(dataIds, 1, 10, 2, 0);
         }
         updateMultipleAndAssertUpdateSuccess(new long[]{dataIds[1]});
-        assertDataUsageEquals(dataIds, 1, 20, 2, 0);
 
         deleteDataUsage();
         RawContactUtil.delete(mResolver, ids.mRawContactId, true);
@@ -142,7 +134,6 @@
                 .appendQueryParameter(DataUsageFeedback.USAGE_TYPE,
                         DataUsageFeedback.USAGE_TYPE_CALL).build();
         int result = mResolver.update(uri, new ContentValues(), null, null);
-        assertTrue(result > 0);
     }
 
     /**
@@ -154,42 +145,6 @@
                 .appendQueryParameter(DataUsageFeedback.USAGE_TYPE,
                         DataUsageFeedback.USAGE_TYPE_CALL).build();
         int result = mResolver.update(uri, new ContentValues(), null, null);
-        assertTrue(result > 0);
-
-        assertDataUsageEquals(dataId, assertValue);
-    }
-
-    /**
-     * Assert that the given data ids have usage values in the respective order.
-     */
-    private void assertDataUsageEquals(long[] dataIds, int... expectedValues) {
-        if (dataIds.length != expectedValues.length) {
-            throw new IllegalArgumentException("dataIds and expectedValues must be the same size");
-        }
-
-        for (int i = 0; i < dataIds.length; i++) {
-            assertDataUsageEquals(dataIds[i], expectedValues[i]);
-        }
-    }
-
-    /**
-     * Assert a single data item has a specific usage value.
-     */
-    private void assertDataUsageEquals(long dataId, int expectedValue) {
-        // Query and assert value is expected.
-        String[] projection = new String[]{ContactsContract.Data.TIMES_USED};
-        String[] record = DataUtil.queryById(mResolver, dataId, projection);
-        assertNotNull(record);
-        long actual = 0;
-        // Tread null as 0
-        if (record[0] != null) {
-            actual = Long.parseLong(record[0]);
-        }
-        assertEquals(expectedValue, actual);
-
-        // Also make sure the rounded value is used in 'where' too.
-        assertEquals("Query should match", 1, DataUtil.queryById(mResolver, dataId, projection,
-                "ifnull(" + Data.TIMES_USED + ",0)=" + expectedValue, null).length);
     }
 
     private void deleteDataUsage() {
diff --git a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_FrequentsStrequentsTest.java b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_FrequentsStrequentsTest.java
index 2231bd2f..f06c859 100644
--- a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_FrequentsStrequentsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_FrequentsStrequentsTest.java
@@ -196,11 +196,6 @@
 
         // Contact the third contact twice.
         markDataAsUsed(mDataIds[2], 2);
-
-        // The strequents uri should now return contact 2, 3, 1 in order due to ranking by
-        // data usage.
-        assertCursorStoredValuesWithContactsFilter(Contacts.CONTENT_STREQUENT_URI, ids,
-                false, sContentValues[1], sContentValues[2], sContentValues[0]);
     }
 
     /**
@@ -220,13 +215,6 @@
         // Contact the third contact twice, and mark it as used
         markDataAsUsed(mDataIds[2], 2);
         starContact(ids[2]);
-
-        // The strequents uri should now return contact 3, 2, 1 in order. Contact 3 is ranked first
-        // because it is starred, followed by contacts 2 and 1 due to their data usage ranking.
-        // Note that contact 3 is only returned once (as a starred contact) even though it is also
-        // a frequently contacted contact.
-        assertCursorStoredValuesWithContactsFilter(Contacts.CONTENT_STREQUENT_URI, ids,
-                false, sContentValues[2], sContentValues[1], sContentValues[0]);
     }
 
     /**
@@ -243,10 +231,6 @@
 
         // Construct a uri that filters for the query string "ta".
         Uri uri = Contacts.CONTENT_STREQUENT_FILTER_URI.buildUpon().appendEncodedPath("ta").build();
-
-        // Only contact 1 and 2 should be returned (sorted in alphabetical order) due to the
-        // filtered query.
-        assertCursorStoredValuesWithContactsFilter(uri, ids, false, sContentValues[1], sContentValues[0]);
     }
 
     public void testStrequents_projection() throws Exception {
@@ -303,10 +287,6 @@
         // Construct a uri for phone only favorites.
         Uri uri = Contacts.CONTENT_STREQUENT_URI.buildUpon().
                 appendQueryParameter(ContactsContract.STREQUENT_PHONE_ONLY, "true").build();
-
-        // Only the contacts with phone numbers are returned, in frequency ranking order.
-        assertCursorStoredValuesWithContactsFilter(uri, mDataIds, false,
-                sContentValues[2], sContentValues[0]);
     }
 
     public void testStrequents_phoneOnly_projection() throws Exception {
@@ -342,11 +322,6 @@
 
         // Contact the third contact twice.
         markDataAsUsed(mDataIds[2], 2);
-
-        // The frequents uri should now return contact 2, 3, 1 in order due to ranking by
-        // data usage.
-        assertCursorStoredValuesWithContactsFilter(Contacts.CONTENT_FREQUENT_URI, ids,
-                true /* inOrder */, sContentValues[1], sContentValues[2], sContentValues[0]);
     }
 
     public void testFrequent_projection() throws Exception {
diff --git a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
index 7c971b3..d937005 100644
--- a/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
@@ -243,8 +243,6 @@
                     .insert();
 
             rawContact.load();
-            assertEquals(12340, rawContact.getLong(RawContacts.TIMES_CONTACTED));
-            assertEquals(now / 86400 * 86400, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
         }
 
         {
@@ -255,8 +253,6 @@
                     .insert();
 
             rawContact.load();
-            assertEquals(5L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
-            assertEquals(0, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
         }
         {
             TestRawContact rawContact = mBuilder.newRawContact()
@@ -266,8 +262,6 @@
                     .insert();
 
             rawContact.load();
-            assertEquals(0L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
-            assertEquals(now / 86400 * 86400, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
         }
     }
 
@@ -283,24 +277,17 @@
                 .insert();
 
         rawContact.load();
-        assertEquals(12340L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
-        assertEquals(now / 86400 * 86400, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
 
         values.clear();
         values.put(RawContacts.TIMES_CONTACTED, 99999);
         RawContactUtil.update(mResolver, rawContact.getId(), values);
 
         rawContact.load();
-        assertEquals(99990L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
-        assertEquals(now / 86400 * 86400, rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
 
         values.clear();
         values.put(RawContacts.LAST_TIME_CONTACTED, now + 86400);
         RawContactUtil.update(mResolver, rawContact.getId(), values);
 
         rawContact.load();
-        assertEquals(99990L, rawContact.getLong(RawContacts.TIMES_CONTACTED));
-        assertEquals((now / 86400 * 86400) + 86400,
-                rawContact.getLong(RawContacts.LAST_TIME_CONTACTED));
     }
 }
diff --git a/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk b/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
index 7328762..c85f8b7 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp1/apk/signed-CtsSecureElementAccessControlTestCases1.apk
Binary files differ
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
index 22b8432..45dd3f0 100644
--- 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
@@ -18,6 +18,7 @@
 
 package android.omapi.accesscontrol1.cts;
 
+import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.*;
 import static org.junit.Assume.assumeTrue;
 
@@ -239,121 +240,121 @@
     }
 
     private void testSelectableAid(byte[] aid) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte) 0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
         } catch (Exception e) {
             fail("Unexpected Exception " + e);
-        } finally{
-            if (channel != null)
-                channel.close();
-            if (session != null)
-                session.close();
         }
     }
 
     private void testUnauthorisedAid(byte[] aid) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte) 0x00);
-                fail("SecurityException Expected ");
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    try {
+                        channel = session.openLogicalChannel(aid, (byte) 0x00);
+                        fail("SecurityException Expected");
+                    } catch (SecurityException e) {
+                        // Expected
+                    }
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
-        } catch(SecurityException ex){ }
-        catch (Exception e) {
+        } catch (Exception e) {
             fail("Unexpected Exception " + e);
         }
-        if (channel != null)
-            channel.close();
-        if (session != null)
-            session.close();
     }
 
     private void testTransmitAPDU(byte[] aid, byte[] apdu) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte) 0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
-                byte[] apduResponse = channel.transmit(apdu);
-                assertNotNull("Null Channel", apduResponse);
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                    byte[] apduResponse = channel.transmit(apdu);
+                    assertNotNull("Null Channel", apduResponse);
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
         } catch (Exception e) {
             fail("Unexpected Exception " + e);
         }
-        if (channel != null)
-            channel.close();
-        if (session != null)
-            session.close();
     }
 
     private void testUnauthorisedAPDU(byte[] aid, byte[] apdu) {
-        Session session = null;
-        Channel channel = null;
-        boolean exceptionOnTransmit = false;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte) 0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
-                exceptionOnTransmit = true;
-                channel.transmit(apdu);
-                fail("Security Exception is expected");
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                    try {
+                        channel.transmit(apdu);
+                        fail("Security Exception is expected");
+                    } catch (SecurityException e) {
+                        // Expected
+                    }
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
-        } catch (SecurityException ex) {
-          if (!exceptionOnTransmit) {
-            fail("Unexpected SecurityException onSelect" + ex);
-          }
         } catch (Exception e) {
-          fail("Unexpected Exception " + e);
-        } finally {
-            if(channel != null)
-                channel.close();
-            if (session != null)
-                session.close();
+            fail("Unexpected Exception " + e);
         }
     }
 
diff --git a/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk b/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
index 072f2af..b8a978d 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp2/apk/signed-CtsSecureElementAccessControlTestCases2.apk
Binary files differ
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
index 3adc1c9..4a7b7e6 100644
--- 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
@@ -18,6 +18,7 @@
 
 package android.omapi.accesscontrol2.cts;
 
+import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.*;
 import static org.junit.Assume.assumeTrue;
 
@@ -238,121 +239,121 @@
     }
 
     private void testSelectableAid(byte[] aid) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte) 0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
         } catch (Exception e) {
             fail("Unexpected Exception " + e);
-        } finally{
-            if (channel != null)
-                channel.close();
-            if (session != null)
-                session.close();
         }
     }
 
     private void testUnauthorisedAid(byte[] aid) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte)0x00);
-                fail("SecurityException Expected ");
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    try {
+                        channel = session.openLogicalChannel(aid, (byte) 0x00);
+                        fail("SecurityException Expected");
+                    } catch (SecurityException e) {
+                        // Expected
+                    }
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
-        } catch(SecurityException ex){ }
-        catch (Exception e) {
+        } catch (Exception e) {
             fail("Unexpected Exception " + e);
         }
-        if (channel != null)
-            channel.close();
-        if (session != null)
-            session.close();
     }
 
     private void testTransmitAPDU(byte[] aid, byte[] apdu) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte)0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
-                byte[] apduResponse = channel.transmit(apdu);
-                assertNotNull("Null Channel", apduResponse);
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                    byte[] apduResponse = channel.transmit(apdu);
+                    assertNotNull("Null Channel", apduResponse);
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
         } catch (Exception e) {
             fail("Unexpected Exception " + e);
         }
-        if (channel != null)
-            channel.close();
-        if (session != null)
-            session.close();
     }
 
     private void testUnauthorisedAPDU(byte[] aid, byte[] apdu) {
-        Session session = null;
-        Channel channel = null;
-        boolean exceptionOnTransmit = false;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte) 0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
-                exceptionOnTransmit = true;
-                channel.transmit(apdu);
-                fail("Security Exception is expected");
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                    try {
+                        channel.transmit(apdu);
+                        fail("Security Exception is expected");
+                    } catch (SecurityException e) {
+                        // Expected
+                    }
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
-        } catch (SecurityException ex) {
-          if (!exceptionOnTransmit) {
-            fail("Unexpected SecurityException onSelect" + ex);
-          }
         } catch (Exception e) {
-          fail("Unexpected Exception " + e);
-        } finally {
-            if(channel != null)
-                channel.close();
-            if (session != null)
-                session.close();
+            fail("Unexpected Exception " + e);
         }
     }
 
diff --git a/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk b/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
index 10939c6..b3c4054 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
+++ b/tests/tests/secure_element/access_control/AccessControlApp3/apk/signed-CtsSecureElementAccessControlTestCases3.apk
Binary files differ
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
index 7071628..3a8971c 100644
--- 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
@@ -18,6 +18,7 @@
 
 package android.omapi.accesscontrol3.cts;
 
+import static org.hamcrest.CoreMatchers.is;
 import static org.junit.Assert.*;
 import static org.junit.Assume.assumeTrue;
 
@@ -241,121 +242,121 @@
     }
 
     private void testSelectableAid(byte[] aid) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte)0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
         } catch (Exception e) {
             fail("Unexpected Exception " + e);
-        } finally{
-            if (channel != null)
-                channel.close();
-            if (session != null)
-                session.close();
         }
     }
 
     private void testUnauthorisedAid(byte[] aid) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte)0x00);
-                fail("SecurityException Expected ");
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    try {
+                        channel = session.openLogicalChannel(aid, (byte) 0x00);
+                        fail("SecurityException Expected");
+                    } catch (SecurityException e) {
+                        // Expected
+                    }
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
-        } catch(SecurityException ex){ }
-        catch (Exception e) {
+        } catch (Exception e) {
             fail("Unexpected Exception " + e);
         }
-        if (channel != null)
-            channel.close();
-        if (session != null)
-            session.close();
     }
 
     private void testTransmitAPDU(byte[] aid, byte[] apdu) {
-        Session session = null;
-        Channel channel = null;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte)0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
-                byte[] apduResponse = channel.transmit(apdu);
-                assertNotNull("Null Channel", apduResponse);
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                    byte[] apduResponse = channel.transmit(apdu);
+                    assertNotNull("Null Channel", apduResponse);
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
         } catch (Exception e) {
             fail("Unexpected Exception " + e);
         }
-        if (channel != null)
-            channel.close();
-        if (session != null)
-            session.close();
     }
 
     private void testUnauthorisedAPDU(byte[] aid, byte[] apdu) {
-        Session session = null;
-        Channel channel = null;
-        boolean exceptionOnTransmit = false;
         try {
             waitForConnection();
             Reader[] readers = seService.getReaders();
-
             for (Reader reader : readers) {
-                assertTrue(reader.isSecureElementPresent());
-                session = reader.openSession();
-                assertNotNull("Null Session", session);
-                channel = session.openLogicalChannel(aid, (byte)0x00);
-                assertNotNull("Null Channel", channel);
-                byte[] selectResponse = channel.getSelectResponse();
-                assertNotNull("Null Select Response", selectResponse);
-                assertEquals(selectResponse[selectResponse.length - 1] & 0xFF, 0x00);
-                assertEquals(selectResponse[selectResponse.length - 2] & 0xFF, 0x90);
-                assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
-                exceptionOnTransmit = true;
-                channel.transmit(apdu);
-                fail("Security Exception is expected");
+                Session session = null;
+                Channel channel = null;
+                try {
+                    assertTrue(reader.isSecureElementPresent());
+                    session = reader.openSession();
+                    assertNotNull("Null Session", session);
+                    channel = session.openLogicalChannel(aid, (byte) 0x00);
+                    assertNotNull("Null Channel", channel);
+                    byte[] selectResponse = channel.getSelectResponse();
+                    assertNotNull("Null Select Response", selectResponse);
+                    assertThat(selectResponse[selectResponse.length - 1] & 0xFF, is(0x00));
+                    assertThat(selectResponse[selectResponse.length - 2] & 0xFF, is(0x90));
+                    assertTrue("Select Response is not complete", verifyBerTlvData(selectResponse));
+                    try {
+                        channel.transmit(apdu);
+                        fail("Security Exception is expected");
+                    } catch (SecurityException e) {
+                        // Expected
+                    }
+                } finally {
+                    if (channel != null) channel.close();
+                    if (session != null) session.close();
+                }
             }
-        } catch (SecurityException ex) {
-          if (!exceptionOnTransmit) {
-            fail("Unexpected SecurityException onSelect" + ex);
-          }
         } catch (Exception e) {
-          fail("Unexpected Exception " + e);
-        } finally {
-            if(channel != null)
-                channel.close();
-            if (session != null)
-                session.close();
+            fail("Unexpected Exception " + e);
         }
     }
 
diff --git a/tests/tests/secure_element/sample_applet/uicc/google-cardlet.cap b/tests/tests/secure_element/sample_applet/uicc/google-cardlet.cap
new file mode 100644
index 0000000..01f7ea0
--- /dev/null
+++ b/tests/tests/secure_element/sample_applet/uicc/google-cardlet.cap
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/ListeningPortsTest.java b/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
index 58f9192..6d7c5e2 100644
--- a/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
+++ b/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
@@ -17,9 +17,12 @@
 package android.security.cts;
 
 import android.content.pm.PackageManager;
+import android.os.Process;
+import android.os.UserHandle;
 import android.platform.test.annotations.SecurityTest;
 import android.test.AndroidTestCase;
 import android.util.Log;
+import com.android.compatibility.common.util.FeatureUtil;
 import junit.framework.AssertionFailedError;
 
 import java.io.File;
@@ -46,6 +49,8 @@
 
     private static final int CONN_TIMEOUT_IN_MS = 5000;
 
+    private boolean mIsTelevision;
+
     /** Ports that are allowed to be listening. */
     private static final List<String> EXCEPTION_PATTERNS = new ArrayList<String>(6);
 
@@ -73,6 +78,12 @@
         EXCEPTION_PATTERNS.add(":::5555");          // emulator port for adb
     }
 
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mIsTelevision = FeatureUtil.isTV();
+    }
+
     /**
      * Remotely accessible ports are often used by attackers to gain
      * unauthorized access to computers systems without user knowledge or
@@ -221,6 +232,12 @@
                 if (isTcp && !isTcpConnectable(entry.localAddress, entry.port)) {
                     continue;
                 }
+                // allow non-system processes to listen
+                int appId = UserHandle.getAppId(entry.uid);
+                if (appId >= Process.FIRST_APPLICATION_UID
+                        && appId <= Process.LAST_APPLICATION_UID) {
+                    continue;
+                }
 
                 errors += "\nFound port listening on addr="
                         + entry.localAddress.getHostAddress() + ", port="
diff --git a/tests/tests/security/src/android/security/cts/MotionEventTest.java b/tests/tests/security/src/android/security/cts/MotionEventTest.java
index db29704..4a8cc780 100644
--- a/tests/tests/security/src/android/security/cts/MotionEventTest.java
+++ b/tests/tests/security/src/android/security/cts/MotionEventTest.java
@@ -124,7 +124,8 @@
         FutureTask<Point> task = new FutureTask<>(() -> {
             final int[] viewLocation = new int[2];
             viewHolder[0].getLocationOnScreen(viewLocation);
-            return new Point(viewLocation[0], viewLocation[1]);
+            // Set y position to the center of the view, to make sure it is away from the status bar
+            return new Point(viewLocation[0], viewLocation[1] + viewHolder[0].getHeight() / 2);
         });
         mActivity.runOnUiThread(task);
         Point viewLocation = task.get(5, TimeUnit.SECONDS);
diff --git a/tests/tests/security/src/android/security/cts/VerifiedBootTest.java b/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
index 33a1b7a..a3209fc 100644
--- a/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
+++ b/tests/tests/security/src/android/security/cts/VerifiedBootTest.java
@@ -26,10 +26,21 @@
 public class VerifiedBootTest extends AndroidTestCase {
   private static final String TAG = "VerifiedBootTest";
 
+  private static boolean isLowRamExempt(PackageManager pm) {
+    if (pm.hasSystemFeature(PackageManager.FEATURE_RAM_NORMAL)) {
+      // No exemption for normal RAM
+      return false;
+    }
+    return (PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.P);
+  }
+
   /**
-   * Asserts that Verified Boot is supported on devices that report the feature flag
-   * android.hardware.ram.normal. If a device launched on a pre-O_MR1 level without verified boot
-   * then it is exempt from this requirement.
+   * Asserts that Verified Boot is supported.
+   *
+   * A device is exempt if it launched on a pre-O_MR1 level.
+   *
+   * A device without the feature flag android.hardware.ram.normal is exempt if
+   * it launched on a pre-P level.
    */
   public void testVerifiedBootSupport() throws Exception {
     if (PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.O_MR1) {
@@ -37,11 +48,10 @@
     }
     PackageManager pm = getContext().getPackageManager();
     assertNotNull("PackageManager must not be null", pm);
-    boolean isRAMNormal = pm.hasSystemFeature(PackageManager.FEATURE_RAM_NORMAL);
-    if (!isRAMNormal) {
+    if (isLowRamExempt(pm)) {
       return;
     }
-    assertTrue("Verified boot must be supported on a device with normal RAM",
+    assertTrue("Verified boot must be supported on the device",
         pm.hasSystemFeature(PackageManager.FEATURE_VERIFIED_BOOT));
   }
 }
diff --git a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
index 904f0cf..f2b9fc4 100644
--- a/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
+++ b/tests/tests/shortcutmanager/src/android/content/pm/cts/shortcutmanager/ShortcutManagerClientApiTest.java
@@ -129,6 +129,8 @@
         assertExpectException(NullPointerException.class, "action must be set",
                 () -> new ShortcutInfo.Builder(getTestContext(), "id").setIntent(new Intent()));
 
+        setCurrentCaller(getTestContext());
+
         assertExpectException(
                 IllegalArgumentException.class, "Short label must be provided", () -> {
                     ShortcutInfo si = new ShortcutInfo.Builder(getTestContext(), "id")
diff --git a/tests/tests/systemui/AndroidManifest.xml b/tests/tests/systemui/AndroidManifest.xml
index ce4b90d..bdd6da7 100644
--- a/tests/tests/systemui/AndroidManifest.xml
+++ b/tests/tests/systemui/AndroidManifest.xml
@@ -23,9 +23,11 @@
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     <application>
         <activity android:name=".LightBarActivity"
-                android:theme="@android:style/Theme.Material.NoActionBar"></activity>
+                android:theme="@android:style/Theme.Material.NoActionBar"
+                android:screenOrientation="portrait"></activity>
         <activity android:name=".LightBarThemeActivity"
-            android:theme="@style/LightBarTheme"></activity>
+                android:theme="@style/LightBarTheme"
+                android:screenOrientation="portrait"></activity>
         <uses-library android:name="android.test.runner" />
     </application>
 
diff --git a/tests/tests/systemui/AndroidTest.xml b/tests/tests/systemui/AndroidTest.xml
index 208f844..e7852c5 100644
--- a/tests/tests/systemui/AndroidTest.xml
+++ b/tests/tests/systemui/AndroidTest.xml
@@ -25,4 +25,11 @@
         <option name="package" value="android.systemui.cts" />
         <option name="runtime-hint" value="10m19s" />
     </test>
+
+    <!-- Collect the files in the dump directory for debugging -->
+    <metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector">
+        <option name="directory-keys" value="/sdcard/LightBarTestBase/" />
+        <option name="collect-on-run-ended-only" value="true" />
+    </metrics_collector>
+
 </configuration>
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
index c88e7d1..dde2ce1 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTestBase.java
@@ -29,18 +29,21 @@
 import android.support.test.InstrumentationRegistry;
 import android.support.test.rule.ActivityTestRule;
 import android.util.Log;
-import android.view.KeyCharacterMap;
 import android.view.KeyEvent;
 import android.view.WindowInsets;
 
+import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.nio.file.Path;
 
 public class LightBarTestBase {
 
     private static final String TAG = "LightBarTestBase";
 
-    public static final String DUMP_PATH = "/sdcard/lightstatustest.png";
+    public static final Path DUMP_PATH = FileSystems.getDefault()
+            .getPath("/sdcard/LightBarTestBase/");
 
     protected Bitmap takeStatusBarScreenshot(LightBarBaseActivity activity) {
         Bitmap fullBitmap = getInstrumentation().getUiAutomation().takeScreenshot();
@@ -53,11 +56,17 @@
                 fullBitmap.getHeight() - activity.getBottom());
     }
 
-    protected void dumpBitmap(Bitmap bitmap) {
-        Log.e(TAG, "Dumping failed bitmap to " + DUMP_PATH);
+    protected void dumpBitmap(Bitmap bitmap, String name) {
+        File dumpDir = DUMP_PATH.toFile();
+        if (!dumpDir.exists()) {
+            dumpDir.mkdirs();
+        }
+
+        Path filePath = DUMP_PATH.resolve(name + ".png");
+        Log.e(TAG, "Dumping failed bitmap to " + filePath);
         FileOutputStream fileStream = null;
         try {
-            fileStream = new FileOutputStream(DUMP_PATH);
+            fileStream = new FileOutputStream(filePath.toFile());
             bitmap.compress(Bitmap.CompressFormat.PNG, 85, fileStream);
             fileStream.flush();
         } catch (Exception e) {
@@ -75,13 +84,11 @@
 
     private boolean hasVirtualNavigationBar(ActivityTestRule<? extends LightBarBaseActivity> rule)
             throws Throwable {
-        boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
-        boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
         final WindowInsets[] inset = new WindowInsets[1];
         rule.runOnUiThread(()-> {
             inset[0] = rule.getActivity().getRootWindowInsets();
         });
-        return !hasBackKey || !hasHomeKey || inset[0].getStableInsetBottom() == 0;
+        return inset[0].getStableInsetBottom() > 0;
     }
 
     private boolean isRunningInVr() {
@@ -132,7 +139,7 @@
     }
 
     protected void checkNavigationBarDivider(LightBarBaseActivity activity, int dividerColor,
-            int backgroundColor) {
+            int backgroundColor, String methodName) {
         final Bitmap bitmap = takeNavigationBarScreenshot(activity);
         int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
         bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
@@ -147,7 +154,7 @@
 
         for (int col = 0; col < bitmap.getWidth(); col++) {
             if (dividerColor != pixels[col]) {
-                dumpBitmap(bitmap);
+                dumpBitmap(bitmap, methodName);
                 fail("Invalid color exptected=" + dividerColor + " actual=" + pixels[col]);
             }
         }
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
index fc7e70f..724bca0 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarTests.java
@@ -38,6 +38,7 @@
 
 import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TestName;
 import org.junit.runner.RunWith;
 
 /**
@@ -66,6 +67,8 @@
     @Rule
     public ActivityTestRule<LightBarActivity> mActivityRule = new ActivityTestRule<>(
             LightBarActivity.class);
+    @Rule
+    public TestName mTestName = new TestName();
 
     @Test
     @AppModeFull // Instant apps cannot create notifications
@@ -128,7 +131,8 @@
         });
         Thread.sleep(WAIT_TIME);
 
-        checkNavigationBarDivider(mActivityRule.getActivity(), Color.WHITE, Color.RED);
+        checkNavigationBarDivider(mActivityRule.getActivity(), Color.WHITE, Color.RED,
+                mTestName.getMethodName());
     }
 
     private void injectCanceledTap(int x, int y) {
@@ -167,7 +171,7 @@
             success = true;
         } finally {
             if (!success) {
-                dumpBitmap(bitmap);
+                dumpBitmap(bitmap, mTestName.getMethodName());
             }
         }
     }
@@ -227,6 +231,15 @@
 
         int mixedIconColor = mixSrcOver(background, iconColor);
         int mixedIconPartialColor = mixSrcOver(background, iconPartialColor);
+        float [] hsvMixedIconColor = new float[3];
+        float [] hsvMixedPartialColor = new float[3];
+        Color.RGBToHSV(Color.red(mixedIconColor), Color.green(mixedIconColor),
+                Color.blue(mixedIconColor), hsvMixedIconColor);
+        Color.RGBToHSV(Color.red(mixedIconPartialColor), Color.green(mixedIconPartialColor),
+                Color.blue(mixedIconPartialColor), hsvMixedPartialColor);
+
+        float maxHsvValue = Math.max(hsvMixedIconColor[2], hsvMixedPartialColor[2]);
+        float minHsvValue = Math.min(hsvMixedIconColor[2], hsvMixedPartialColor[2]);
 
         int[] pixels = new int[bitmap.getHeight() * bitmap.getWidth()];
         bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
@@ -234,6 +247,7 @@
         Stats s = new Stats();
         float eps = 0.005f;
 
+        float [] hsvPixel = new float[3];
         for (int c : pixels) {
             if (isColorSame(c, background)) {
                 s.backgroundPixels++;
@@ -241,7 +255,9 @@
             }
 
             // What we expect the icons to be colored according to the spec.
-            if (isColorSame(c, mixedIconColor) || isColorSame(c, mixedIconPartialColor)) {
+            Color.RGBToHSV(Color.red(c), Color.green(c), Color.blue(c), hsvPixel);
+            if (isColorSame(c, mixedIconColor) || isColorSame(c, mixedIconPartialColor)
+                    || (hsvPixel[2] >= minHsvValue && hsvPixel[2] <= maxHsvValue)) {
                 s.iconPixels++;
                 continue;
             }
diff --git a/tests/tests/systemui/src/android/systemui/cts/LightBarThemeTest.java b/tests/tests/systemui/src/android/systemui/cts/LightBarThemeTest.java
index 4d20dfb..207b321 100644
--- a/tests/tests/systemui/src/android/systemui/cts/LightBarThemeTest.java
+++ b/tests/tests/systemui/src/android/systemui/cts/LightBarThemeTest.java
@@ -33,6 +33,7 @@
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TestName;
 import org.junit.runner.RunWith;
 
 /**
@@ -49,6 +50,9 @@
     public ActivityTestRule<LightBarThemeActivity> mActivityRule = new ActivityTestRule<>(
             LightBarThemeActivity.class);
 
+    @Rule
+    public TestName mTestName = new TestName();
+
     @Before
     public void setUp() {
         mDevice = UiDevice.getInstance(getInstrumentation());
@@ -79,6 +83,7 @@
         final Context instrumentationContext = getInstrumentation().getContext();
         checkNavigationBarDivider(mActivityRule.getActivity(),
                 instrumentationContext.getColor(R.color.navigationBarDividerColor),
-                instrumentationContext.getColor(R.color.navigationBarColor));
+                instrumentationContext.getColor(R.color.navigationBarColor),
+                mTestName.getMethodName());
     }
 }
diff --git a/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
index 36db13a..ba8be5e 100755
--- a/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/ConnectionServiceTest.java
@@ -176,9 +176,11 @@
 
         // GIVEN a managed call
         placeAndVerifyCall();
-        verifyConnectionForOutgoingCall().setActive();
+        Connection outgoing = verifyConnectionForOutgoingCall();
+        outgoing.setActive();
         assertTrue(connectionService.waitForEvent(
                 MockConnectionService.EVENT_CONNECTION_SERVICE_FOCUS_GAINED));
+        assertCallState(mInCallCallbacks.getService().getLastCall(), Call.STATE_ACTIVE);
 
         // WHEN place another call has the same ConnectionService as the existing call
         placeAndVerifyCall();
diff --git a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
index 9f2139a..c477ce4 100644
--- a/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/src/android/telephony/cts/TelephonyManagerTest.java
@@ -205,7 +205,13 @@
         mTelephonyManager.getNetworkOperator();
         mTelephonyManager.getSimCountryIso();
         mTelephonyManager.getVoiceMailAlphaTag();
-        mTelephonyManager.getNeighboringCellInfo();
+        try {
+            mTelephonyManager.getNeighboringCellInfo();
+        } catch (SecurityException expectedForQ) {
+            // FIXME(nharold): This API will always throw a SecurityException for SDK level Q+.
+            // For earlier API levels this check should ensure that no exception is thrown.
+        }
+
         mTelephonyManager.isNetworkRoaming();
         mTelephonyManager.getDeviceId();
         mTelephonyManager.getDeviceId(mTelephonyManager.getSlotIndex());
@@ -610,22 +616,12 @@
         }
 
         for(String plmn : plmns) {
-            if (plmn.length() > 6 || plmn.length() < 5) {
-                fail("Invalid Length for PLMN-ID, must be 5 or 6: " + plmn);
-            }
-
-            // A record which is written in the SIM but empty will
-            // be all f's
-            if(android.text.TextUtils.isDigitsOnly(plmn)) {
-                assertTrue(
-                        "PLMNs must be strings of digits 0-9,F! " + plmn,
-                        android.text.TextUtils.isDigitsOnly(plmn));
-            } else {
-                for (char c : plmn.toUpperCase().toCharArray()) {
-                    assertTrue("PLMNs must be strings of digits 0-9,F! " + plmn,
-                            Character.toUpperCase(c) == 'F');
-                }
-            }
+            assertTrue(
+                    "Invalid Length for PLMN-ID, must be 5 or 6! plmn=" + plmn,
+                    plmn.length() >= 5 && plmn.length() <= 6);
+            assertTrue(
+                    "PLMNs must be strings of digits 0-9! plmn=" + plmn,
+                    android.text.TextUtils.isDigitsOnly(plmn));
         }
     }
 
diff --git a/tests/tests/uirendering/Android.bp b/tests/tests/uirendering/Android.bp
new file mode 100644
index 0000000..6c8bb8fa
--- /dev/null
+++ b/tests/tests/uirendering/Android.bp
@@ -0,0 +1,38 @@
+// 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.
+
+android_test {
+    name: "CtsUiRenderingTestCases",
+    sdk_version: "test_current",
+
+    srcs: [
+        "src/**/*.java",
+        "src/**/*.kt",
+    ],
+
+    static_libs: [
+        "compatibility-device-util",
+        "ctsdeviceutillegacy",
+        "mockito-target-minus-junit4",
+        "android-support-test",
+    ],
+
+    libs: ["android.test.runner.stubs"],
+
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+}
\ No newline at end of file
diff --git a/tests/tests/uirendering/Android.mk b/tests/tests/uirendering/Android.mk
deleted file mode 100644
index ec98a0e..0000000
--- a/tests/tests/uirendering/Android.mk
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-# don't include this package in any target
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
-
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util \
-    ctsdeviceutillegacy \
-    ctstestrunner \
-    mockito-target-minus-junit4 \
-    android-support-test
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_PACKAGE_NAME := CtsUiRenderingTestCases
-
-# Enforce public / test api only
-LOCAL_SDK_VERSION := test_current
-
-include $(BUILD_CTS_PACKAGE)
diff --git a/tests/tests/view/src/android/view/cts/DragDropTest.java b/tests/tests/view/src/android/view/cts/DragDropTest.java
index 2ae12f0..d53d8c3 100644
--- a/tests/tests/view/src/android/view/cts/DragDropTest.java
+++ b/tests/tests/view/src/android/view/cts/DragDropTest.java
@@ -241,7 +241,7 @@
             long downTime = SystemClock.uptimeMillis();
             MotionEvent event = MotionEvent.obtain(downTime, downTime, action,
                     destLoc[0] + offset, destLoc[1] + offset, 1);
-            event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
+            event.setSource(InputDevice.SOURCE_MOUSE);
             mAutomation.injectInputEvent(event, false);
         });
 
diff --git a/tests/tests/view/src/android/view/cts/TextureViewTest.java b/tests/tests/view/src/android/view/cts/TextureViewTest.java
index 88ac1f5..431b27d 100644
--- a/tests/tests/view/src/android/view/cts/TextureViewTest.java
+++ b/tests/tests/view/src/android/view/cts/TextureViewTest.java
@@ -45,6 +45,7 @@
 import com.android.compatibility.common.util.SynchronousPixelCopy;
 import com.android.compatibility.common.util.WidgetTestUtils;
 
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -118,6 +119,7 @@
     }
 
     @Test
+    @Ignore // Temporary, see b/111801626
     public void testRotateScale() throws Throwable {
         final TextureViewCtsActivity activity = mActivityRule.launchActivity(null);
         final TextureView textureView = activity.getTextureView();
@@ -157,6 +159,7 @@
     }
 
     @Test
+    @Ignore // Temporary, see b/111801626
     public void testTransformScale() throws Throwable {
         final TextureViewCtsActivity activity = mActivityRule.launchActivity(null);
         final TextureView textureView = activity.getTextureView();
diff --git a/tests/tests/widget/src/android/widget/cts/OWNERS b/tests/tests/widget/src/android/widget/cts/OWNERS
index f8095fe..dd41f7f 100644
--- a/tests/tests/widget/src/android/widget/cts/OWNERS
+++ b/tests/tests/widget/src/android/widget/cts/OWNERS
@@ -1,7 +1 @@
-per-file TextView*.java = siyamed@google.com
-per-file TextView*.java = nona@google.com
-per-file TextView*.java = clarabayarri@google.com
-
-per-file EditText*.java = siyamed@google.com
-per-file EditText*.java = nona@google.com
-per-file EditText*.java = clarabayarri@google.com
+per-file TextView*.java, EditText*.java = siyamed@google.com, nona@google.com, clarabayarri@google.com
diff --git a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
index f9103e6..c25c620 100644
--- a/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
+++ b/tests/tests/widget/src/android/widget/cts/PopupWindowTest.java
@@ -32,6 +32,7 @@
 import android.app.Instrumentation;
 import android.content.Context;
 import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
 import android.content.res.Configuration;
 import android.graphics.Color;
 import android.graphics.Point;
@@ -79,6 +80,7 @@
     private static final int CONTENT_SIZE_DP = 30;
 
     private Instrumentation mInstrumentation;
+    private Context mContext;
     private PopupWindowCtsActivity mActivity;
     private PopupWindow mPopupWindow;
     private TextView mTextView;
@@ -90,6 +92,7 @@
     @Before
     public void setup() {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
+        mContext = InstrumentationRegistry.getContext();
         mActivity = mActivityRule.getActivity();
     }
 
@@ -1332,6 +1335,11 @@
 
         for (int i = 0; i < 2; i++) {
             final int orientation = orientationValues[i];
+            if (orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
+                    && !hasDeviceFeature(PackageManager.FEATURE_SCREEN_PORTRAIT)) {
+                // skip test for devices not supporting portrait orientation
+                continue;
+            }
             mActivity.runOnUiThread(() ->
                     mActivity.setRequestedOrientation(orientation));
             mActivity.waitForConfigurationChanged();
@@ -1600,6 +1608,10 @@
         return window;
     }
 
+    private boolean hasDeviceFeature(final String requiredFeature) {
+        return mContext.getPackageManager().hasSystemFeature(requiredFeature);
+    }
+
     private void showPopup(int resourceId) throws Throwable {
         mActivityRule.runOnUiThread(() -> {
             if (mPopupWindow == null || mPopupWindow.isShowing()) {
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_double/AddDoubleTest.java b/tests/vm/src/android/vm/cts/opcodes/add_double/AddDoubleTest.java
deleted file mode 100644
index ba5a41d..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_double/AddDoubleTest.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.vm.cts.opcodes.add_double;
-
-import junit.framework.TestCase;
-
-public class AddDoubleTest extends TestCase {
-
-    /**
-     * @title Arguments = 2.7d, 3.14d
-     */
-    public void testN1() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(5.84d, t.run(2.7d, 3.14d));
-    }
-
-    /**
-     * @title Arguments = 0, -3.14d
-     */
-    public void testN2() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(-3.14d, t.run(0, -3.14d));
-    }
-
-    /**
-     * @title Arguments = -3.14d, -2.7d
-     */
-    public void testN3() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(-5.84d, t.run(-3.14d, -2.7d));
-    }
-
-    /**
-     * @title Arguments = Double.MAX_VALUE, Double.NaN
-     */
-    public void testB1() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(Double.NaN, t.run(Double.MAX_VALUE, Double.NaN));
-    }
-
-    /**
-     * @title Arguments = Double.POSITIVE_INFINITY,
-     * Double.NEGATIVE_INFINITY
-     */
-    public void testB2() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(Double.NaN, t.run(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY));
-    }
-
-    /**
-     * @title Arguments = Double.POSITIVE_INFINITY,
-     * Double.POSITIVE_INFINITY
-     */
-    public void testB3() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(Double.POSITIVE_INFINITY, t.run(Double.POSITIVE_INFINITY,
-                Double.POSITIVE_INFINITY));
-    }
-
-    /**
-     * @title Arguments = Double.POSITIVE_INFINITY, -2.7d
-     */
-    public void testB4() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(Double.POSITIVE_INFINITY, t.run(Double.POSITIVE_INFINITY, -2.7d));
-    }
-
-    /**
-     * @title Arguments = +0, -0
-     */
-    public void testB5() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(+0d, t.run(+0d, -0d));
-    }
-
-    /**
-     * @title Arguments = -0d, -0d
-     */
-    public void testB6() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(-0d, t.run(-0d, -0d));
-    }
-
-    /**
-     * @title Arguments = -2.7d, 2.7d
-     */
-    public void testB7() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(+0d, t.run(-2.7d, 2.7d));
-    }
-
-    /**
-     * @title Arguments = Double.MAX_VALUE, Double.MAX_VALUE
-     */
-    public void testB8() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(Double.POSITIVE_INFINITY, t.run(Double.MAX_VALUE, Double.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Double.MIN_VALUE, -4.9E-324
-     */
-    public void testB9() {
-        AddDouble_1 t = new AddDouble_1();
-        assertEquals(0d, t.run(Double.MIN_VALUE, -4.9E-324));
-    }
-
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_double/AddDouble_1.java b/tests/vm/src/android/vm/cts/opcodes/add_double/AddDouble_1.java
deleted file mode 100644
index d4ebed2..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_double/AddDouble_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_double;
-
-public class AddDouble_1 {
-
-    public double run(double a, double b) {
-        return a + b;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_double/AddDouble_3.java b/tests/vm/src/android/vm/cts/opcodes/add_double/AddDouble_3.java
deleted file mode 100644
index 587a68b..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_double/AddDouble_3.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_double;
-
-public class AddDouble_3 {
-
-    public double run(long a, double b) {
-        return 1;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2AddrTest.java b/tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2AddrTest.java
deleted file mode 100644
index 27de92c..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2AddrTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_double_2addr;
-
-import junit.framework.TestCase;
-
-public class AddDouble2AddrTest extends TestCase {
-    /**
-     * @title Arguments = 2.7d, 3.14d
-     */
-    public void testN1() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(5.84d, t.run(2.7d, 3.14d));
-    }
-
-    /**
-     * @title Arguments = 0, -3.14d
-     */
-    public void testN2() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(-3.14d, t.run(0, -3.14d));
-    }
-
-    /**
-     * @title Arguments = -3.14d, -2.7d
-     */
-    public void testN3() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(-5.84d, t.run(-3.14d, -2.7d));
-    }
-
-    /**
-     * @title Arguments = Double.MAX_VALUE, Double.NaN
-     */
-    public void testB1() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(Double.NaN, t.run(Double.MAX_VALUE, Double.NaN));
-    }
-
-    /**
-     * @title Arguments = Double.POSITIVE_INFINITY,
-     * Double.NEGATIVE_INFINITY
-     */
-    public void testB2() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(Double.NaN, t.run(Double.POSITIVE_INFINITY,
-                Double.NEGATIVE_INFINITY));
-    }
-
-    /**
-     * @title Arguments = Double.POSITIVE_INFINITY,
-     * Double.POSITIVE_INFINITY
-     */
-    public void testB3() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(Double.POSITIVE_INFINITY, t.run(Double.POSITIVE_INFINITY,
-                Double.POSITIVE_INFINITY));
-    }
-
-    /**
-     * @title Arguments = Double.POSITIVE_INFINITY, -2.7d
-     */
-    public void testB4() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(Double.POSITIVE_INFINITY, t.run(Double.POSITIVE_INFINITY,
-                -2.7d));
-    }
-
-    /**
-     * @title Arguments = +0, -0
-     */
-    public void testB5() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(+0d, t.run(+0d, -0d));
-    }
-
-    /**
-     * @title Arguments = -0d, -0d
-     */
-    public void testB6() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(-0d, t.run(-0d, -0d));
-    }
-
-    /**
-     * @title Arguments = -2.7d, 2.7d
-     */
-    public void testB7() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(+0d, t.run(-2.7d, 2.7d));
-    }
-
-    /**
-     * @title Arguments = Double.MAX_VALUE, Double.MAX_VALUE
-     */
-    public void testB8() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(Double.POSITIVE_INFINITY, t.run(Double.MAX_VALUE,
-                Double.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Double.MIN_VALUE, -4.9E-324
-     */
-    public void testB9() {
-        AddDouble2Addr_1 t = new AddDouble2Addr_1();
-        assertEquals(0d, t.run(Double.MIN_VALUE, -4.9E-324));
-    }
-
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2Addr_3.java b/tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2Addr_3.java
deleted file mode 100644
index 7ed1fe8..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_double_2addr/AddDouble2Addr_3.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_double_2addr;
-
-public class AddDouble2Addr_3 {
-
-    public double run(long a) {
-        return 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloatTest.java b/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloatTest.java
deleted file mode 100644
index 76490b0..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloatTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_float;
-
-import junit.framework.TestCase;
-
-public class AddFloatTest extends TestCase {
-    /**
-     * @title Arguments = 2.7f, 3.14f
-     */
-    public void testN1() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(5.84f, t.run(2.7f, 3.14f));
-    }
-
-    /**
-     * @title Arguments = 0, -3.14f
-     */
-    public void testN2() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(-3.14f, t.run(0, -3.14f));
-    }
-
-    /**
-     * @title Arguments = -3.14f, -2.7f
-     */
-    public void testN3() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(-5.84f, t.run(-3.14f, -2.7f));
-    }
-
-    /**
-     * @title Arguments = Float.MAX_VALUE, Float.NaN
-     */
-    public void testB1() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(Float.POSITIVE_INFINITY, t.run(3.3028235E38f, 0.11E38f));
-    }
-
-    /**
-     * @title Arguments = Float.POSITIVE_INFINITY,
-     * Float.NEGATIVE_INFINITY
-     */
-    public void testB2() {
-        AddFloat_1 t = new AddFloat_1();
-        assertTrue(Float.isNaN(t.run(Float.POSITIVE_INFINITY,
-                Float.NEGATIVE_INFINITY)));
-    }
-
-    /**
-     * @title Arguments = Float.POSITIVE_INFINITY,
-     * Float.POSITIVE_INFINITY
-     */
-    public void testB3() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(Float.POSITIVE_INFINITY, t.run(Float.POSITIVE_INFINITY,
-                Float.POSITIVE_INFINITY));
-    }
-
-    /**
-     * @title Arguments = Float.POSITIVE_INFINITY, -2.7f
-     */
-    public void testB4() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(Float.POSITIVE_INFINITY, t.run(Float.POSITIVE_INFINITY,
-                -2.7f));
-    }
-
-    /**
-     * @title Arguments = +0, -0f
-     */
-    public void testB5() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(+0f, t.run(+0f, -0f));
-    }
-
-    /**
-     * @title Arguments = -0f, -0f
-     */
-    public void testB6() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(-0f, t.run(-0f, -0f));
-    }
-
-    /**
-     * @title Arguments = -2.7f, 2.7f
-     */
-    public void testB7() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(+0f, t.run(-2.7f, 2.7f));
-    }
-
-    /**
-     * @title Arguments = Float.MAX_VALUE, Float.MAX_VALUE
-     */
-    public void testB8() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(Float.POSITIVE_INFINITY, t.run(Float.MAX_VALUE,
-                Float.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Float.MIN_VALUE, -1.4E-45f
-     */
-    public void testB9() {
-        AddFloat_1 t = new AddFloat_1();
-        assertEquals(0f, t.run(Float.MIN_VALUE, -1.4E-45f));
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloat_1.java b/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloat_1.java
deleted file mode 100644
index aff5beb..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloat_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_float;
-
-public class AddFloat_1 {
-
-    public float run(float a, float b) {
-        return a + b;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloat_5.java b/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloat_5.java
deleted file mode 100644
index 2eba052..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_float/AddFloat_5.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_float;
-
-public class AddFloat_5 {
-
-    public float run(int a, float b) {
-        return 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2AddrTest.java b/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2AddrTest.java
deleted file mode 100644
index 177e564..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2AddrTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.vm.cts.opcodes.add_float_2addr;
-
-import junit.framework.TestCase;
-
-public class AddFloat2AddrTest extends TestCase {
-    /**
-     * @title Arguments = 2.7f, 3.14f
-     */
-    public void testN1() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(5.84f, t.run(2.7f, 3.14f));
-    }
-
-    /**
-     * @title Arguments = 0, -3.14f
-     */
-    public void testN2() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(-3.14f, t.run(0, -3.14f));
-    }
-
-    /**
-     * @title Arguments = -3.14f, -2.7f
-     */
-    public void testN3() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(-5.84f, t.run(-3.14f, -2.7f));
-    }
-
-    /**
-     * @title Arguments = Float.MAX_VALUE, Float.NaN
-     */
-    public void testB1() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(Float.POSITIVE_INFINITY, t.run(3.3028235E38f, 0.11E38f));
-    }
-
-    /**
-     * @title Arguments = Float.POSITIVE_INFINITY,
-     * Float.NEGATIVE_INFINITY
-     */
-    public void testB2() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertTrue(Float.isNaN(t.run(Float.POSITIVE_INFINITY,
-                Float.NEGATIVE_INFINITY)));
-    }
-
-    /**
-     * @title Arguments = Float.POSITIVE_INFINITY,
-     * Float.POSITIVE_INFINITY
-     */
-    public void testB3() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(Float.POSITIVE_INFINITY, t.run(Float.POSITIVE_INFINITY,
-                Float.POSITIVE_INFINITY));
-    }
-
-    /**
-     * @title Arguments = Float.POSITIVE_INFINITY, -2.7f
-     */
-    public void testB4() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(Float.POSITIVE_INFINITY, t.run(Float.POSITIVE_INFINITY,
-                -2.7f));
-    }
-
-    /**
-     * @title Arguments = +0, -0f
-     */
-    public void testB5() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(+0f, t.run(+0f, -0f));
-    }
-
-    /**
-     * @title Arguments = -0f, -0f
-     */
-    public void testB6() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(-0f, t.run(-0f, -0f));
-    }
-
-    /**
-     * @title Arguments = -2.7f, 2.7f
-     */
-    public void testB7() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(+0f, t.run(-2.7f, 2.7f));
-    }
-
-    /**
-     * @title Arguments = Float.MAX_VALUE, Float.MAX_VALUE
-     */
-    public void testB8() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(Float.POSITIVE_INFINITY, t.run(Float.MAX_VALUE,
-                Float.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Float.MIN_VALUE, -1.4E-45f
-     */
-    public void testB9() {
-        AddFloat2Addr_1 t = new AddFloat2Addr_1();
-        assertEquals(0f, t.run(Float.MIN_VALUE, -1.4E-45f));
-    }
-
-    
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2Addr_1.java b/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2Addr_1.java
deleted file mode 100644
index cabd4f9..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2Addr_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_float_2addr;
-
-public class AddFloat2Addr_1 {
-
-    public float run(float a, float b) {
-        return a + b;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2Addr_5.java b/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2Addr_5.java
deleted file mode 100644
index 7fdd723..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_float_2addr/AddFloat2Addr_5.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_float_2addr;
-
-public class AddFloat2Addr_5 {
-
-    public float run(int a, float b) {
-        return 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int/AddIntTest.java b/tests/vm/src/android/vm/cts/opcodes/add_int/AddIntTest.java
deleted file mode 100644
index 7e67da63..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int/AddIntTest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.vm.cts.opcodes.add_int;
-
-import junit.framework.TestCase;
-
-public class AddIntTest extends TestCase {
-    /**
-     * @title Arguments = 8, 4
-     */
-    public void testN1() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(12, t.run(8, 4));
-    }
-
-    /**
-     * @title Arguments = 0, 255
-     */
-    public void testN2() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(255, t.run(0, 255));
-    }
-
-    /**
-     * @title Arguments = 0, -65536
-     */
-    public void testN3() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(-65536, t.run(0, -65536));
-    }
-
-    /**
-     * @title Arguments = 0, -2147483647
-     */
-    public void testN4() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(-2147483647, t.run(0, -2147483647));
-    }
-
-    /**
-     * @title Arguments = 0x7ffffffe, 2
-     */
-    public void testN5() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(-2147483648, t.run(0x7ffffffe, 2));
-    }
-
-    /**
-     * @title Arguments = -1, 1
-     */
-    public void testN6() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(0, t.run(-1, 1));
-    }
-
-
-    /**
-     * @title Arguments = 0, Integer.MAX_VALUE
-     */
-    public void testB1() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(Integer.MAX_VALUE, t.run(0, Integer.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Integer.MAX_VALUE, Integer.MAX_VALUE
-     */
-    public void testB2() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(-2, t.run(Integer.MAX_VALUE, Integer.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Integer.MAX_VALUE, 1
-     */
-    public void testB3() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(Integer.MIN_VALUE, t.run(Integer.MAX_VALUE, 1));
-    }
-
-    /**
-     * @title Arguments = Integer.MIN_VALUE, 1
-     */
-    public void testB4() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(-2147483647, t.run(Integer.MIN_VALUE, 1));
-    }
-
-    /**
-     * @title Arguments = 0, 0
-     */
-    public void testB5() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(0, t.run(0, 0));
-    }
-
-    /**
-     * @title Arguments = Integer.MIN_VALUE, Integer.MIN_VALUE
-     */
-    public void testB6() {
-        AddInt_1 t = new AddInt_1();
-        assertEquals(0, t.run(Integer.MIN_VALUE, Integer.MIN_VALUE));
-    }
-
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int/AddInt_1.java b/tests/vm/src/android/vm/cts/opcodes/add_int/AddInt_1.java
deleted file mode 100644
index 825821d..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int/AddInt_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int;
-
-public class AddInt_1 {
-
-    public int run(int a, int b) {
-        return a + b;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int/AddInt_5.java b/tests/vm/src/android/vm/cts/opcodes/add_int/AddInt_5.java
deleted file mode 100644
index c17caaa..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int/AddInt_5.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int;
-
-public class AddInt_5 {
-
-    public int run(int a, float b) {
-        return 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2AddrTest.java b/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2AddrTest.java
deleted file mode 100644
index b2c4eb3..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2AddrTest.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.vm.cts.opcodes.add_int_2addr;
-
-import junit.framework.TestCase;
-
-public class AddInt2AddrTest extends TestCase {
-    /**
-     * @title Arguments = 8, 4
-     */
-    public void testN1() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(12, t.run(8, 4));
-    }
-
-    /**
-     * @title Arguments = 0, 255
-     */
-    public void testN2() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(255, t.run(0, 255));
-    }
-
-    /**
-     * @title Arguments = 0, -65536
-     */
-    public void testN3() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(-65536, t.run(0, -65536));
-    }
-
-    /**
-     * @title Arguments = 0, -2147483647
-     */
-    public void testN4() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(-2147483647, t.run(0, -2147483647));
-    }
-
-    /**
-     * @title Arguments = 0x7ffffffe, 2
-     */
-    public void testN5() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(-2147483648, t.run(0x7ffffffe, 2));
-    }
-
-    /**
-     * @title Arguments = -1, 1
-     */
-    public void testN6() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(0, t.run(-1, 1));
-    }
-
-    /**
-     * @title Arguments = 0, Integer.MAX_VALUE
-     */
-    public void testB1() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(Integer.MAX_VALUE, t.run(0, Integer.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Integer.MAX_VALUE, Integer.MAX_VALUE
-     */
-    public void testB2() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(-2, t.run(Integer.MAX_VALUE, Integer.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Integer.MAX_VALUE, 1
-     */
-    public void testB3() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(Integer.MIN_VALUE, t.run(Integer.MAX_VALUE, 1));
-    }
-
-    /**
-     * @title Arguments = Integer.MIN_VALUE, 1
-     */
-    public void testB4() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(-2147483647, t.run(Integer.MIN_VALUE, 1));
-    }
-
-    /**
-     * @title Arguments = 0, 0
-     */
-    public void testB5() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(0, t.run(0, 0));
-    }
-
-    /**
-     * @title Arguments = Integer.MIN_VALUE, Integer.MIN_VALUE
-     */
-    public void testB6() {
-        AddInt2Addr_1 t = new AddInt2Addr_1();
-        assertEquals(0, t.run(Integer.MIN_VALUE, Integer.MIN_VALUE));
-    }
-
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2Addr_1.java b/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2Addr_1.java
deleted file mode 100644
index ec0757b..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2Addr_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_2addr;
-
-public class AddInt2Addr_1 {
-
-    public int run(int a, int b) {
-        return a+b;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2Addr_5.java b/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2Addr_5.java
deleted file mode 100644
index 8b78444..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_2addr/AddInt2Addr_5.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_2addr;
-
-public class AddInt2Addr_5 {
-
-    public int run(int a, float b) {
-        return 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16Test.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16Test.java
deleted file mode 100644
index cc378df7..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16Test.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.vm.cts.opcodes.add_int_lit16;
-
-import junit.framework.TestCase;
-
-public class AddIntLit16Test extends TestCase {
-    /**
-     * @title Arguments = 8 + 4
-     */
-    public void testN1() {
-        AddIntLit16_1 t = new AddIntLit16_1();
-        assertEquals(12, t.run());
-    }
-
-    /**
-     * @title Arguments = 0 + 255
-     */
-    public void testN2() {
-        AddIntLit16_2 t = new AddIntLit16_2();
-        assertEquals(255, t.run());
-    }
-
-    /**
-     * @title Arguments = 0 + (-32768)
-     */
-    public void testN3() {
-        AddIntLit16_3 t = new AddIntLit16_3();
-        assertEquals(-32768, t.run());
-    }
-
-    /**
-     * @title Arguments = (-2147483647) + 0
-     */
-    public void testN4() {
-        AddIntLit16_4 t = new AddIntLit16_4();
-        assertEquals(-2147483647, t.run());
-    }
-
-    /**
-     * @title Arguments = 0x7ffffffe + 2
-     */
-    public void testN5() {
-        AddIntLit16_5 t = new AddIntLit16_5();
-        assertEquals(-2147483648, t.run());
-    }
-
-    /**
-     * @title Arguments = -1 + 1
-     */
-    public void testN6() {
-        AddIntLit16_6 t = new AddIntLit16_6();
-        assertEquals(0, t.run());
-    }
-
-    /**
-     * @title Arguments = 0 + Short.MAX_VALUE
-     */
-    public void testB1() {
-        AddIntLit16_7 t = new AddIntLit16_7();
-        assertEquals(Short.MAX_VALUE, t.run());
-    }
-
-    /**
-     * @title Arguments = Integer.MAX_VALUE + Short.MAX_VALUE
-     */
-    public void testB2() {
-        AddIntLit16_8 t = new AddIntLit16_8();
-        assertEquals(-2147450882, t.run());
-    }
-
-    /**
-     * @title Arguments = Integer.MAX_VALUE + 1
-     */
-    public void testB3() {
-        AddIntLit16_9 t = new AddIntLit16_9();
-        assertEquals(Integer.MIN_VALUE, t.run());
-    }
-
-    /**
-     * @title Arguments = Integer.MIN_VALUE + 1
-     */
-    public void testB4() {
-        AddIntLit16_10 t = new AddIntLit16_10();
-        assertEquals(-2147483647, t.run());
-    }
-
-    /**
-     * @title Arguments = 0 + 0
-     */
-    public void testB5() {
-        AddIntLit16_11 t = new AddIntLit16_11();
-        assertEquals(0, t.run());
-    }
-
-    /**
-     * @title Arguments = Short.MIN_VALUE + Short.MIN_VALUE
-     */
-    public void testB6() {
-        AddIntLit16_12 t = new AddIntLit16_12();
-        assertEquals(-65536, t.run());
-    }
-    
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_1.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_1.java
deleted file mode 100644
index 95313ee..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_1 {
-
-    public int run() {
-        return 8 + 4;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_10.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_10.java
deleted file mode 100644
index e5fa9fa..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_10.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_10 {
-
-    public int run() {
-        return Integer.MIN_VALUE + 1;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_11.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_11.java
deleted file mode 100644
index 375cfff..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_11.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_11 {
-
-    public int run() {
-        return 0 + 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_12.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_12.java
deleted file mode 100644
index 3c30be0..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_12.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_12 {
-
-    public int run() {
-        return Short.MIN_VALUE + Short.MIN_VALUE;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_16.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_16.java
deleted file mode 100644
index 5f3d6f9..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_16.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_16 {
-
-    public int run(float f) {
-        return 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_2.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_2.java
deleted file mode 100644
index 69c6c8d..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_2.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_2 {
-
-    public int run() {
-        return 0 + 255;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_3.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_3.java
deleted file mode 100644
index 51e84ba..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_3.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_3 {
-
-    public int run() {
-        return 0 + (-32768);
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_4.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_4.java
deleted file mode 100644
index 0fa1146..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_4.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_4 {
-
-    public int run() {
-        return (-2147483647) + 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_5.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_5.java
deleted file mode 100644
index 2080b8b..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_5.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_5 {
-
-    public int run() {
-        return 0x7ffffffe + 2;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_6.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_6.java
deleted file mode 100644
index 4db27b0..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_6.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_6 {
-
-    public int run() {
-        return -1 + 1;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_7.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_7.java
deleted file mode 100644
index b74ed5d..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_7.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_7 {
-
-    public int run() {
-        return 0 + Short.MAX_VALUE;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_8.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_8.java
deleted file mode 100644
index c4900e0..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_8.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_8 {
-
-    public int run() {
-        return Integer.MAX_VALUE + Short.MAX_VALUE;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_9.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_9.java
deleted file mode 100644
index 3368cf9..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit16/AddIntLit16_9.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit16;
-
-public class AddIntLit16_9 {
-
-    public int run() {
-        return Integer.MAX_VALUE + 1;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8.java
deleted file mode 100644
index fe3710b..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.vm.cts.opcodes.add_int_lit8;
-
-import junit.framework.TestCase;
-
-public class AddIntLit8 extends TestCase {
-    /**
-     * @title Arguments = 8 + 4
-     */
-    public void testN1() {
-        AddIntLit8_1 t = new AddIntLit8_1();
-        assertEquals(12, t.run());
-    }
-
-    /**
-     * @title Arguments = Byte.MIN_VALUE + Byte.MAX_VALUE
-     */
-    public void testN2() {
-        AddIntLit8_2 t = new AddIntLit8_2();
-        assertEquals(-1, t.run());
-    }
-
-    /**
-     * @title Arguments = 0 + (-128)
-     */
-    public void testN3() {
-        AddIntLit8_3 t = new AddIntLit8_3();
-        assertEquals(-128, t.run());
-    }
-
-    /**
-     * @title Arguments = (-2147483647) + 0
-     */
-    public void testN4() {
-        AddIntLit8_4 t = new AddIntLit8_4();
-        assertEquals(-2147483647, t.run());
-    }
-
-    /**
-     * @title Arguments = 0x7ffffffe + 2
-     */
-    public void testN5() {
-        AddIntLit8_5 t = new AddIntLit8_5();
-        assertEquals(-2147483648, t.run());
-    }
-
-    /**
-     * @title Arguments = -1 + 1
-     */
-    public void testN6() {
-        AddIntLit8_6 t = new AddIntLit8_6();
-        assertEquals(0, t.run());
-    }
-
-    /**
-     * @title Arguments = 0 + Byte.MAX_VALUE
-     */
-    public void testB1() {
-        AddIntLit8_7 t = new AddIntLit8_7();
-        assertEquals(Byte.MAX_VALUE, t.run());
-    }
-
-    /**
-     * @title Arguments = Integer.MAX_VALUE + Byte.MAX_VALUE
-     */
-    public void testB2() {
-        AddIntLit8_8 t = new AddIntLit8_8();
-        assertEquals(-2147483522, t.run());
-    }
-
-    /**
-     * @title Arguments = Integer.MAX_VALUE + 1
-     */
-    public void testB3() {
-        AddIntLit8_9 t = new AddIntLit8_9();
-        assertEquals(Integer.MIN_VALUE, t.run());
-    }
-
-    /**
-     * @title Arguments = Integer.MIN_VALUE + 1
-     */
-    public void testB4() {
-        AddIntLit8_10 t = new AddIntLit8_10();
-        assertEquals(-2147483647, t.run());
-    }
-
-    /**
-     * @title Arguments = 0 + 0
-     */
-    public void testB5() {
-        AddIntLit8_11 t = new AddIntLit8_11();
-        assertEquals(0, t.run());
-    }
-
-    /**
-     * @title Arguments = Short.MIN_VALUE + Byte.MIN_VALUE
-     */
-    public void testB6() {
-        AddIntLit8_12 t = new AddIntLit8_12();
-        assertEquals(-32896, t.run());
-    }
-
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_1.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_1.java
deleted file mode 100644
index 2017b31..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_1 {
-
-    public int run() {
-        return 8 + 4;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_10.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_10.java
deleted file mode 100644
index 88fae83..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_10.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_10 {
-
-    public int run() {
-        return Integer.MIN_VALUE + 1;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_11.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_11.java
deleted file mode 100644
index 5c29a91..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_11.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_11 {
-
-    public int run() {
-        return 0 + 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_12.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_12.java
deleted file mode 100644
index 9fa0a8d..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_12.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_12 {
-
-    public int run() {
-        return Short.MIN_VALUE + Byte.MIN_VALUE;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_16.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_16.java
deleted file mode 100644
index f8338e8..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_16.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_16 {
-
-    public int run(float f) {
-        return 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_2.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_2.java
deleted file mode 100644
index eaa4f38..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_2.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_2 {
-
-    public int run() {
-        return Byte.MIN_VALUE + Byte.MAX_VALUE;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_3.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_3.java
deleted file mode 100644
index e7b0534..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_3.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_3 {
-
-    public int run() {
-        return 0 + (-128);
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_4.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_4.java
deleted file mode 100644
index 7a22091..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_4.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_4 {
-
-    public int run() {
-        return (-2147483647) + 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_5.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_5.java
deleted file mode 100644
index bfbd8c5..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_5.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_5 {
-
-    public int run() {
-        return 0x7ffffffe + 2;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_6.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_6.java
deleted file mode 100644
index 7c14c374..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_6.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_6 {
-
-    public int run() {
-        return -1 + 1;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_7.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_7.java
deleted file mode 100644
index d5347d0..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_7.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_7 {
-
-    public int run() {
-        return 0 + Byte.MAX_VALUE;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_8.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_8.java
deleted file mode 100644
index c7a8a9b..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_8.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_8 {
-
-    public int run() {
-        return Integer.MAX_VALUE + Byte.MAX_VALUE;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_9.java b/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_9.java
deleted file mode 100644
index c246375..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_int_lit8/AddIntLit8_9.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_int_lit8;
-
-public class AddIntLit8_9 {
-
-    public int run() {
-        return Integer.MAX_VALUE + 1;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_long/AddLongTest.java b/tests/vm/src/android/vm/cts/opcodes/add_long/AddLongTest.java
deleted file mode 100644
index 27c4536..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_long/AddLongTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_long;
-
-import junit.framework.TestCase;
-
-public class AddLongTest extends TestCase {
-    /**
-     * @title Arguments = 12345678l, 87654321l
-     */
-    public void testN1() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(99999999l, t.run(12345678l, 87654321l));
-    }
-
-    /**
-     * @title Arguments = 0l, 87654321l
-     */
-    public void testN2() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(87654321l, t.run(0l, 87654321l));
-    }
-
-    /**
-     * @title Arguments = -12345678l, 0l
-     */
-    public void testN3() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(-12345678l, t.run(-12345678l, 0l));
-    }
-
-    /**
-     * @title Arguments = 0 + Long.MAX_VALUE
-     */
-    public void testB1() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(9223372036854775807L, t.run(0l, Long.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = 0 + Long.MIN_VALUE
-     */
-    public void testB2() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(-9223372036854775808L, t.run(0l, Long.MIN_VALUE));
-    }
-
-    /**
-     * @title Arguments = 0 + 0
-     */
-    public void testB3() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(0l, t.run(0l, 0l));
-    }
-
-    /**
-     * @title Arguments = Long.MAX_VALUE + Long.MAX_VALUE
-     */
-    public void testB4() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(-2, t.run(Long.MAX_VALUE, Long.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Long.MAX_VALUE + Long.MIN_VALUE
-     */
-    public void testB5() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(-1l, t.run(Long.MAX_VALUE, Long.MIN_VALUE));
-    }
-
-    /**
-     * @title Arguments = Long.MIN_VALUE + Long.MIN_VALUE
-     */
-    public void testB6() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(0l, t.run(Long.MIN_VALUE, Long.MIN_VALUE));
-    }
-
-    /**
-     * @title Arguments = Long.MIN_VALUE + 1
-     */
-    public void testB7() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(-9223372036854775807l, t.run(Long.MIN_VALUE, 1l));
-    }
-
-    /**
-     * @title Arguments = Long.MAX_VALUE + 1
-     */
-    public void testB8() {
-        AddLong_1 t = new AddLong_1();
-        assertEquals(-9223372036854775808l, t.run(Long.MAX_VALUE, 1l));
-    }
-
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_long/AddLong_1.java b/tests/vm/src/android/vm/cts/opcodes/add_long/AddLong_1.java
deleted file mode 100644
index 285e4df..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_long/AddLong_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_long;
-
-public class AddLong_1 {
-
-    public long run(long a, long b) {
-        return a+b;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_long/AddLong_6.java b/tests/vm/src/android/vm/cts/opcodes/add_long/AddLong_6.java
deleted file mode 100644
index ff7195e..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_long/AddLong_6.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_long;
-
-public class AddLong_6 {
-
-    public long run(long a, double b) {
-        return 0;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2AddrTest.java b/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2AddrTest.java
deleted file mode 100644
index 5e97757..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2AddrTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.vm.cts.opcodes.add_long_2addr;
-
-import junit.framework.TestCase;
-
-public class AddLong2AddrTest extends TestCase {
-    /**
-     * @title Arguments = 12345678l, 87654321l
-     */
-    public void testN1() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(99999999l, t.run(12345678l, 87654321l));
-    }
-
-    /**
-     * @title Arguments = 0l, 87654321l
-     */
-    public void testN2() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(87654321l, t.run(0l, 87654321l));
-    }
-
-    /**
-     * @title Arguments = -12345678l, 0l
-     */
-    public void testN3() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(-12345678l, t.run(-12345678l, 0l));
-    }
-
-    /**
-     * @title Arguments = 0 + Long.MAX_VALUE
-     */
-    public void testB1() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(9223372036854775807L, t.run(0l, Long.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = 0 + Long.MIN_VALUE
-     */
-    public void testB2() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(-9223372036854775808L, t.run(0l, Long.MIN_VALUE));
-    }
-
-    /**
-     * @title Arguments = 0 + 0
-     */
-    public void testB3() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(0l, t.run(0l, 0l));
-    }
-
-    /**
-     * @title Arguments = Long.MAX_VALUE + Long.MAX_VALUE
-     */
-    public void testB4() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(-2, t.run(Long.MAX_VALUE, Long.MAX_VALUE));
-    }
-
-    /**
-     * @title Arguments = Long.MAX_VALUE + Long.MIN_VALUE
-     */
-    public void testB5() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(-1l, t.run(Long.MAX_VALUE, Long.MIN_VALUE));
-    }
-
-    /**
-     * @title Arguments = Long.MIN_VALUE + Long.MIN_VALUE
-     */
-    public void testB6() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(0l, t.run(Long.MIN_VALUE, Long.MIN_VALUE));
-    }
-
-    /**
-     * @title Arguments = Long.MIN_VALUE + 1
-     */
-    public void testB7() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(-9223372036854775807l, t.run(Long.MIN_VALUE, 1l));
-    }
-
-    /**
-     * @title Arguments = Long.MAX_VALUE + 1
-     */
-    public void testB8() {
-        AddLong2Addr_1 t = new AddLong2Addr_1();
-        assertEquals(-9223372036854775808l, t.run(Long.MAX_VALUE, 1l));
-    }
-
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2Addr_1.java b/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2Addr_1.java
deleted file mode 100644
index 777a356..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2Addr_1.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_long_2addr;
-
-public class AddLong2Addr_1 {
-
-    public long run(long a, long b) {
-        return a+b;
-    }
-}
diff --git a/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2Addr_6.java b/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2Addr_6.java
deleted file mode 100644
index 4c7dd18..0000000
--- a/tests/vm/src/android/vm/cts/opcodes/add_long_2addr/AddLong2Addr_6.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.vm.cts.opcodes.add_long_2addr;
-
-public class AddLong2Addr_6 {
-
-    public long run(double a) {
-        return 0;
-    }
-}
diff --git a/tools/cts-api-coverage/Android.bp b/tools/cts-api-coverage/Android.bp
new file mode 100644
index 0000000..ed802ca
--- /dev/null
+++ b/tools/cts-api-coverage/Android.bp
@@ -0,0 +1,54 @@
+// Copyright (C) 2010 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+java_library_host {
+    name: "api-coverage",
+
+    srcs: [
+        "**/*.java",
+        "proto/**/*.proto",
+    ],
+
+    proto: {
+        type: "full",
+        local_include_dirs: ["proto"],
+    },
+
+    java_resource_dirs: ["res"],
+    manifest: "MANIFEST.mf",
+
+    static_libs: [
+        "compatibility-host-util",
+        "dexlib2",
+        // This tool is not checking any dependencies or metadata, so all of the
+        // dependencies of all of the tests must be on its classpath. This is
+        // super fragile.
+        "tradefed",
+        "hosttestlib",
+        "platformprotos",
+    ],
+}
+
+java_binary_host {
+    name: "cts-api-coverage",
+    wrapper: "etc/cts-api-coverage",
+    static_libs: ["api-coverage"],
+}
+
+java_binary_host {
+    name: "ndk-api-report",
+    wrapper: "etc/ndk-api-report",
+    static_libs: ["api-coverage"],
+}
diff --git a/tools/cts-api-coverage/Android.mk b/tools/cts-api-coverage/Android.mk
deleted file mode 100644
index 8e5e0ee..0000000
--- a/tools/cts-api-coverage/Android.mk
+++ /dev/null
@@ -1,65 +0,0 @@
-# Copyright (C) 2010 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-# the cts-api-coverage script
-# ============================================================
-include $(CLEAR_VARS)
-LOCAL_IS_HOST_MODULE := true
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_MODULE := cts-api-coverage
-LOCAL_SRC_FILES := etc/$(LOCAL_MODULE)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(HOST_OUT_JAVA_LIBRARIES)/$(LOCAL_MODULE)$(COMMON_JAVA_PACKAGE_SUFFIX)
-
-include $(BUILD_PREBUILT)
-
-# the ndk-api-report script
-# ============================================================
-include $(CLEAR_VARS)
-LOCAL_IS_HOST_MODULE := true
-LOCAL_MODULE_CLASS := EXECUTABLES
-LOCAL_MODULE := ndk-api-report
-LOCAL_SRC_FILES := etc/$(LOCAL_MODULE)
-
-include $(BUILD_PREBUILT)
-
-# cts-api-coverage java library
-# ============================================================
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := \
-    $(call all-subdir-java-files) \
-    $(call all-proto-files-under, proto)
-
-LOCAL_PROTOC_OPTIMIZE_TYPE := full
-LOCAL_PROTOC_FLAGS := --proto_path=$(LOCAL_PATH)/proto/
-
-LOCAL_JAVA_RESOURCE_DIRS := res
-LOCAL_JAR_MANIFEST := MANIFEST.mf
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-  compatibility-host-util \
-  dexlib2
-
-LOCAL_MODULE := cts-api-coverage
-
-# This tool is not checking any dependencies or metadata, so all of the
-# dependencies of all of the tests must be on its classpath. This is
-# super fragile.
-LOCAL_STATIC_JAVA_LIBRARIES += \
-  tradefed hosttestlib \
-  platformprotos
-
-include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/tools/cts-preconditions/Android.bp b/tools/cts-preconditions/Android.bp
new file mode 100644
index 0000000..47c92f3
--- /dev/null
+++ b/tools/cts-preconditions/Android.bp
@@ -0,0 +1,36 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+android_test {
+    name: "CtsPreconditions",
+
+    static_libs: [
+        "android-support-test",
+        "compatibility-device-preconditions",
+    ],
+
+    libs: ["android.test.base.stubs"],
+
+    srcs: ["src/**/*.java"],
+
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+        "cts_instant",
+    ],
+
+    sdk_version: "26",
+}
diff --git a/tools/cts-preconditions/Android.mk b/tools/cts-preconditions/Android.mk
deleted file mode 100644
index 888eadc..0000000
--- a/tools/cts-preconditions/Android.mk
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (C) 2015 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-
-# Don't include this package in any target
-LOCAL_MODULE_TAGS := tests
-# When built, explicitly put it in the data partition.
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_DEX_PREOPT := false
-
-LOCAL_PROGUARD_ENABLED := disabled
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    android-support-test \
-    compatibility-device-preconditions
-
-LOCAL_JAVA_LIBRARIES := android.test.base.stubs
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts vts general-tests cts_instant
-
-LOCAL_PACKAGE_NAME := CtsPreconditions
-
-LOCAL_SDK_VERSION := 26
-
-include $(BUILD_PACKAGE)
diff --git a/tools/cts-reference-app-lib/Android.mk b/tools/cts-reference-app-lib/Android.mk
deleted file mode 100644
index f006bb0..0000000
--- a/tools/cts-reference-app-lib/Android.mk
+++ /dev/null
@@ -1,35 +0,0 @@
-# Copyright (C) 2008 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-LOCAL_PATH := $(call my-dir)
-
-# the library
-# ============================================================
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(call all-subdir-java-files)
-
-# don't include this package in any target
-LOCAL_MODULE_TAGS := optional
-# and when built explicitly put it in the data partition
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_STATIC_JAVA_LIBRARIES := junit
-
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
-
-LOCAL_SDK_VERSION := current
-
-LOCAL_MODULE := android.cts.refapp
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/tools/cts-reference-app-lib/src/android/cts/refapp/ReferenceAppTestCase.java b/tools/cts-reference-app-lib/src/android/cts/refapp/ReferenceAppTestCase.java
deleted file mode 100644
index 203b690..0000000
--- a/tools/cts-reference-app-lib/src/android/cts/refapp/ReferenceAppTestCase.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.cts.refapp;
-
-import android.app.Activity;
-import android.test.ActivityInstrumentationTestCase2;
-import android.util.Log;
-
-import java.lang.InterruptedException;
-import java.lang.Thread;
-
-/**
- * Base Class that provides common functionality for all Reference Application Tests.
- */
-public class ReferenceAppTestCase<T extends Activity> extends ActivityInstrumentationTestCase2<T> {
-    /** The time to wait for the test host to finish taking the snapshot. */
-    private static final int SNAPSHOT_TIMEOUT_MS = 1000;
-    /** The default time that the applicaiton has to start in. */
-    private static final int DEFAULT_MAX_STATUP_TIME_MS = 5000;
-
-    private int maxStartupTimeMs;
-
-    /**
-     * Create a ReferenceAppTestCase for the specified activity.
-     *
-     * @param pkg the java package the class is contained in.
-     * @param activityClass the class of the activity to instrument.
-     * @param maxStartupTimeMs the startup time the activity should start in.
-     */
-    public ReferenceAppTestCase(String pkg, Class<T> activityClass, int maxStartupTimeMs) {
-        super(pkg, activityClass);
-        this.maxStartupTimeMs = maxStartupTimeMs;
-    }
-
-    /**
-     * Create a ReferenceAppTestCase for the specified activity.
-     *
-     * @param pkg the java package the class is contained in.
-     * @param activityClass the class of the activity to instrument.
-     */
-    public ReferenceAppTestCase(String pkg, Class<T> activityClass) {
-       this(pkg, activityClass, DEFAULT_MAX_STATUP_TIME_MS);
-    }
-
-    public void testActivityStartupTime() {
-        // Test activity startup time.
-
-        long start = System.currentTimeMillis();
-        Activity activity = getActivity();
-        long end = System.currentTimeMillis();
-
-        long startupTime = end - start;
-        assertTrue("Activity Startup took more than " + maxStartupTimeMs +
-                   " ms",
-                   startupTime <= maxStartupTimeMs);
-    }
-
-    /**
-     * Allows tests to record screen snapshots for inclusion in the
-     * CTS test report.
-     *
-     * @param name the name to save the snapshot under
-     */
-    public void takeSnapshot(String name) {
-        // request a snapshot from the CTS host
-        Log.d("ReferenceAppTestCase", "takeSnapshot:" + name);
-        // Give the host enough time to take the picture
-        try {
-            Thread.sleep(SNAPSHOT_TIMEOUT_MS);
-        } catch (InterruptedException e) {
-            // ok
-        }
-    }
-}
diff --git a/tools/junit/Android.mk b/tools/junit/Android.mk
deleted file mode 100644
index 0b56d0e..0000000
--- a/tools/junit/Android.mk
+++ /dev/null
@@ -1,24 +0,0 @@
-# Copyright (C) 2014 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES :=  $(call all-java-files-under, src)
-LOCAL_MODULE := cts-junit
-LOCAL_MODULE_TAGS := optional
-LOCAL_STATIC_JAVA_LIBRARIES := junit
-LOCAL_DEX_PREOPT := false
-LOCAL_SDK_VERSION := current
-include $(BUILD_JAVA_LIBRARY)
diff --git a/tools/junit/src/com/android/cts/junit/SingleJUnitTestRunListener.java b/tools/junit/src/com/android/cts/junit/SingleJUnitTestRunListener.java
deleted file mode 100644
index 06e9bc46..0000000
--- a/tools/junit/src/com/android/cts/junit/SingleJUnitTestRunListener.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.junit;
-
-import org.junit.runner.Description;
-import org.junit.runner.Result;
-import org.junit.runner.notification.Failure;
-import org.junit.runner.notification.RunListener;
-
-public class SingleJUnitTestRunListener extends RunListener {
-    private static class Prefixes {
-        @SuppressWarnings("unused")
-        private static final String INFORMATIONAL_MARKER = "[----------]";
-        private static final String START_TEST_RUN_MARKER = "[==========] Running";
-        private static final String TEST_RUN_MARKER = "[==========]";
-        private static final String START_TEST_MARKER = "[ RUN      ]";
-        private static final String OK_TEST_MARKER = "[       OK ]";
-        private static final String FAILED_TEST_MARKER = "[  FAILED  ]";
-    }
-
-    @Override
-    public void testRunStarted(Description description) throws Exception {
-    }
-
-    @Override
-    public void testRunFinished(Result result) throws Exception {
-        String status = result.wasSuccessful() ? Prefixes.OK_TEST_MARKER
-                : Prefixes.FAILED_TEST_MARKER;
-        System.out.println(status);
-    }
-
-    @Override
-    public void testStarted(Description description) throws Exception {
-        System.out.println(String.format("%s %s.%s", Prefixes.START_TEST_MARKER,
-                description.getClassName(), description.getMethodName()));
-    }
-
-    @Override
-    public void testFinished(Description description) throws Exception {
-    }
-
-    @Override
-    public void testFailure(Failure failure) throws Exception {
-    }
-
-    @Override
-    public void testAssumptionFailure(Failure failure) {
-    }
-
-    @Override
-    public void testIgnored(Description description) throws Exception {
-    }
-}
diff --git a/tools/junit/src/com/android/cts/junit/SingleJUnitTestRunner.java b/tools/junit/src/com/android/cts/junit/SingleJUnitTestRunner.java
deleted file mode 100644
index 2eb9f3a..0000000
--- a/tools/junit/src/com/android/cts/junit/SingleJUnitTestRunner.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.junit;
-
-import org.junit.runner.JUnitCore;
-import org.junit.runner.Request;
-import org.junit.runner.Result;
-
-/**
- * Test runner to run a single JUnit test. It will output either [PASSED] or [FAILED] at the end.
- */
-public class SingleJUnitTestRunner {
-    private static String mUsage = "Usage: java -cp <classpath> SingleJUnitTestRunner" +
-            " class#testmethod";
-    private static final String PASSED_TEST_MARKER = "[ PASSED ]";
-    private static final String FAILED_TEST_MARKER = "[ FAILED ]";
-
-    public static void main(String... args) throws ClassNotFoundException {
-        if (args.length != 1) {
-            throw new IllegalArgumentException(mUsage);
-        }
-        String[] classAndMethod = args[0].split("#");
-        if (classAndMethod.length != 2) {
-            throw new IllegalArgumentException(mUsage);
-        }
-        Request request = Request.method(Class.forName(classAndMethod[0]),
-                classAndMethod[1]);
-        JUnitCore jUnitCore = new JUnitCore();
-        Result result = jUnitCore.run(request);
-        String status = result.wasSuccessful() ? PASSED_TEST_MARKER : FAILED_TEST_MARKER;
-        System.out.println(String.format("%s %s.%s", status,
-                classAndMethod[0], classAndMethod[1]));
-    }
-}
diff --git a/tools/testng/Android.mk b/tools/testng/Android.mk
deleted file mode 100644
index af1593d..0000000
--- a/tools/testng/Android.mk
+++ /dev/null
@@ -1,23 +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_SRC_FILES :=  $(call all-java-files-under, src)
-LOCAL_MODULE := cts-testng
-LOCAL_MODULE_TAGS := optional
-LOCAL_STATIC_JAVA_LIBRARIES := testng
-LOCAL_DEX_PREOPT := false
-include $(BUILD_JAVA_LIBRARY)
diff --git a/tools/testng/gen-test-list-xml.py b/tools/testng/gen-test-list-xml.py
deleted file mode 100755
index 961410d..0000000
--- a/tools/testng/gen-test-list-xml.py
+++ /dev/null
@@ -1,248 +0,0 @@
-#!/usr/bin/python2.7
-
-# 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.
-
-#
-# Generate a CTS test XML file from a text file containing every single class#method per line
-#
-# For example, given an input file:
-#
-#          foo.txt:
-#                com.android.ClassName#methodNameA
-#                com.android.ClassName#methodNameB
-#
-# Will generate the output file:
-#
-#          TestPackage.xml:
-#                <TestPackage>
-#                  <TestSuite name="com">
-#                    <TestSuite name="android">
-#                      <TestCase name="ClassName">
-#                        <Test name="methodNameA" />
-#                        <Test name="methodNameB" />
-#                      </TestCase>
-#                    </TestSuite>
-#                  </TestSuite>
-#                </TestPackage>
-#
-
-import argparse
-import sys
-
-INDENTATION_INCREASE=2
-
-class BaseNode(object):
-    def __init__(self, name=None):
-        self._children = []
-        self._name = name
-        self._properties = []
-
-    def _get_children(self):
-        return self._children
-
-    def _set_children(self, value):
-        self._children = value
-
-    children = property(_get_children, _set_children, doc="Get/set list of children BaseNode")
-
-    def append_child(self, child):
-        self._children.append(child)
-
-    def has_children(self):
-        return not not self._children
-
-    def _get_name(self):
-        return self._name
-
-    def _set_name(self, value):
-        self._name = value
-
-    name = property(_get_name, _set_name, doc="Get/set the name property of the current XML node")
-
-    def _get_type_name(self):
-        return type(self).__name__
-
-    type_name = property(_get_type_name, doc="Get the name of the current XML node")
-
-    def _set_properties(self, value):
-        self._properties = value
-
-    def _get_properties(self):
-        return self._properties
-
-    properties = property(_get_properties, _set_properties, doc="Get/set additional XML properties such as appPackageName (as a dict)")
-
-    def write_xml(self, out, indent=0):
-        out.write(' ' * indent)
-        out.write('<' + self.type_name)
-
-        if self.name is not None:
-            out.write(' name="')
-            out.write(self.name)
-            out.write('"')
-
-        if self.properties:
-            for key, value in self.properties.iteritems():
-                out.write(' ' + key + '="' + value + '"')
-
-        if not self.has_children():
-            out.write(' />')
-            out.write('\n')
-            return
-
-        out.write('>\n')
-
-        #TODO: print all the properties
-
-        for child in self.children:
-            child.write_xml(out, indent + INDENTATION_INCREASE)
-
-        out.write(' ' * indent)
-        out.write('</' + self.type_name + '>')
-        out.write('\n')
-
-class _SuiteContainer(BaseNode):
-    def get_or_create_suite(self, package_list):
-        debug_print("get_or_create_suite, package_list = " + str(package_list))
-        debug_print("name = " + self.name)
-        # If we are empty, then we just reached the TestSuite which we actually wanted. Return.
-        if not package_list:
-            return self
-
-        current_package = package_list[0]
-        rest_of_packages = package_list[1:]
-
-        # If a suite already exists for the requested package, then have it look/create recursively.
-        for child in self.children:
-            if child.name == current_package:
-                return child.get_or_create_suite(rest_of_packages)
-
-        # No suite exists yet, create it recursively
-        new_suite = TestSuite(name=current_package)
-        self.append_child(new_suite)
-        return new_suite.get_or_create_suite(rest_of_packages)
-
-class TestPackage(_SuiteContainer):
-    def add_class_and_method(self, fq_class_name, method):
-        debug_print("add_class_and_method, fq_class_name=" + fq_class_name + ", method=" + method)
-        package_list = fq_class_name.split(".")[:-1] # a.b.c -> ['a', 'b']
-        just_class_name = fq_class_name.split(".")[-1] # a.b.c -> 'c'
-
-        test_suite = self.get_or_create_suite(package_list)
-
-        if test_suite == self:
-            raise Exception("The suite cannot be the package")
-
-        return test_suite.add_class_and_method(just_class_name, method)
-
-class TestSuite(_SuiteContainer):
-    def add_class_and_method(self, just_class_name, method_name):
-        test_case = self.get_or_create_test_case(just_class_name)
-        return test_case.add_method(method_name)
-
-    def get_or_create_test_case(self, just_class_name):
-        for child in self.children:
-            if child.name == just_class_name:
-                return child
-
-        new_test_case = TestCase(name=just_class_name)
-        self.append_child(new_test_case)
-        return new_test_case
-
-class TestCase(BaseNode):
-    def add_method(self, method_name):
-        tst = Test(name=method_name)
-        self.append_child(tst)
-        return tst
-
-class Test(BaseNode):
-    def __init__(self, name):
-        super(Test, self).__init__(name)
-        self._children = None
-
-def debug_print(x):
-    #print x
-    pass
-
-def build_xml_test_package(input, name, xml_properties):
-    root = TestPackage(name=name)
-
-    for line in input:
-        class_and_method_name = line.split('#')
-        fq_class_name = class_and_method_name[0].strip()
-        method_name = class_and_method_name[1].strip()
-
-        root.add_class_and_method(fq_class_name, method_name)
-
-    root.properties = xml_properties
-    return root
-
-def write_xml(out, test_package):
-    out.write('<?xml version="1.0" encoding="UTF-8"?>\n')
-    test_package.write_xml(out)
-
-def main():
-    parser = argparse.ArgumentParser(description='Process a test methods list file to generate CTS test xml.')
-
-    # Named required
-    parser.add_argument('--cts-name', help="name (e.g. CtsJdwp)", required=True)
-    parser.add_argument('--app-package-name', help="appPackageName (e.g. android.jdwp)", required=True)
-    parser.add_argument('--jar-path', help="jarPath (e.g. CtsJdwp.jar)", required=True)
-
-    # Named optionals
-    parser.add_argument('--test-type', help="testType (default testNGDeviceTest)",
-                        default="testNGDeviceTest")
-    parser.add_argument('--runtime-args', help="runtimeArgs (e.g. -XXlib:libart.so)")
-    parser.add_argument('--version', help="version (default 1.0)", default="1.0")
-
-    # Positional optionals
-    parser.add_argument('input-filename', nargs='?',
-                               help='name of the cts test file (stdin by default)')
-    parser.add_argument('output-filename', nargs='?',
-                               help='name of the cts output file (stdout by default)')
-
-    # Map named arguments into the xml <TestPackage> property key name
-    argv_to_xml = {
-            'app_package_name' : 'appPackageName',
-            'jar_path' : 'jarPath',
-            'test_type' : 'testType',
-            'runtime_args' : 'runtimeArgs',
-            'version' : 'version'
-    }
-
-    args = parser.parse_args()
-    argv = vars(args) # convert Namespace to Dict
-
-    xml_properties = {}
-    for key, value in argv_to_xml.iteritems():
-        if argv.get(key):
-            xml_properties[value] = argv[key]
-
-    debug_print(argv['input-filename'])
-    debug_print(argv['output-filename'])
-
-    name_in = argv['input-filename']
-    name_out = argv['output-filename']
-
-    file_in = name_in and open(name_in, "r") or sys.stdin
-    file_out = name_out and open(name_out, "w+") or sys.stdout
-
-    # read all the input
-    test_package = build_xml_test_package(file_in, args.cts_name, xml_properties)
-    # write all the output
-    write_xml(file_out, test_package)
-
-if __name__ == "__main__":
-    main()
diff --git a/tools/testng/src/com/android/cts/testng/SingleTestNGTestRunListener.java b/tools/testng/src/com/android/cts/testng/SingleTestNGTestRunListener.java
deleted file mode 100644
index 2509366..0000000
--- a/tools/testng/src/com/android/cts/testng/SingleTestNGTestRunListener.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.testng;
-
-import java.util.Arrays;
-
-public class SingleTestNGTestRunListener implements org.testng.ITestListener {
-    private static class Prefixes {
-        @SuppressWarnings("unused")
-        private static final String INFORMATIONAL_MARKER =  "[----------]";
-        private static final String START_TEST_MARKER =     "[ RUN      ]";
-        private static final String OK_TEST_MARKER =        "[       OK ]";
-        private static final String ERROR_TEST_RUN_MARKER = "[    ERROR ]";
-        private static final String SKIPPED_TEST_MARKER =   "[     SKIP ]";
-        private static final String TEST_RUN_MARKER =       "[==========]";
-    }
-
-    @Override
-    public void onFinish(org.testng.ITestContext context) {
-        System.out.println(String.format("%s", Prefixes.TEST_RUN_MARKER));
-    }
-
-    @Override
-    public void onStart(org.testng.ITestContext context) {
-        System.out.println(String.format("%s", Prefixes.INFORMATIONAL_MARKER));
-    }
-
-    @Override
-    public void onTestFailedButWithinSuccessPercentage(org.testng.ITestResult result) {
-        onTestFailure(result);
-    }
-
-    @Override
-    public void onTestFailure(org.testng.ITestResult result) {
-        // All failures are coalesced into one '[ FAILED ]' message at the end
-        // This is because a single test method can run multiple times with different parameters.
-        // Since we only test a single method, it's safe to combine all failures into one
-        // failure at the end.
-        //
-        // The big pass/fail is printed from SingleTestNGTestRunner, not from the listener.
-        System.out.println(String.format("%s %s ::: %s", Prefixes.ERROR_TEST_RUN_MARKER,
-              getId(result), stringify(result.getThrowable())));
-    }
-
-    @Override
-    public void onTestSkipped(org.testng.ITestResult result) {
-        System.out.println(String.format("%s %s", Prefixes.SKIPPED_TEST_MARKER,
-              getId(result)));
-    }
-
-    @Override
-    public void onTestStart(org.testng.ITestResult result) {
-        System.out.println(String.format("%s %s", Prefixes.START_TEST_MARKER,
-              getId(result)));
-    }
-
-    @Override
-    public void onTestSuccess(org.testng.ITestResult result) {
-        System.out.println(String.format("%s", Prefixes.OK_TEST_MARKER));
-    }
-
-    private String getId(org.testng.ITestResult test) {
-        // TestNG is quite complicated since tests can have arbitrary parameters.
-        // Use its code to stringify a result name instead of doing it ourselves.
-
-        org.testng.remote.strprotocol.TestResultMessage msg =
-                new org.testng.remote.strprotocol.TestResultMessage(
-                    null, /*suite name*/
-                    null, /*test name -- display the test method name instead */
-                    test);
-
-        String className = test.getTestClass().getName();
-        //String name = test.getMethod().getMethodName();
-        return String.format("%s#%s", className, msg.toDisplayString());
-
-    }
-
-    private String stringify(Throwable error) {
-        return Arrays.toString(error.getStackTrace()).replaceAll("\n", " ");
-    }
-}
diff --git a/tools/testng/src/com/android/cts/testng/SingleTestNGTestRunner.java b/tools/testng/src/com/android/cts/testng/SingleTestNGTestRunner.java
deleted file mode 100644
index c9f31af..0000000
--- a/tools/testng/src/com/android/cts/testng/SingleTestNGTestRunner.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.testng;
-
-import org.testng.TestNG;
-import org.testng.xml.XmlClass;
-import org.testng.xml.XmlInclude;
-import org.testng.xml.XmlSuite;
-import org.testng.xml.XmlTest;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Test runner to run a single TestNG test. It will output either [PASSED] or [FAILED] at the end.
- */
-public class SingleTestNGTestRunner {
-    private static String mUsage = "Usage: java -cp <classpath> SingleTestNGTestRunner" +
-            " class#testMethod";
-    private static final String PASSED_TEST_MARKER = "[ PASSED ]";
-    private static final String FAILED_TEST_MARKER = "[ FAILED ]";
-
-    public static void main(String... args) {
-        if (args.length != 1) {
-            throw new IllegalArgumentException(mUsage);
-        }
-        String[] classAndMethod = args[0].split("#");
-        if (classAndMethod.length != 2) {
-            throw new IllegalArgumentException(mUsage);
-        }
-
-        TestNG testng = createTestNG(classAndMethod[0], classAndMethod[1]);
-        testng.run();
-        String status = (!testng.hasFailure()) ? PASSED_TEST_MARKER : FAILED_TEST_MARKER;
-        System.out.println(String.format("%s %s.%s", status,
-                classAndMethod[0], classAndMethod[1]));
-    }
-
-    private static org.testng.TestNG createTestNG(String klass, String method) {
-        org.testng.TestNG testng = new org.testng.TestNG();
-        testng.setUseDefaultListeners(false);  // Don't create the testng-specific HTML/XML reports.
-        testng.addListener(new SingleTestNGTestRunListener());
-
-        /* Construct the following equivalent XML configuration:
-         *
-         * <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
-         * <suite>
-         *   <test>
-         *     <classes>
-         *       <class name="$klass">
-         *         <include name="$method" />
-         *       </class>
-         *     </classes>
-         *   </test>
-         * </suite>
-         *
-         * This will ensure that only a single klass/method is being run by testng.
-         * (It can still be run multiple times due to @DataProvider, with different parameters
-         * each time)
-         */
-        List<XmlSuite> suites = new ArrayList<>();
-        XmlSuite the_suite = new XmlSuite();
-        XmlTest the_test = new XmlTest(the_suite);
-        XmlClass the_class = new XmlClass(klass);
-        XmlInclude the_include = new XmlInclude(method);
-
-        the_class.getIncludedMethods().add(the_include);
-        the_test.getXmlClasses().add(the_class);
-        suites.add(the_suite);
-        testng.setXmlSuites(suites);
-
-        return testng;
-    }
-}
diff --git a/tools/testng/test-script b/tools/testng/test-script
deleted file mode 100755
index 9bfdf82..0000000
--- a/tools/testng/test-script
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/bash
-
-adb push $ANDROID_PRODUCT_OUT/system/framework/cts-testng.jar /data/local/tmp
-adb shell "cd /data/local/tmp && dalvikvm -cp cts-testng.jar:ctslibcore/CtsLibcoreOjTestCases.apk com.android.cts.testng.SingleTestNGTestRunner org.openjdk.tests.java.util.stream.GroupByOpTest#testOps"
diff --git a/tools/utils/Android.bp b/tools/utils/Android.bp
new file mode 100644
index 0000000..406ad01
--- /dev/null
+++ b/tools/utils/Android.bp
@@ -0,0 +1,36 @@
+// Copyright (C) 2008 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// descGen java library
+// ============================================================
+java_library_host {
+    name: "descGen",
+
+    srcs: [
+        "CollectAllTests.java",
+        "DescriptionGenerator.java",
+        "VogarUtils.java",
+    ],
+
+    use_tools_jar: true,
+
+    libs: [
+        "junit",
+        "tradefed",
+    ],
+    static_libs: [
+        "compatibility-host-util",
+        "vogarexpect",
+    ],
+}
diff --git a/tools/utils/Android.mk b/tools/utils/Android.mk
deleted file mode 100644
index 6b01e57..0000000
--- a/tools/utils/Android.mk
+++ /dev/null
@@ -1,30 +0,0 @@
-# Copyright (C) 2008 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#      http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-# descGen java library
-# ============================================================
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := descGen
-
-LOCAL_SRC_FILES := CollectAllTests.java DescriptionGenerator.java VogarUtils.java
-
-LOCAL_CLASSPATH := $(HOST_JDK_TOOLS_JAR)
-
-LOCAL_JAVA_LIBRARIES := junit-host tradefed
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-host-util vogarexpectlib
-
-include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/tools/vm-tests-tf/Android.bp b/tools/vm-tests-tf/Android.bp
index c2b3d92..f48f9e6 100644
--- a/tools/vm-tests-tf/Android.bp
+++ b/tools/vm-tests-tf/Android.bp
@@ -25,16 +25,16 @@
     name: "vmtests-buildutil",
     static_libs: [ "cts-vmtests-dot", "junit" ],
     srcs: [
-        "src/util/build/BuildCTSHostSources.java",
-        "src/util/build/BuildCTSMainsSources.java",
-        "src/util/build/BuildUtilBase.java",
-        "src/util/build/FileUtil.java",
-        "src/util/build/JUnitTestCollector.java",
+        "build/src/util/build/BuildCTSHostSources.java",
+        "build/src/util/build/BuildCTSMainsSources.java",
+        "build/src/util/build/BuildUtilBase.java",
+        "build/src/util/build/FileUtil.java",
+        "build/src/util/build/JUnitTestCollector.java",
     ],
     wrapper: "etc/vmtests-buildutil.sh",
 }
 
-genrule {
+java_genrule_host {
     name: "vmtests_generated_host_test_sources",
     tools: [
         "vmtests-buildutil",
@@ -45,7 +45,17 @@
     out: ["vmtests.host.generated.srcjar"],
 }
 
-genrule {
+java_library_host {
+    name: "host-cts-vmtests",
+    libs: [
+        "junit",
+        "tradefed",
+    ],
+    srcs : [ ":vmtests_generated_host_test_sources" ],
+    installable: false,
+}
+
+java_genrule_host {
     name: "vmtests-dfh-dex-generated",
     tools: [
         "cfassembler",
@@ -57,7 +67,7 @@
     out: ["vmtests_dfh_dex_generated.jar"],
 }
 
-genrule {
+java_genrule_host {
     name: "vmtests-dasm-dex-generated",
     tools: [
         "dasm",
@@ -69,7 +79,7 @@
     out: ["vmtests_dasm_dex_generated.jar"],
 }
 
-genrule {
+java_genrule {
     name: "vmtests_generated_mains_test_sources",
     tools: [
         "vmtests-buildutil",
@@ -94,6 +104,7 @@
 java_library_host {
     name: "vmtests-generated-resources",
     static_libs: [
+        "host-cts-vmtests",
         "vmtests-dfh-dex-generated",
         "vmtests-dasm-dex-generated",
     ],
diff --git a/tools/vm-tests-tf/Android.mk b/tools/vm-tests-tf/Android.mk
index 539582f..589737e 100644
--- a/tools/vm-tests-tf/Android.mk
+++ b/tools/vm-tests-tf/Android.mk
@@ -19,7 +19,7 @@
 include $(CLEAR_VARS)
 
 # custom variables used to generate test description. do not touch!
-LOCAL_SRC_FILES := $(call all-java-files-under, src/dot)
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_MODULE := cts-tf-dalvik-lib
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
@@ -37,13 +37,13 @@
 LOCAL_TEST_TYPE := vmHostTest
 LOCAL_JAR_PATH := android.core.vm-tests-tf.jar
 
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
+LOCAL_SRC_FILES := $(call all-java-files-under, src build/src)
 
 LOCAL_MODULE := cts-tf-dalvik-buildutil
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 LOCAL_MODULE_TAGS := optional
 
-LOCAL_JAVA_LIBRARIES := dx dasm junit-host jsr305lib d8 smali
+LOCAL_JAVA_LIBRARIES := dx dasm junit jsr305 d8 smali
 
 LOCAL_CLASSPATH := $(HOST_JDK_TOOLS_JAR)
 
@@ -72,7 +72,7 @@
 vmteststf_dep_jars := \
     $(HOST_JDK_TOOLS_JAR) \
     $(cts-tf-dalvik-lib.jar) \
-    $(addprefix $(HOST_OUT_JAVA_LIBRARIES)/, cts-tf-dalvik-buildutil.jar dx.jar junit-host.jar d8.jar smali.jar) \
+    $(addprefix $(HOST_OUT_JAVA_LIBRARIES)/, cts-tf-dalvik-buildutil.jar dx.jar junit.jar d8.jar smali.jar) \
     $(call intermediates-dir-for,JAVA_LIBRARIES,cts-vmtests-dot,HOST,COMMON)/classes.jar
 
 vmtests_generated_resources_jar := \
@@ -84,11 +84,11 @@
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_CLASSES := $(call intermediates-dir-for,JAVA_LIBRARIES,cts-tf-dalvik-buildutil,HOST)/classes
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES := $(intermediates)/tests
 $(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_DEXCORE_JAR := $(intermediates)/tests/dot/junit/dexcore.jar
-$(LOCAL_BUILT_MODULE): PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES := $(intermediates)/hostjunit_files
 $(LOCAL_BUILT_MODULE): PRIVATE_CLASS_PATH := $(call normalize-path-list, $(vmteststf_dep_jars))
 oj_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,core-oj,,COMMON)/classes.jar
 libart_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,core-libart,,COMMON)/classes.jar
-$(LOCAL_BUILT_MODULE): PRIVATE_DALVIK_SUITE_CLASSPATH := $(oj_jar):$(libart_jar):$(cts-tf-dalvik-lib.jar):$(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar:
+simple_jar := $(call intermediates-dir-for,JAVA_LIBRARIES,core-simple,,COMMON)/classes.jar
+$(LOCAL_BUILT_MODULE): PRIVATE_DALVIK_SUITE_CLASSPATH := $(oj_jar):$(libart_jar):$(simple_jar):$(cts-tf-dalvik-lib.jar):$(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar:
 $(LOCAL_BUILT_MODULE): PRIVATE_VMTESTS_GENERATED_RESOURCES := $(vmtests_generated_resources_jar)
 $(LOCAL_BUILT_MODULE): PRIVATE_VMTESTS_MAINS_GENERATED := $(vmtests_mains_generated_jar)
 $(LOCAL_BUILT_MODULE) : $(vmteststf_dep_jars) $(HOST_OUT_JAVA_LIBRARIES)/tradefed.jar $(DX) $(vmtests_generated_resources_jar) $(vmtests_mains_generated_jar)
@@ -98,8 +98,7 @@
 	@echo "Write generated Main_*.java"
 	$(hide) $(JAVA) \
 	    -cp $(PRIVATE_CLASS_PATH) util.build.BuildDalvikSuite $(PRIVATE_SRC_FOLDER) $(PRIVATE_INTERMEDIATES) \
-		$(PRIVATE_DALVIK_SUITE_CLASSPATH) \
-		$(PRIVATE_INTERMEDIATES_CLASSES) $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)
+		$(PRIVATE_INTERMEDIATES_CLASSES)
 	@echo "Generate $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)"
 	$(hide) $(JAR) -cf $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar \
 		$(addprefix -C $(PRIVATE_INTERMEDIATES_CLASSES) , dot/junit/DxUtil.class dot/junit/DxAbstractMain.class dot/junit/AssertionFailedException.class)
@@ -108,7 +107,6 @@
 		$(if $(NO_OPTIMIZE_DX), --debug) $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)-class.jar && rm -f $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).jar
 	$(hide) cd $(PRIVATE_INTERMEDIATES_DEXCORE_JAR).tmp && zip -q -r $(abspath $(PRIVATE_INTERMEDIATES_DEXCORE_JAR)) .
 	$(hide) cp $(PRIVATE_VMTESTS_GENERATED_RESOURCES) $@
-	$(hide) cd $(PRIVATE_INTERMEDIATES_HOSTJUNIT_FILES)/classes && zip -q -r ../../$(notdir $@) .
 	$(hide) cp $(PRIVATE_VMTESTS_MAINS_GENERATED) $(dir $@)/tests/mains.jar
 	$(hide) cd $(dir $@) && zip -q -r $(notdir $@) tests
 oj_jar :=
diff --git a/tools/vm-tests-tf/AndroidTest.xml b/tools/vm-tests-tf/AndroidTest.xml
index fc0f8af..aaafbcf 100644
--- a/tools/vm-tests-tf/AndroidTest.xml
+++ b/tools/vm-tests-tf/AndroidTest.xml
@@ -16,7 +16,6 @@
 <configuration description="Config for CTS VM test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="art" />
-    <option name="not-strict-shardable" value= "true" />
     <target_preparer class="android.core.vm.targetprep.VmTestPreparer" />
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="android.core.vm-tests-tf.jar" />
diff --git a/tools/vm-tests-tf/TEST_MAPPING b/tools/vm-tests-tf/TEST_MAPPING
new file mode 100644
index 0000000..a566107
--- /dev/null
+++ b/tools/vm-tests-tf/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "vm-tests-tf"
+    }
+  ]
+}
diff --git a/tools/vm-tests-tf/src/util/build/BuildCTSHostSources.java b/tools/vm-tests-tf/build/src/util/build/BuildCTSHostSources.java
similarity index 99%
rename from tools/vm-tests-tf/src/util/build/BuildCTSHostSources.java
rename to tools/vm-tests-tf/build/src/util/build/BuildCTSHostSources.java
index 3038394..bcdcd49 100644
--- a/tools/vm-tests-tf/src/util/build/BuildCTSHostSources.java
+++ b/tools/vm-tests-tf/build/src/util/build/BuildCTSHostSources.java
@@ -178,7 +178,7 @@
     }
 
     private static String getShellExecJavaLine(String classpath, String mainclass) {
-      String cmd = String.format("ANDROID_DATA=%s dalvikvm|#ABI#| -Xmx512M -Xss32K -Xnodex2oat " +
+      String cmd = String.format("ANDROID_DATA=%s dalvikvm|#ABI#| -Xmx512M -Xss32K " +
               "-Djava.io.tmpdir=%s -classpath %s %s", TARGET_JAR_ROOT_PATH, TARGET_JAR_ROOT_PATH,
               classpath, mainclass);
       StringBuilder code = new StringBuilder();
diff --git a/tools/vm-tests-tf/src/util/build/BuildCTSMainsSources.java b/tools/vm-tests-tf/build/src/util/build/BuildCTSMainsSources.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/BuildCTSMainsSources.java
rename to tools/vm-tests-tf/build/src/util/build/BuildCTSMainsSources.java
diff --git a/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java b/tools/vm-tests-tf/build/src/util/build/BuildDalvikSuite.java
similarity index 66%
rename from tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
rename to tools/vm-tests-tf/build/src/util/build/BuildDalvikSuite.java
index 7e13cc5..0b069b5 100644
--- a/tools/vm-tests-tf/src/util/build/BuildDalvikSuite.java
+++ b/tools/vm-tests-tf/build/src/util/build/BuildDalvikSuite.java
@@ -39,15 +39,8 @@
 
     // the folder for the generated junit-files for the cts host (which in turn
     // execute the real vm tests using adb push/shell etc)
-    private static String HOSTJUNIT_SRC_OUTPUT_FOLDER = "";
-    private static String OUTPUT_FOLDER = "";
-    private static String COMPILED_CLASSES_FOLDER = "";
-
-    private static String HOSTJUNIT_CLASSES_OUTPUT_FOLDER = "";
-
-    private static String CLASS_PATH = "";
-
-    private static final String TARGET_JAR_ROOT_PATH = "/data/local/tmp/vm-tests";
+    private String OUTPUT_FOLDER = "";
+    private String COMPILED_CLASSES_FOLDER = "";
 
     private String JAVASRC_FOLDER;
 
@@ -72,15 +65,10 @@
     }
 
     private boolean parseArgs(String[] args) {
-      if (args.length == 5) {
+      if (args.length == 3) {
           JAVASRC_FOLDER = args[0];
           OUTPUT_FOLDER = args[1];
-          CLASS_PATH = args[2];
-
-          COMPILED_CLASSES_FOLDER = args[3];
-
-          HOSTJUNIT_SRC_OUTPUT_FOLDER = args[4];
-          HOSTJUNIT_CLASSES_OUTPUT_FOLDER = HOSTJUNIT_SRC_OUTPUT_FOLDER + "/classes";
+          COMPILED_CLASSES_FOLDER = args[2];
           return true;
       } else {
           return false;
@@ -89,135 +77,7 @@
 
     private static void printUsage() {
         System.out.println("usage: java-src-folder output-folder classpath " +
-                           "generated-main-files compiled_output generated-main-files " +
-                           "[restrict-to-opcode]");
-    }
-
-    private SourceBuildStep hostJunitBuildStep;
-
-    private static class HostState {
-        private String fileName;
-        private StringBuilder fileData;
-
-        public HostState(String fileName) {
-            this.fileName = fileName;
-            fileData = new StringBuilder();
-        }
-
-        public void append(String s) {
-            fileData.append(s);
-        }
-
-        private void addCTSHostMethod(String pName, String method,
-                Collection<String> dependentTestClassNames) {
-            fileData.append("public void " + method + "() throws Exception {\n");
-            final String targetCoreJarPath = String.format("%s/dot/junit/dexcore.jar",
-                    TARGET_JAR_ROOT_PATH);
-
-            String mainsJar = String.format("%s/%s", TARGET_JAR_ROOT_PATH, TARGET_MAIN_FILE);
-
-            String cp = String.format("%s:%s", targetCoreJarPath, mainsJar);
-            for (String depFqcn : dependentTestClassNames) {
-                String sourceName = depFqcn.replaceAll("\\.", "/") + ".jar";
-                String targetName= String.format("%s/%s", TARGET_JAR_ROOT_PATH,
-                        sourceName);
-                cp += ":" + targetName;
-                // dot.junit.opcodes.invoke_interface_range.ITest
-                // -> dot/junit/opcodes/invoke_interface_range/ITest.jar
-            }
-
-            //"dot.junit.opcodes.add_double_2addr.Main_testN2";
-            String mainclass = pName + ".Main_" + method;
-            fileData.append(getShellExecJavaLine(cp, mainclass));
-            fileData.append("\n}\n\n");
-        }
-
-        public void end() {
-            fileData.append("\n}\n");
-        }
-
-        public File getFileToWrite() {
-            return new File(fileName);
-        }
-        public String getBuildStep() {
-            return new File(fileName).getAbsolutePath();
-        }
-        public String getData() {
-            return fileData.toString();
-        }
-    }
-
-    private void flushHostState(HostState state) {
-        state.end();
-
-        File toWrite = state.getFileToWrite();
-        writeToFileMkdir(toWrite, state.getData());
-
-        hostJunitBuildStep.addSourceFile(state.getBuildStep());
-    }
-
-    private HostState openCTSHostFileFor(String pName, String classOnlyName) {
-        String sourceName = classOnlyName;
-
-        String modPackage = pName;
-        {
-            // Given a class name of "Test_zzz" and a package of "xxx.yyy.zzz," strip
-            // "zzz" from the package to reduce duplication (and dashboard clutter).
-            int lastDot = modPackage.lastIndexOf('.');
-            if (lastDot > 0) {
-                String lastPackageComponent = modPackage.substring(lastDot + 1);
-                if (classOnlyName.equals("Test_" + lastPackageComponent)) {
-                    // Drop the duplication.
-                    modPackage = modPackage.substring(0, lastDot);
-                }
-            }
-        }
-
-        String fileName = HOSTJUNIT_SRC_OUTPUT_FOLDER + "/" + modPackage.replaceAll("\\.", "/")
-                + "/" + sourceName + ".java";
-
-        HostState newState = new HostState(fileName);
-
-        newState.append(getWarningMessage());
-        newState.append("package " + modPackage + ";\n");
-        newState.append("import java.io.IOException;\n" +
-                "import java.util.concurrent.TimeUnit;\n\n" +
-                "import com.android.tradefed.device.CollectingOutputReceiver;\n" +
-                "import com.android.tradefed.testtype.IAbi;\n" +
-                "import com.android.tradefed.testtype.IAbiReceiver;\n" +
-                "import com.android.tradefed.testtype.DeviceTestCase;\n" +
-                "import com.android.tradefed.util.AbiFormatter;\n" +
-                "\n");
-        newState.append("public class " + sourceName + " extends DeviceTestCase implements " +
-                "IAbiReceiver {\n");
-
-        newState.append("\n" +
-                "protected IAbi mAbi;\n" +
-                "@Override\n" +
-                "public void setAbi(IAbi abi) {\n" +
-                "    mAbi = abi;\n" +
-                "}\n\n");
-
-        return newState;
-    }
-
-    private static String getShellExecJavaLine(String classpath, String mainclass) {
-      String cmd = String.format("ANDROID_DATA=%s dalvikvm|#ABI#| -Xmx512M -Xss32K -Xnodex2oat " +
-              "-Djava.io.tmpdir=%s -classpath %s %s", TARGET_JAR_ROOT_PATH, TARGET_JAR_ROOT_PATH,
-              classpath, mainclass);
-      StringBuilder code = new StringBuilder();
-      code.append("    String cmd = AbiFormatter.formatCmdForAbi(\"")
-          .append(cmd)
-          .append("\", mAbi.getBitness());\n")
-          .append("    CollectingOutputReceiver receiver = new CollectingOutputReceiver();\n")
-          .append("    getDevice().executeShellCommand(cmd, receiver, 6, TimeUnit.MINUTES, 1);\n")
-          .append("    // A sucessful adb shell command returns an empty string.\n")
-          .append("    assertEquals(cmd, \"\", receiver.getOutput());");
-      return code.toString();
-    }
-
-    private String getWarningMessage() {
-        return "//Autogenerated code by " + this.getClass().getName() + "; do not edit.\n";
+                           "generated-main-files compiled_output");
     }
 
     class MyTestHandler implements TestHandler {
@@ -230,8 +90,6 @@
             String pName = fqcn.substring(0, lastDotPos);
             String classOnlyName = fqcn.substring(lastDotPos + 1);
 
-            HostState hostState = openCTSHostFileFor(pName, classOnlyName);
-
             Collections.sort(methods, new Comparator<String>() {
                 @Override
                 public int compare(String s1, String s2) {
@@ -260,8 +118,6 @@
                 List<String> dependentTestClassNames = parseTestClassName(pName,
                         classOnlyName, methodContent);
 
-                hostState.addCTSHostMethod(pName, method, dependentTestClassNames);
-
                 if (dependentTestClassNames.isEmpty()) {
                     continue;
                 }
@@ -347,16 +203,11 @@
                 datafileContent += line + "\n";
                 generateBuildStepFor(dependentTestClassNames, targets);
             }
-
-            flushHostState(hostState);
         }
     }
 
     @Override
     protected void handleTests(JUnitTestCollector tests, TestHandler ignored) {
-        hostJunitBuildStep = new JavacBuildStep(
-                HOSTJUNIT_CLASSES_OUTPUT_FOLDER, CLASS_PATH);
-
         MyTestHandler handler = new MyTestHandler();
         super.handleTests(tests, handler);
 
@@ -364,11 +215,6 @@
         scriptDataDir.mkdirs();
         writeToFile(new File(scriptDataDir, "scriptdata"), handler.datafileContent);
 
-        if (!hostJunitBuildStep.build()) {
-            System.out.println("main javac cts-host-hostjunit-classes build step failed");
-            System.exit(1);
-        }
-
         for (BuildStep buildStep : handler.targets) {
             if (!buildStep.build()) {
                 System.out.println("building failed. buildStep: " +
diff --git a/tools/vm-tests-tf/src/util/build/BuildStep.java b/tools/vm-tests-tf/build/src/util/build/BuildStep.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/BuildStep.java
rename to tools/vm-tests-tf/build/src/util/build/BuildStep.java
diff --git a/tools/vm-tests-tf/src/util/build/BuildUtilBase.java b/tools/vm-tests-tf/build/src/util/build/BuildUtilBase.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/BuildUtilBase.java
rename to tools/vm-tests-tf/build/src/util/build/BuildUtilBase.java
diff --git a/tools/vm-tests-tf/src/util/build/D8BuildStep.java b/tools/vm-tests-tf/build/src/util/build/D8BuildStep.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/D8BuildStep.java
rename to tools/vm-tests-tf/build/src/util/build/D8BuildStep.java
diff --git a/tools/vm-tests-tf/src/util/build/FileUtil.java b/tools/vm-tests-tf/build/src/util/build/FileUtil.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/FileUtil.java
rename to tools/vm-tests-tf/build/src/util/build/FileUtil.java
diff --git a/tools/vm-tests-tf/src/util/build/JUnitTestCollector.java b/tools/vm-tests-tf/build/src/util/build/JUnitTestCollector.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/JUnitTestCollector.java
rename to tools/vm-tests-tf/build/src/util/build/JUnitTestCollector.java
diff --git a/tools/vm-tests-tf/src/util/build/JarBuildStep.java b/tools/vm-tests-tf/build/src/util/build/JarBuildStep.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/JarBuildStep.java
rename to tools/vm-tests-tf/build/src/util/build/JarBuildStep.java
diff --git a/tools/vm-tests-tf/src/util/build/JavacBuildStep.java b/tools/vm-tests-tf/build/src/util/build/JavacBuildStep.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/JavacBuildStep.java
rename to tools/vm-tests-tf/build/src/util/build/JavacBuildStep.java
diff --git a/tools/vm-tests-tf/src/util/build/SmaliBuildStep.java b/tools/vm-tests-tf/build/src/util/build/SmaliBuildStep.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/SmaliBuildStep.java
rename to tools/vm-tests-tf/build/src/util/build/SmaliBuildStep.java
diff --git a/tools/vm-tests-tf/src/util/build/SourceBuildStep.java b/tools/vm-tests-tf/build/src/util/build/SourceBuildStep.java
similarity index 100%
rename from tools/vm-tests-tf/src/util/build/SourceBuildStep.java
rename to tools/vm-tests-tf/build/src/util/build/SourceBuildStep.java
diff --git a/tools/vm-tests-tf/targetprep/src/android/core/vm/targetprep/VmTestPreparer.java b/tools/vm-tests-tf/targetprep/src/android/core/vm/targetprep/VmTestPreparer.java
index 1513592..6a17e91 100644
--- a/tools/vm-tests-tf/targetprep/src/android/core/vm/targetprep/VmTestPreparer.java
+++ b/tools/vm-tests-tf/targetprep/src/android/core/vm/targetprep/VmTestPreparer.java
@@ -25,6 +25,8 @@
 import com.android.tradefed.targetprep.BuildError;
 import com.android.tradefed.targetprep.ITargetCleaner;
 import com.android.tradefed.targetprep.TargetSetupError;
+import com.android.tradefed.util.CommandResult;
+import com.android.tradefed.util.CommandStatus;
 import com.android.tradefed.util.FileUtil;
 
 import java.io.File;
@@ -80,21 +82,28 @@
         // a sigsev thrown by the vm.
         createRemoteDir(device, VM_TEMP_DIR + "/dalvik-cache" );
         try {
-            File tmpDir = new File(System.getProperty("java.io.tmpdir"));
-            File localTmpDir = FileUtil.createTempDir("cts-vm", tmpDir);
             File jarFile = ctsBuild.getTestFile(JAR_FILE);
             if (!jarFile.exists()) {
                 CLog.e("Missing jar file %s", jarFile.getPath());
                 return false;
             }
-            ZipFile zipFile = new ZipFile(jarFile);
-            FileUtil.extractZip(zipFile, localTmpDir);
-            File localTestTmpDir = new File(localTmpDir, "tests");
-            if (!device.pushDir(localTestTmpDir, VM_TEMP_DIR)) {
-                CLog.e("Failed to push vm test files");
+
+            String jarOnDevice = VM_TEMP_DIR + "/" + JAR_FILE;
+            if (!device.pushFile(jarFile, jarOnDevice)) {
+                CLog.e("Failed to push vm test jar");
                 return false;
             }
-            FileUtil.recursiveDelete(localTmpDir);
+
+            // TODO: Only extract tests directory, avoid rm.
+            String cmd = "unzip -d " + VM_TEMP_DIR + " " + jarOnDevice
+                    + " && rm -rf " + VM_TEMP_DIR + "/dot*"
+                    + " && mv " + VM_TEMP_DIR + "/tests/* " + VM_TEMP_DIR + "/"
+                    + " && echo Success";
+            CommandResult result = device.executeShellV2Command(cmd);
+            if (result.getStatus() != CommandStatus.SUCCESS) {
+                CLog.e("Failed to extract and prepare vm tests jar");
+                return false;
+            }
         } catch (IOException e) {
             CLog.e("Failed to extract jar file %s and sync it to device %s.",
                     JAR_FILE, device.getSerialNumber());