Revert "resolve merge conflicts of 2537ffdefc to marshmallow-cts-dev"
am: 48850d1d57  -s ours

Change-Id: Ia0bb87f5a1dde2ad014d2e91bddf1a00b3a9e6dc
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk
index cc36b20..00ba034 100644
--- a/CtsTestCaseList.mk
+++ b/CtsTestCaseList.mk
@@ -106,7 +106,6 @@
     CtsMonkeyApp2 \
     CtsPackageInstallerApp \
     CtsPermissionApp \
-    CtsPreconditionsApp \
     CtsSimpleApp \
     CtsSimplePreMApp \
     CtsSomeAccessibilityServices \
diff --git a/apps/CameraITS/tests/scene1/test_black_white.py b/apps/CameraITS/tests/scene1/test_black_white.py
index 56bc5ec..68d7de6 100644
--- a/apps/CameraITS/tests/scene1/test_black_white.py
+++ b/apps/CameraITS/tests/scene1/test_black_white.py
@@ -76,9 +76,9 @@
         matplotlib.pyplot.savefig("%s_plot_means.png" % (NAME))
 
         for val in black_means:
-            assert(val < 0.035)
+            assert(val < 0.025)
         for val in white_means:
-            assert(val > 0.965)
+            assert(val > 0.975)
 
 if __name__ == '__main__':
     main()
diff --git a/apps/CameraITS/tests/scene1/test_exposure.py b/apps/CameraITS/tests/scene1/test_exposure.py
index e448f80..dc4a790 100644
--- a/apps/CameraITS/tests/scene1/test_exposure.py
+++ b/apps/CameraITS/tests/scene1/test_exposure.py
@@ -61,9 +61,8 @@
             mults.append(m)
             s_test = round(s*m)
             e_test = s_e_product / s_test
-            print "Testsing s:", s_test, "e:", e_test
-            req = its.objects.manual_capture_request(
-                    s_test, e_test, True, props)
+            print "Testing s:", s_test, "e:", e_test
+            req = its.objects.manual_capture_request(s_test, e_test, True, props)
             cap = cam.do_capture(req)
             s_res = cap["metadata"]["android.sensor.sensitivity"]
             e_res = cap["metadata"]["android.sensor.exposureTime"]
@@ -113,4 +112,3 @@
 
 if __name__ == '__main__':
     main()
-
diff --git a/apps/CtsVerifier/Android.mk b/apps/CtsVerifier/Android.mk
index 18ef8dd..ad78a59 100644
--- a/apps/CtsVerifier/Android.mk
+++ b/apps/CtsVerifier/Android.mk
@@ -41,7 +41,7 @@
 
 LOCAL_PACKAGE_NAME := CtsVerifier
 
-LOCAL_JNI_SHARED_LIBRARIES := libctsverifier_jni libaudioloopback_jni
+LOCAL_JNI_SHARED_LIBRARIES := libctsverifier_jni
 
 LOCAL_PROGUARD_FLAG_FILES := proguard.flags
 
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index a8d2e19..b636820 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -18,7 +18,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.android.cts.verifier"
       android:versionCode="5"
-      android:versionName="6.0_r14">
+      android:versionName="6.0_r201602s">
 
     <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23"/>
 
@@ -380,17 +380,6 @@
             <meta-data android:name="test_required_features"
                     android:value="android.software.device_admin" />
         </activity>
-        <activity android:name=".security.WiFiCACertificateBugTest"
-                android:configChanges="keyboardHidden|orientation|screenSize"
-                android:label="@string/sec_wifi_ca_cert_test">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN"/>
-                <category android:name="android.cts.intent.category.MANUAL_TEST"/>
-            </intent-filter>
-            <meta-data android:name="test_category" android:value="@string/test_category_security"/>
-            <meta-data android:name="test_excluded_features"
-                       android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch"/>
-        </activity>
 
         <activity android:name=".streamquality.StreamingVideoActivity"
                 android:label="@string/streaming_video"
@@ -1153,15 +1142,6 @@
                     android:value="android.software.leanback" />
         </activity>
 
-        <activity android:name=".security.AlarmIntentTest"
-                  android:label="@string/alarmintenttest_title">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.cts.intent.category.MANUAL_TEST" />
-            </intent-filter>
-            <meta-data android:name="test_category" android:value="@string/test_category_security" />
-        </activity>
-
         <activity android:name=".p2p.GoNegRequesterTestListActivity"
                 android:label="@string/p2p_go_neg_requester"
                 android:configChanges="keyboardHidden|orientation|screenSize" />
@@ -1705,7 +1685,6 @@
                     android:value="android.software.live_tv" />
         </activity>
 
-        <!-- Comment out in M due to b/29916035.
         <activity android:name=".tv.TimeShiftTestActivity"
                 android:label="@string/tv_time_shift_test">
             <intent-filter>
@@ -1716,7 +1695,6 @@
             <meta-data android:name="test_required_features"
                     android:value="android.software.live_tv" />
         </activity>
-        -->
 
         <activity android:name=".tv.AppLinkTestActivity"
             android:label="@string/tv_app_link_test"
diff --git a/apps/CtsVerifier/res/layout/activity_alarmintent.xml b/apps/CtsVerifier/res/layout/activity_alarmintent.xml
deleted file mode 100644
index 9b97d2a..0000000
--- a/apps/CtsVerifier/res/layout/activity_alarmintent.xml
+++ /dev/null
@@ -1,150 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<RelativeLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:padding="20dp"
-    tools:context=".AlarmIntentTest">
-    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:scrollbars="vertical">
-        <LinearLayout android:orientation="vertical"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_centerInParent="true">
-            <ImageView
-                android:id="@+id/img1"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentLeft="true"
-                android:layout_alignParentTop="true"
-                android:contentDescription="@string/pass_button_text"
-                android:padding="10dp"
-                android:src="@drawable/fs_indeterminate"/>
-            <TextView
-                android:id="@+id/set_alarm_info"
-                style="@style/InstructionsSmallFont"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_alignParentRight="true"
-                android:layout_alignParentTop="true"
-                android:layout_toRightOf="@+id/img1"
-                android:text="@string/alarmintenttest_set_alarm"/>
-            <Button
-                android:id="@+id/set_alarm"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/set_alarm_info"
-                android:layout_toRightOf="@+id/img1"
-                android:text="@string/set_alarm_btn"/>
-            <ImageView
-                android:id="@+id/img2"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentLeft="true"
-                android:layout_below="@id/set_alarm"
-                android:layout_marginTop="10dp"
-                android:contentDescription="@string/pass_button_text"
-                android:padding="10dp"
-                android:src="@drawable/fs_indeterminate"/>
-            <TextView
-                android:id="@+id/instructions"
-                style="@style/InstructionsSmallFont"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/set_alarm"
-                android:layout_toRightOf="@+id/img2"
-                android:text="@string/alarmintenttest_instructions"/>
-            <TextView
-                android:id="@+id/initialstep"
-                style="@style/InstructionsSmallFont"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/instructions"
-                android:layout_toRightOf="@+id/img2"
-                android:text="@string/alarmintenttest_verify_bug"/>
-            <TextView
-                android:id="@+id/point1"
-                style="@style/InstructionsSmallFont"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/initialstep"
-                android:layout_toRightOf="@+id/img2"
-                android:paddingRight="2dp"
-                android:text="@string/alarmintenttest_point1"/>
-            <TextView
-                android:id="@+id/instruction1"
-                style="@style/InstructionsSmallFont"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_alignParentRight="true"
-                android:layout_below="@+id/initialstep"
-                android:layout_toRightOf="@+id/point1"
-                android:text="@string/alarmintenttest_failcase"/>
-            <TextView
-                android:id="@+id/point2"
-                style="@style/InstructionsSmallFont"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/instruction1"
-                android:layout_toRightOf="@+id/img2"
-                android:paddingRight="2dp"
-                android:text="@string/alarmintenttest_point2"/>
-            <TextView
-                android:id="@+id/instruction2"
-                style="@style/InstructionsSmallFont"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_alignParentRight="true"
-                android:layout_below="@+id/instruction1"
-                android:layout_toRightOf="@+id/point1"
-                android:text="@string/alarmintenttest_passcase"/>
-            <ImageView
-                android:id="@+id/img3"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentLeft="true"
-                android:layout_below="@id/instruction2"
-                android:layout_marginTop="10dp"
-                android:contentDescription="@string/pass_button_text"
-                android:padding="10dp"
-                android:src="@drawable/fs_indeterminate"/>
-            <TextView
-                android:id="@+id/calcel_alaem_info"
-                style="@style/InstructionsSmallFont"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/instruction2"
-                android:layout_toRightOf="@+id/img3"
-                android:text="@string/calcel_alarm_info"/>
-            <Button
-                android:id="@+id/cancel_alarm"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/calcel_alaem_info"
-                android:layout_toRightOf="@+id/img3"
-                android:text="@string/cancel_alarm_btn"/>
-            <include
-                layout="@layout/pass_fail_buttons"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_alignParentBottom="true"/>
-        </LinearLayout>
-    </ScrollView>
-</RelativeLayout>
diff --git a/apps/CtsVerifier/res/layout/ca_certificate_wifi.xml b/apps/CtsVerifier/res/layout/ca_certificate_wifi.xml
deleted file mode 100644
index 9a16e3f..0000000
--- a/apps/CtsVerifier/res/layout/ca_certificate_wifi.xml
+++ /dev/null
@@ -1,173 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<RelativeLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:padding="10dip">
-
-    <ScrollView
-        android:layout_width="match_parent"
-        android:layout_height="match_parent"
-        android:layout_above="@+id/pass_fail_buttons">
-
-        <RelativeLayout
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content">
-
-            <LinearLayout
-                android:id="@+id/layout1"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:orientation="horizontal">
-
-                <ImageView
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_marginTop="10dip"
-                    android:contentDescription="@string/pass_button_text"
-                    android:padding="10dip"
-                    android:src="@drawable/fs_indeterminate"/>
-
-                <TextView
-                    style="@style/InstructionsSmallFont"
-                    android:layout_width="0dp"
-                    android:layout_height="wrap_content"
-                    android:layout_weight="1"
-                    android:text="@string/sec_push_ca_certificate_to_device_text"/>
-            </LinearLayout>
-
-            <Button
-                android:id="@+id/transfer_ca_certificate"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/layout1"
-                android:gravity="center"
-                android:text="@string/cacert_do_something"/>
-
-            <LinearLayout
-                android:id="@+id/layout2"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/transfer_ca_certificate">
-
-                <ImageView
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_marginTop="10dip"
-                    android:contentDescription="@string/pass_button_text"
-                    android:padding="10dip"
-                    android:src="@drawable/fs_indeterminate"/>
-
-                <TextView
-                    style="@style/InstructionsSmallFont"
-                    android:layout_width="match_parent"
-                    android:layout_height="wrap_content"
-                    android:text="@string/sec_launch_wifi_settings"/>
-            </LinearLayout>
-
-            <Button
-                android:id="@+id/gotowifisettings"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/layout2"
-                android:gravity="center"
-                android:text="@string/cacert_do_something"/>
-
-            <LinearLayout
-                android:id="@+id/layout3"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/gotowifisettings">
-
-                <ImageView
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_below="@+id/transfer_ca_certificate"
-                    android:layout_marginTop="5dip"
-                    android:contentDescription="@string/pass_button_text"
-                    android:padding="10dip"
-                    android:src="@drawable/fs_indeterminate"/>
-
-                <TextView
-                    style="@style/InstructionsSmallFont"
-                    android:layout_width="match_parent"
-                    android:layout_height="wrap_content"
-                    android:text="@string/sec_certificate_trust_text"/>
-            </LinearLayout>
-
-            <Button
-                android:id="@+id/check_cert_trust"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/layout3"
-                android:gravity="center"
-                android:text="@string/cacert_do_something"/>
-
-            <LinearLayout
-                android:id="@+id/layout4"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/check_cert_trust">
-
-                <ImageView
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:contentDescription="@string/pass_button_text"
-                    android:padding="10dip"
-                    android:src="@drawable/fs_indeterminate"/>
-
-                <TextView
-                    style="@style/InstructionsSmallFont"
-                    android:layout_width="match_parent"
-                    android:layout_height="wrap_content"
-                    android:text="@string/sec_push_ca_certificate_to_device_clearcreds_text"/>
-            </LinearLayout>
-
-            <Button
-                android:id="@+id/gotosettings"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/layout4"
-                android:gravity="center"
-                android:text="@string/cacert_do_something"/>
-
-            <LinearLayout
-                android:id="@+id/layout6"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:layout_below="@+id/gotosettings">
-
-                <TextView
-                    android:id="@+id/clear_creds_textView"
-                    style="@style/InstructionsSmallFont"
-                    android:layout_width="match_parent"
-                    android:layout_height="wrap_content"
-                    android:text="@string/passfail_instruction"
-                    android:textAlignment="center"/>
-            </LinearLayout>
-
-        </RelativeLayout>
-    </ScrollView>
-
-    <include
-        android:id="@+id/pass_fail_buttons"
-        layout="@layout/pass_fail_buttons"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:layout_alignParentBottom="true"/>
-
-</RelativeLayout>
\ No newline at end of file
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index c658341..2c85c30 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -147,21 +147,7 @@
     <string name="sec_fp_dialog_message">Authenticate now with fingerprint</string>
     <string name="sec_fp_auth_failed">Authentication failed</string>
     <string name="sec_start_test">Start Test</string>
-    <!--CA certificate Test - CA Certificates installed for WiFi are trusted by whole system-->
-    <string name="sec_wifi_ca_cert_test">WiFi CA Certificate Test</string>
-    <string name="sec_wifi_ca_cert_test_info">This test ensures that the CA certificates installed for WiFi should not be trusted by the whole system</string>
-    <string name="sec_push_ca_certificate_to_device_text">Click on the below button to transfer the Certificate to internal storage of your device.</string>
-    <string name="sec_push_ca_certificate_to_device_clearcreds_text">1. Click on below button to launch the security settings of the device.\n2. Select the Clear Credentials option. Select OK.\n3. Come back to the test case. Proceed to the next step</string>
-    <string name="sec_certificate_trust_text">1. Click on the button below to check if the certificate is trusted or not.</string>
-    <string name="sec_launch_wifi_settings">1. Click on the button below to launch the wifi settings.\n2. Access the Action Overflow menu and select Advanced.\n3. Select Install Certificates option.\n4. On left hand slider menu, select Internal Storage.\n5. Browse to \'myCA.cer\' file.\n6. Type \'bug\' in Certificate Name and select WiFi under Credential use dropdown.\n7. Select OK. Come back to the test case.</string>
-    <string name="sec_file_transfer_failed">Failed to transfer the Certificate to the device</string>
-    <string name="sec_file_transferred_text">The certificate has been transferred to the device successfully</string>
-    <string name="sec_cert_nottrusted_text">Certificate not trusted by the system. Proceed to the next step</string>
-    <string name="sec_cert_trusted_text">Certificate trusted by the system. Proceed to the next step</string>
-    <string name="sec_pass_test_instruction">Please PASS the test case, as the certificate is not trusted</string>
-    <string name="sec_fail_test_instruction">Please FAIL the test case, as the certificate is trusted</string>
-    <string name="sec_read_cert_exception">Exception occurred while reading the certificate</string>
-    <string name="passfail_instruction"></string>
+
     <!-- Strings for BluetoothActivity -->
     <string name="bluetooth_test">Bluetooth Test</string>
     <string name="bluetooth_test_info">The Bluetooth Control tests check whether or not the device
@@ -1696,6 +1682,19 @@
         Then use the Back button to return to this test and mark accordingly.
     </string>
 
+    <string name="provisioning_byod_battery_settings">Profile-aware battery settings</string>
+    <string name="provisioning_byod_battery_settings_instruction">
+        Please press the Go button to open Battery page in settings.\n
+        \n
+        Verify that Battery page shows both badged and unbadged apps in the usage list.\n
+        \n
+        Note that the usage list only displays usage since last charge,
+        so you may need to unplug your device and use a badged and unbadged app
+        for a little while before they will appear in the list.\n
+        \n
+        Then use the Back button to return to this test and mark accordingly.
+    </string>
+
     <string name="provisioning_byod_data_usage_settings">Profile-aware data usage settings</string>
     <string name="provisioning_byod_data_usage_settings_instruction">
         Please press the Go button to open the Settings page.\n
@@ -1906,16 +1905,6 @@
             your phone are not and cannot be downloaded through USB.\n
             Please mark the test accordingly.
     </string>
-    <string name="device_owner_set_user_icon">Setting the user icon</string>
-    <string name="device_owner_set_user_icon_instruction">
-        This test verifies that the user icon can be set.\n
-        1. Press the set user icon button.\n
-        2. Press the go button to go to Settings.\n
-        3a. If there is a "users" section in Settings, check that the icon of the user "owner" is the CtsVerifier one and mark this test accordingly.\n
-        3b. If there is no "users" section, mark this test as passed.\n
-    </string>
-    <string name="device_owner_set_user_icon_button">Set user icon</string>
-
     <string name="profile_owner_permission_lockdown_test_info">
         <b>
         Before proceeding, check if com.android.cts.permissionapp (aka CtsPermissionApp) is installed in work profile by going to Settings &gt; Apps. If not, please install the app before proceeding.\n\n
@@ -2331,21 +2320,4 @@
     <string name="audio_frequency_mic_test2_btn">Test 2</string>
     <string name="audio_frequency_mic_results_text">Results...</string>
 
-    <string name="alarmintenttest_title">Alarm Intent Test</string>
-    <string name="alarmintenttest_desc">This test verifies Elevation of Privileges by an
-        external application through setting an alarm using AlarmManager.setAlarmClock (A
-        vulnerability in SystemUI component)</string>
-    <string name="set_alarm_btn">Set alarm</string>
-    <string name="cancel_alarm_btn">Cancel</string>
-    <string name="alarmintenttest_set_alarm">Press SET ALARM below to set an Alarm</string>
-    <string name="alarmintenttest_instructions">Instructions to verify the bug:</string>
-    <string name="alarmintenttest_verify_bug">Click on alarm description near date in quick
-        settings</string>
-    <string name="alarmintenttest_point1">1.</string>
-    <string name="alarmintenttest_failcase">If a new activity(PlatLogoActivity) is
-        launched, please fail the test case</string>
-    <string name="alarmintenttest_point2">2.</string>
-    <string name="alarmintenttest_passcase">If nothing is happening after clicking on alarm
-        description, please pass the test case </string>
-    <string name="calcel_alarm_info">Click on Cancel below to cancel the Alarm</string>
 </resources>
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 0e7bca4..2148c83 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -70,6 +70,7 @@
     private DialogTestListItem mWorkStatusBarToastTest;
     private DialogTestListItem mAppSettingsVisibleTest;
     private DialogTestListItem mLocationSettingsVisibleTest;
+    private DialogTestListItem mBatterySettingsVisibleTest;
     private DialogTestListItem mDataUsageSettingsVisibleTest;
     private DialogTestListItem mCredSettingsVisibleTest;
     private DialogTestListItem mPrintSettingsVisibleTest;
@@ -255,6 +256,12 @@
                 R.string.provisioning_byod_location_settings_instruction,
                 new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
 
+        mBatterySettingsVisibleTest = new DialogTestListItem(this,
+                R.string.provisioning_byod_battery_settings,
+                "BYOD_BatterySettingsVisibleTest",
+                R.string.provisioning_byod_battery_settings_instruction,
+                new Intent(Intent.ACTION_POWER_USAGE_SUMMARY));
+
         mDataUsageSettingsVisibleTest = new DialogTestListItem(this,
                 R.string.provisioning_byod_data_usage_settings,
                 "BYOD_DataUsageSettingsVisibleTest",
@@ -341,6 +348,7 @@
         adapter.add(mCredSettingsVisibleTest);
         adapter.add(mAppSettingsVisibleTest);
         adapter.add(mLocationSettingsVisibleTest);
+        adapter.add(mBatterySettingsVisibleTest);
         adapter.add(mDataUsageSettingsVisibleTest);
         adapter.add(mPrintSettingsVisibleTest);
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
index 9c3afb1..2f8adbe 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceOwnerPositiveTestActivity.java
@@ -24,7 +24,6 @@
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.database.DataSetObserver;
-import android.graphics.BitmapFactory;
 import android.os.Bundle;
 import android.os.UserManager;
 import android.provider.Settings;
@@ -65,7 +64,6 @@
     static final String COMMAND_SET_STATUSBAR_DISABLED = "set-statusbar-disabled";
     static final String COMMAND_SET_KEYGUARD_DISABLED = "set-keyguard-disabled";
     static final String COMMAND_CHECK_PERMISSION_LOCKDOWN = "check-permission-lockdown";
-    static final String COMMAND_SET_USER_ICON = "set-user-icon";
     static final String EXTRA_SETTING = "extra-setting";
 
     private static final String CHECK_DEVICE_OWNER_TEST_ID = "CHECK_DEVICE_OWNER";
@@ -79,7 +77,6 @@
     private static final String DISALLOW_CONFIG_WIFI_ID = "DISALLOW_CONFIG_WIFI";
     private static final String DISALLOW_CONFIG_VPN_ID = "DISALLOW_CONFIG_VPN";
     private static final String DISALLOW_USB_FILE_TRANSFER_ID = "DISALLOW_USB_FILE_TRANSFER";
-    private static final String SET_USER_ICON_TEST_ID = "SET_USER_ICON";
     //TODO(rgl): This symbol should be available in android.provider.settings
     private static final String ACTION_VPN_SETTINGS = "android.net.vpn.SETTINGS";
     private static final String REMOVE_DEVICE_OWNER_TEST_ID = "REMOVE_DEVICE_OWNER";
@@ -236,17 +233,6 @@
                                 createDeviceOwnerIntentWithBooleanParameter(
                                         COMMAND_SET_KEYGUARD_DISABLED, false))}));
 
-        adapter.add(createInteractiveTestItem(this, SET_USER_ICON_TEST_ID,
-                R.string.device_owner_set_user_icon,
-                R.string.device_owner_set_user_icon_instruction,
-                new ButtonInfo[] {
-                        new ButtonInfo(
-                                R.string.device_owner_set_user_icon_button,
-                                createSetUserIconIntent()),
-                        new ButtonInfo(
-                                R.string.device_owner_settings_go,
-                                new Intent(Settings.ACTION_SETTINGS))}));
-
         // setPermissionGrantState
         adapter.add(createTestItem(this, CHECK_PERMISSION_LOCKDOWN_TEST_ID,
                 R.string.device_profile_owner_permission_lockdown_test,
@@ -299,11 +285,6 @@
                 .putExtra(EXTRA_RESTRICTION, restriction);
     }
 
-    private Intent createSetUserIconIntent() {
-        return new Intent(this, CommandReceiver.class)
-                .putExtra(EXTRA_COMMAND, COMMAND_SET_USER_ICON);
-    }
-
     public static class CommandReceiver extends Activity {
         @Override
         public void onCreate(Bundle savedInstanceState) {
@@ -347,12 +328,6 @@
                         TestResult.setFailedResult(this, intent.getStringExtra(EXTRA_TEST_ID),
                                 getString(R.string.device_owner_incorrect_device_owner), null);
                     }
-                } else if (COMMAND_SET_USER_ICON.equals(command)) {
-                    if (!dpm.isDeviceOwnerApp(getPackageName())) {
-                        return;
-                    }
-                    dpm.setUserIcon(admin, BitmapFactory.decodeResource(getResources(),
-                            com.android.cts.verifier.R.drawable.icon));
                 } else {
                     Log.e(TAG, "Invalid command: " + command);
                 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/AlarmIntentTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/AlarmIntentTest.java
deleted file mode 100644
index fd0b0a7..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/security/AlarmIntentTest.java
+++ /dev/null
@@ -1,84 +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.verifier.security;
-
-import android.app.Activity;
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.view.View;
-import android.widget.Button;
-import android.widget.ImageView;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import java.util.Date;
-
-public class AlarmIntentTest extends PassFailButtons.Activity {
-
-    // Just for cancelling alarm
-    private PendingIntent mAlarmIntent;
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setContentView(R.layout.activity_alarmintent);
-        setPassFailButtonClickListeners();
-        setInfoResources(R.string.alarmintenttest_title, R.string.alarmintenttest_desc, -1);
-        mAlarmIntent = PendingIntent.getBroadcast(this, 0, new Intent("alarm_going_off"), 0);
-
-        Button setAlarm = (Button) findViewById(R.id.set_alarm);
-        setAlarm.setOnClickListener(new View.OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                ImageView view1 = (ImageView) findViewById(R.id.img1);
-                setAlarm();
-                view1.setImageResource(R.drawable.fs_good);
-            }
-        });
-
-        Button cancelAlarm = (Button) findViewById(R.id.cancel_alarm);
-        cancelAlarm.setOnClickListener(new View.OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                ImageView view2 = (ImageView) findViewById(R.id.img2);
-                ImageView view3 = (ImageView) findViewById(R.id.img3);
-                cancelAlarm();
-                view2.setImageResource(R.drawable.fs_good);
-                view3.setImageResource(R.drawable.fs_good);
-            }
-        });
-    }
-
-    public void setAlarm() {
-        PendingIntent editAlarmIntent = PendingIntent.getActivity(this, 0, new Intent().
-                setClassName("android", "com.android.internal.app.PlatLogoActivity"), 0);
-
-        // Set the alarm
-        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
-        alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(
-                new Date().getTime() + 1000 * 60 * 5, editAlarmIntent), mAlarmIntent);
-        // Alarm intent(mAlarmIntent) is irrelevant here, just for cancelling
-    }
-
-    public void cancelAlarm() {
-        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
-        alarmManager.cancel(mAlarmIntent);
-    }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/WiFiCACertificateBugTest.java b/apps/CtsVerifier/src/com/android/cts/verifier/security/WiFiCACertificateBugTest.java
deleted file mode 100644
index 474a157..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/security/WiFiCACertificateBugTest.java
+++ /dev/null
@@ -1,251 +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.verifier.security;
-
-import android.app.AlertDialog;
-import android.app.KeyguardManager;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.os.Bundle;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.widget.Button;
-import android.widget.TextView;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.GeneralSecurityException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.util.Arrays;
-
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509TrustManager;
-
-public class WiFiCACertificateBugTest extends PassFailButtons.Activity {
-
-    private static final String CERT_ASSET_NAME = "myCA.cer";
-    private File certStagingFile = new File("/sdcard/", CERT_ASSET_NAME);
-    private KeyguardManager mKeyguardManager;
-    private boolean testResult;
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setContentView(R.layout.ca_certificate_wifi);
-        setPassFailButtonClickListeners();
-        setInfoResources(R.string.sec_wifi_ca_cert_test, R.string.sec_wifi_ca_cert_test_info, -1);
-
-        mKeyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
-
-        getPassButton().setEnabled(false);
-        Button transferCertificateButton = (Button) findViewById(R.id.transfer_ca_certificate);
-        final Button goToSettingsButton = (Button) findViewById(R.id.gotosettings);
-        goToSettingsButton.setEnabled(false);
-        final Button goToWifiSettingsButton = (Button) findViewById(R.id.gotowifisettings);
-        goToWifiSettingsButton.setEnabled(false);
-        final Button certificateTrustCheckButton = (Button) findViewById(R.id.check_cert_trust);
-        certificateTrustCheckButton.setEnabled(false);
-
-        final TextView finalStepTextView = (TextView) findViewById(R.id.clear_creds_textView);
-
-        goToSettingsButton.setOnClickListener(new OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                //Launch settings of the device
-                startActivityForResult(
-                        new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS), 0);
-                if (testResult) {
-                    getPassButton().setEnabled(true);
-                    finalStepTextView.setText(getResources().getString(R.string
-                            .sec_pass_test_instruction));
-                } else {
-                    finalStepTextView.setText(getResources().getString(R.string
-                            .sec_fail_test_instruction));
-                }
-            }
-        });
-        goToWifiSettingsButton.setOnClickListener(new OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                //Launch WiFi settings of the device
-                startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
-            }
-        });
-        transferCertificateButton.setOnClickListener(new OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                if (transferCertificateToDevice()) {
-                    openDialog(getResources().getString(R.string.sec_file_transferred_text));
-                    goToSettingsButton.setEnabled(true);
-                    goToWifiSettingsButton.setEnabled(true);
-                    certificateTrustCheckButton.setEnabled(true);
-                } else {
-                    openDialog(getResources().getString(R.string.sec_file_transfer_failed));
-                }
-            }
-        });
-        certificateTrustCheckButton.setOnClickListener(new OnClickListener() {
-            @Override
-            public void onClick(View v) {
-                Certificate caCert = readCertificate(convertFileToByteArray(certStagingFile));
-                if (caCert != null) {
-                    if (isCaCertificateTrusted(caCert)) {
-                        testResult = false;
-                        openDialog(getResources().getString(R.string.sec_cert_trusted_text));
-
-                    } else {
-                        testResult = true;
-                        openDialog(getResources().getString(R.string.sec_cert_nottrusted_text));
-                    }
-                } else {
-                    openDialog(getResources().getString(R.string.sec_read_cert_exception));
-                }
-            }
-        });
-    }
-
-    /**
-     * Transfers the certificate file to the internal storage i.e. /sdcard/ of the device
-     *
-     * @return
-     */
-    private boolean transferCertificateToDevice() {
-        InputStream is = null;
-        FileOutputStream os = null;
-        try {
-            try {
-                is = getAssets().open(CERT_ASSET_NAME);
-                os = new FileOutputStream(certStagingFile);
-                byte[] buffer = new byte[1024];
-                int length;
-                while ((length = is.read(buffer)) > 0) {
-                    os.write(buffer, 0, length);
-                }
-            } finally {
-                if (is != null) is.close();
-                if (os != null) os.close();
-                certStagingFile.setReadable(true, false);
-            }
-        } catch (IOException ioe) {
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * Converts the certificate file into byte array
-     *
-     * @param file
-     * @return
-     */
-    private static byte[] convertFileToByteArray(File file) {
-        byte[] byteArray = null;
-        try {
-            InputStream inputStream = new FileInputStream(file);
-            ByteArrayOutputStream bos = new ByteArrayOutputStream();
-            byte[] bytes = new byte[1024 * 8];
-            int bytesRead = 0;
-
-            while ((bytesRead = inputStream.read(bytes)) != -1) {
-                bos.write(bytes, 0, bytesRead);
-            }
-            byteArray = bos.toByteArray();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-        return byteArray;
-    }
-
-    /**
-     * Opens the dialog with the message passed as an argument
-     *
-     * @param message
-     */
-    private void openDialog(String message) {
-        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
-        alertDialogBuilder.setMessage(message);
-
-        alertDialogBuilder.setPositiveButton(getResources().getString(R.string
-                .hifi_ultrasound_test_ok), new DialogInterface.OnClickListener() {
-            @Override
-            public void onClick(DialogInterface dialog, int arg1) {
-                dialog.dismiss();
-            }
-        });
-        AlertDialog alertDialog = alertDialogBuilder.create();
-        alertDialog.show();
-    }
-
-    /**
-     * Checks if the exploit certificate is trusted by the system
-     *
-     * @param caCert
-     * @return
-     * @throws GeneralSecurityException
-     * @throws CertificateException
-     */
-    private boolean isCaCertificateTrusted(Certificate caCert) {
-
-        boolean trusted = false;
-        TrustManagerFactory tmf = null;
-        try {
-            tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
-            tmf.init((KeyStore) null);
-        } catch (NoSuchAlgorithmException | KeyStoreException e) {
-            return trusted;
-        }
-        for (TrustManager trustManager : tmf.getTrustManagers()) {
-            if (trustManager instanceof X509TrustManager) {
-                final X509TrustManager tm = (X509TrustManager) trustManager;
-                if (Arrays.asList(tm.getAcceptedIssuers()).contains(caCert)) {
-                    trusted = true;
-                    break;
-                }
-            }
-        }
-        return trusted;
-    }
-
-    /**
-     * Convert an encoded certificate back into a {@link Certificate}.
-     * <p/>
-     * Instantiates a fresh CertificateFactory every time for repeatability.
-     */
-    private static Certificate readCertificate(byte[] certBuffer) {
-        CertificateFactory certFactory = null;
-        try {
-            certFactory = CertificateFactory.getInstance("X.509");
-            return certFactory.generateCertificate(new ByteArrayInputStream(certBuffer));
-        } catch (CertificateException e) {
-            return null;
-        }
-    }
-}
\ No newline at end of file
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfo.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfo.java
index be44243..c74ed3a 100644
--- a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfo.java
+++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/DeviceInfo.java
@@ -20,4 +20,6 @@
  * class instead of DeviceInfoActivity.
  */
 public abstract class DeviceInfo extends DeviceInfoActivity {
+
 }
+
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptableHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptableHostTest.java
index 6bf2a01..2ae2e10 100644
--- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptableHostTest.java
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/AdoptableHostTest.java
@@ -26,7 +26,6 @@
 import com.android.cts.appsecurity.SplitTests.BaseInstallMultiple;
 import com.android.cts.tradefed.build.CtsBuildHelper;
 import com.android.tradefed.build.IBuildInfo;
-import com.android.tradefed.device.CollectingOutputReceiver;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.testtype.DeviceTestCase;
 import com.android.tradefed.testtype.IAbi;
@@ -34,7 +33,6 @@
 import com.android.tradefed.testtype.IBuildReceiver;
 
 import java.util.Arrays;
-import java.util.concurrent.TimeUnit;
 
 /**
  * Set of tests that verify behavior of adopted storage media, if supported.
@@ -149,10 +147,7 @@
         final LocalVolumeInfo vol = getAdoptionVolume();
 
         // Move storage there and verify that data went along for ride
-        final CollectingOutputReceiver out = new CollectingOutputReceiver();
-        getDevice().executeShellCommand("pm move-primary-storage " + vol.uuid, out, 2,
-                TimeUnit.HOURS, 1);
-        assertSuccess(out.getOutput());
+        assertSuccess(getDevice().executeShellCommand("pm move-primary-storage " + vol.uuid));
         runDeviceTests(PKG, CLASS, "testPrimaryAdopted");
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
 
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java
index 124ebe8..cda76f2 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java
@@ -45,7 +45,7 @@
     private static final String NETWORK_SSID = "com.android.cts.xwde7ktvh8rmjuhr";
 
     // Time duration to allow before assuming that a WiFi operation failed and ceasing to wait.
-    private static final long UPDATE_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(5);
+    private static final long UPDATE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(30);
     private static final long UPDATE_INTERVAL_MS = TimeUnit.SECONDS.toMillis(1);
 
     // Shared WifiManager instance.
diff --git a/hostsidetests/security/src/android/cts/security/PerfEventParanoidTest.java b/hostsidetests/security/src/android/cts/security/PerfEventParanoidTest.java
new file mode 100644
index 0000000..b581dbe
--- /dev/null
+++ b/hostsidetests/security/src/android/cts/security/PerfEventParanoidTest.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.security.cts;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.testtype.DeviceTestCase;
+
+public class PerfEventParanoidTest extends DeviceTestCase {
+
+   /**
+    * a reference to the device under test.
+    */
+    private ITestDevice mDevice;
+
+    private static final String PERF_EVENT_PARANOID_PATH = "/proc/sys/kernel/perf_event_paranoid";
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mDevice = getDevice();
+    }
+
+    public void testPerfEventRestricted() throws DeviceNotAvailableException {
+        String cmd = "cat " + PERF_EVENT_PARANOID_PATH;
+        String output = mDevice.executeShellCommand(cmd);
+        assertTrue("\n/proc/sys/kernel/perf_event_paranoid=3 is required.\n"
+                   + "Please add CONFIG_SECURITY_PERF_EVENTS_RESTRICT=y\n"
+                   + "to your device kernel's defconfig and apply the\n"
+                   + "appropriate patches for your kernel located here:\n"
+                   + "https://android-review.googlesource.com/#/q/topic:CONFIG_SECURITY_PERF_EVENTS_RESTRICT",
+                   output.equals("3\n"));
+    }
+}
diff --git a/libs/deviceutil/src/android/cts/util/KeyEventUtil.java b/libs/deviceutil/src/android/cts/util/KeyEventUtil.java
deleted file mode 100644
index 961337d..0000000
--- a/libs/deviceutil/src/android/cts/util/KeyEventUtil.java
+++ /dev/null
@@ -1,197 +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.cts.util;
-
-import android.app.Instrumentation;
-import android.os.Looper;
-import android.os.SystemClock;
-import android.util.Log;
-import android.view.InputDevice;
-import android.view.KeyCharacterMap;
-import android.view.KeyEvent;
-import android.view.View;
-import android.view.inputmethod.InputMethodManager;
-
-import java.lang.reflect.Field;
-
-/**
- * Utility class to send KeyEvents to TextView bypassing the IME. The code is similar to functions
- * in {@link Instrumentation} and {@link android.test.InstrumentationTestCase} classes. It uses
- * {@link View#dispatchKeyEvent(KeyEvent)} to send the events.
- * After sending the events waits for idle.
- */
-public class KeyEventUtil {
-    private final Instrumentation mInstrumentation;
-
-    public KeyEventUtil(Instrumentation instrumentation) {
-        this.mInstrumentation = instrumentation;
-    }
-
-    /**
-     * Sends the key events corresponding to the text to the app being instrumented.
-     *
-     * @param targetView View to find the ViewRootImpl and dispatch.
-     * @param text The text to be sent. Null value returns immediately.
-     */
-    public final void sendString(final View targetView, final String text) {
-        if (text == null) {
-            return;
-        }
-
-        KeyEvent[] events = getKeyEvents(text);
-
-        if (events != null) {
-            for (int i = 0; i < events.length; i++) {
-                // We have to change the time of an event before injecting it because
-                // all KeyEvents returned by KeyCharacterMap.getEvents() have the same
-                // time stamp and the system rejects too old events. Hence, it is
-                // possible for an event to become stale before it is injected if it
-                // takes too long to inject the preceding ones.
-                sendKey(targetView, KeyEvent.changeTimeRepeat(events[i], SystemClock.uptimeMillis(),
-                        0));
-            }
-        }
-    }
-
-    /**
-     * Sends a series of key events through instrumentation. For instance:
-     * sendKeys(view, KEYCODE_DPAD_LEFT, KEYCODE_DPAD_CENTER).
-     *
-     * @param targetView View to find the ViewRootImpl and dispatch.
-     * @param keys The series of key codes.
-     */
-    public final void sendKeys(final View targetView, final int...keys) {
-        final int count = keys.length;
-
-        for (int i = 0; i < count; i++) {
-            try {
-                sendKeyDownUp(targetView, keys[i]);
-            } catch (SecurityException e) {
-                // Ignore security exceptions that are now thrown
-                // when trying to send to another app, to retain
-                // compatibility with existing tests.
-            }
-        }
-    }
-
-    /**
-     * Sends a series of key events through instrumentation. The sequence of keys is a string
-     * containing the key names as specified in KeyEvent, without the KEYCODE_ prefix. For
-     * instance: sendKeys(view, "DPAD_LEFT A B C DPAD_CENTER"). Each key can be repeated by using
-     * the N* prefix. For instance, to send two KEYCODE_DPAD_LEFT, use the following:
-     * sendKeys(view, "2*DPAD_LEFT").
-     *
-     * @param targetView View to find the ViewRootImpl and dispatch.
-     * @param keysSequence The sequence of keys.
-     */
-    public final void sendKeys(final View targetView, final String keysSequence) {
-        final String[] keys = keysSequence.split(" ");
-        final int count = keys.length;
-
-        for (int i = 0; i < count; i++) {
-            String key = keys[i];
-            int repeater = key.indexOf('*');
-
-            int keyCount;
-            try {
-                keyCount = repeater == -1 ? 1 : Integer.parseInt(key.substring(0, repeater));
-            } catch (NumberFormatException e) {
-                Log.w("ActivityTestCase", "Invalid repeat count: " + key);
-                continue;
-            }
-
-            if (repeater != -1) {
-                key = key.substring(repeater + 1);
-            }
-
-            for (int j = 0; j < keyCount; j++) {
-                try {
-                    final Field keyCodeField = KeyEvent.class.getField("KEYCODE_" + key);
-                    final int keyCode = keyCodeField.getInt(null);
-                    try {
-                        sendKeyDownUp(targetView, keyCode);
-                    } catch (SecurityException e) {
-                        // Ignore security exceptions that are now thrown
-                        // when trying to send to another app, to retain
-                        // compatibility with existing tests.
-                    }
-                } catch (NoSuchFieldException e) {
-                    Log.w("ActivityTestCase", "Unknown keycode: KEYCODE_" + key);
-                    break;
-                } catch (IllegalAccessException e) {
-                    Log.w("ActivityTestCase", "Unknown keycode: KEYCODE_" + key);
-                    break;
-                }
-            }
-        }
-    }
-
-    /**
-     * Sends an up and down key events.
-     *
-     * @param targetView View to find the ViewRootImpl and dispatch.
-     * @param key The integer keycode for the event to be send.
-     */
-    public final void sendKeyDownUp(final View targetView, final int key) {
-        sendKey(targetView, new KeyEvent(KeyEvent.ACTION_DOWN, key));
-        sendKey(targetView, new KeyEvent(KeyEvent.ACTION_UP, key));
-    }
-
-    /**
-     * Sends a key event.
-     *
-     * @param targetView View to find the ViewRootImpl and dispatch.
-     * @param event KeyEvent to be send.
-     */
-    public final void sendKey(final View targetView, final KeyEvent event) {
-        long downTime = event.getDownTime();
-        long eventTime = event.getEventTime();
-        int action = event.getAction();
-        int code = event.getKeyCode();
-        int repeatCount = event.getRepeatCount();
-        int metaState = event.getMetaState();
-        int deviceId = event.getDeviceId();
-        int scancode = event.getScanCode();
-        int source = event.getSource();
-        int flags = event.getFlags();
-        if (source == InputDevice.SOURCE_UNKNOWN) {
-            source = InputDevice.SOURCE_KEYBOARD;
-        }
-        if (eventTime == 0) {
-            eventTime = SystemClock.uptimeMillis();
-        }
-        if (downTime == 0) {
-            downTime = eventTime;
-        }
-
-        final KeyEvent newEvent = new KeyEvent(downTime, eventTime, action, code, repeatCount,
-                metaState, deviceId, scancode, flags, source);
-
-        mInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                targetView.dispatchKeyEvent(newEvent);
-            }
-        });
-        mInstrumentation.waitForIdleSync();
-    }
-
-    private KeyEvent[] getKeyEvents(final String text) {
-        KeyCharacterMap keyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
-        return keyCharacterMap.getEvents(text.toCharArray());
-    }
-}
diff --git a/libs/testserver/src/android/webkit/cts/CtsTestServer.java b/libs/testserver/src/android/webkit/cts/CtsTestServer.java
index 321b44d..de88f3b 100644
--- a/libs/testserver/src/android/webkit/cts/CtsTestServer.java
+++ b/libs/testserver/src/android/webkit/cts/CtsTestServer.java
@@ -54,31 +54,34 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
 import java.net.ServerSocket;
 import java.net.Socket;
 import java.net.URI;
 import java.net.URL;
 import java.net.URLEncoder;
+import java.net.URLConnection;
+import java.security.KeyManagementException;
 import java.security.KeyStore;
+import java.security.NoSuchAlgorithmException;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.Hashtable;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.Vector;
+import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
-import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.KeyManager;
 import javax.net.ssl.KeyManagerFactory;
 import javax.net.ssl.SSLContext;
@@ -112,6 +115,7 @@
     private static final String COOKIE_PREFIX = "/cookie";
     private static final String LINKED_SCRIPT_PREFIX = "/linkedscriptprefix";
     private static final String AUTH_PREFIX = "/auth";
+    private static final String SHUTDOWN_PREFIX = "/shutdown";
     public static final String NOLENGTH_POSTFIX = "nolength";
     private static final int DELAY_MILLIS = 2000;
 
@@ -219,13 +223,74 @@
      * Terminate the http server.
      */
     public void shutdown() {
-        mServerThread.shutDownOnClientThread();
-
         try {
+            // Avoid a deadlock between two threads where one is trying to call
+            // close() and the other one is calling accept() by sending a GET
+            // request for shutdown and having the server's one thread
+            // sequentially call accept() and close().
+            URL url = new URL(mServerUri + SHUTDOWN_PREFIX);
+            if (url.getProtocol().equalsIgnoreCase("http")) {
+                // Use Socket instead of HttpURLConnection when the server is in cleartext HTTP mode
+                // to avoid the request being blocked by NetworkSecurityPolicy.
+                Socket socket = null;
+                try {
+                    socket = new Socket(url.getHost(), url.getPort());
+                    socket.getOutputStream().write(
+                        ("GET " + SHUTDOWN_PREFIX + " HTTP/1.0\r\n\r\n").getBytes("US-ASCII"));
+                    socket.getOutputStream().flush();
+                } finally {
+                    if (socket != null) {
+                        try {
+                            socket.close();
+                        } catch (Exception ignored) {}
+                    }
+                }
+            } else {
+                URLConnection connection = openConnection(url);
+                connection.connect();
+
+                // Read the input from the stream to send the request.
+                InputStream is = connection.getInputStream();
+                is.close();
+            }
+
             // Block until the server thread is done shutting down.
             mServerThread.join();
+
+        } catch (MalformedURLException e) {
+            throw new IllegalStateException(e);
         } catch (InterruptedException e) {
             throw new RuntimeException(e);
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        } catch (NoSuchAlgorithmException e) {
+            throw new IllegalStateException(e);
+        } catch (KeyManagementException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+    private URLConnection openConnection(URL url)
+            throws IOException, NoSuchAlgorithmException, KeyManagementException {
+        if (mSsl == SslMode.INSECURE) {
+            return url.openConnection();
+        } else {
+            // Install hostname verifiers and trust managers that don't do
+            // anything in order to get around the client not trusting
+            // the test server due to a lack of certificates.
+
+            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+            connection.setHostnameVerifier(new CtsHostnameVerifier());
+
+            SSLContext context = SSLContext.getInstance("TLS");
+            try {
+                context.init(ServerThread.getKeyManagers(), getTrustManagers(), null);
+            } catch (Exception e) {
+                throw new RuntimeException(e);
+            }
+            connection.setSSLSocketFactory(context.getSocketFactory());
+
+            return connection;
         }
     }
 
@@ -710,6 +775,11 @@
             response.setEntity(createPage(agent, agent));
         } else if (path.equals(TEST_DOWNLOAD_PATH)) {
             response = createTestDownloadResponse(Uri.parse(uriString));
+        } else if (path.equals(SHUTDOWN_PREFIX)) {
+            response = createResponse(HttpStatus.SC_OK);
+            // We cannot close the socket here, because we need to respond.
+            // Status must be set to OK, or else the test will fail due to
+            // a RunTimeException.
         } else if (path.equals(APPCACHE_PATH)) {
             response = createResponse(HttpStatus.SC_OK);
             response.setEntity(createEntity("<!DOCTYPE HTML>" +
@@ -854,12 +924,9 @@
         private CtsTestServer mServer;
         private ServerSocket mSocket;
         private SslMode mSsl;
-        private boolean mWillShutDown = false;
+        private boolean mIsCancelled;
         private SSLContext mSslContext;
         private ExecutorService mExecutorService = Executors.newFixedThreadPool(20);
-        private Object mLock = new Object();
-        // All the sockets bound to an open connection.
-        private Set<Socket> mSockets = new HashSet<Socket>();
 
         /**
          * Defines the keystore contents for the server, BKS version. Holds just a
@@ -945,14 +1012,10 @@
         }
 
         public void run() {
-            while (!mWillShutDown) {
+            while (!mIsCancelled) {
                 try {
                     Socket socket = mSocket.accept();
 
-                    synchronized(mLock) {
-                        mSockets.add(socket);
-                    }
-
                     DefaultHttpServerConnection conn = mServer.createHttpServerConnection();
                     HttpParams params = new BasicHttpParams();
                     params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
@@ -962,17 +1025,17 @@
                     // parsing the response since conn.close() will crash
                     // for SSL requests due to UnsupportedOperationException.
                     HttpRequest request = conn.receiveRequestHeader();
+                    if (isShutdownRequest(request)) {
+                        mIsCancelled = true;
+                    }
                     if (request instanceof HttpEntityEnclosingRequest) {
                         conn.receiveRequestEntity( (HttpEntityEnclosingRequest) request);
                     }
 
-                    mExecutorService.execute(new HandleResponseTask(conn, request, socket));
+                    mExecutorService.execute(new HandleResponseTask(conn, request));
                 } catch (IOException e) {
                     // normal during shutdown, ignore
                     Log.w(TAG, e);
-                } catch (RejectedExecutionException e) {
-                    // normal during shutdown, ignore.
-                    Log.w(TAG, e);
                 } catch (HttpException e) {
                     Log.w(TAG, e);
                 } catch (UnsupportedOperationException e) {
@@ -981,26 +1044,10 @@
                     Log.w(TAG, e);
                 }
             }
-        }
-
-        /**
-         * Shutdown the socket and the executor service.
-         * Note this method is called on the client thread, instead of the server thread.
-         */
-        public void shutDownOnClientThread() {
             try {
-                mWillShutDown = true;
                 mExecutorService.shutdown();
                 mExecutorService.awaitTermination(1L, TimeUnit.MINUTES);
                 mSocket.close();
-                // To prevent the server thread from being blocked on read from socket,
-                // which is called when the server tries to receiveRequestHeader,
-                // close all the sockets here.
-                synchronized(mLock) {
-                    for (Socket socket : mSockets) {
-                        socket.close();
-                    }
-                }
             } catch (IOException ignored) {
                 // safe to ignore
             } catch (InterruptedException e) {
@@ -1008,19 +1055,24 @@
             }
         }
 
+        private static boolean isShutdownRequest(HttpRequest request) {
+            RequestLine requestLine = request.getRequestLine();
+            String uriString = requestLine.getUri();
+            URI uri = URI.create(uriString);
+            String path = uri.getPath();
+            return path.equals(SHUTDOWN_PREFIX);
+        }
+
         private class HandleResponseTask implements Runnable {
 
             private DefaultHttpServerConnection mConnection;
 
             private HttpRequest mRequest;
 
-            private Socket mSocket;
-
             public HandleResponseTask(DefaultHttpServerConnection connection,
-                    HttpRequest request, Socket socket)  {
+                    HttpRequest request) {
                 this.mConnection = connection;
                 this.mRequest = request;
-                this.mSocket = socket;
             }
 
             @Override
@@ -1030,10 +1082,6 @@
                     mConnection.sendResponseHeader(response);
                     mConnection.sendResponseEntity(response);
                     mConnection.close();
-
-                    synchronized(mLock) {
-                        ServerThread.this.mSockets.remove(mSocket);
-                    }
                 } catch (Exception e) {
                     Log.e(TAG, "Error handling request:", e);
                 }
diff --git a/tests/expectations/knownfailures.txt b/tests/expectations/knownfailures.txt
index 284719e..445e4c8 100644
--- a/tests/expectations/knownfailures.txt
+++ b/tests/expectations/knownfailures.txt
@@ -366,32 +366,5 @@
   description: "Still investigating this, root cause unknown yet",
   bug: 27578806,
   names: ["com.android.cts.cpptools.RunAsHostTest#testRunAs"]
-},
-{
-  description: "Sensor tests not working",
-  bug: 28159339,
-  names: [
-    "android.hardware.cts.helpers.sensorverification.TimestampClockSourceVerificationTest#testVerify_fail",
-    "android.hardware.cts.helpers.sensorverification.TimestampClockSourceVerificationTest#testVerify_jitter_fail",
-    "android.hardware.cts.helpers.sensorverification.TimestampClockSourceVerificationTest#testVerify_jitter_pass",
-    "android.hardware.cts.helpers.sensorverification.TimestampClockSourceVerificationTest#testVerify_missing_events_fail",
-    "android.hardware.cts.helpers.sensorverification.TimestampClockSourceVerificationTest#testVerify_missing_events_pass",
-    "android.hardware.cts.helpers.sensorverification.TimestampClockSourceVerificationTest#testVerify_no_events_fail",
-    "android.hardware.cts.helpers.sensorverification.TimestampClockSourceVerificationTest#testVerify_pass"
-  ]
-},
-{
-  description: "Permission Policy unaltered not working in M",
-  bug: 27599613,
-  names: [
-    "android.permission2.cts.PermissionPolicyTest#testPlatformPermissionPolicyUnaltered"
-  ]
-},
-{
-  description: "Libskia security test not working.",
-  bug: 29635350,
-  names: [
-    "android.security.cts.SkiaJpegDecodingTest#testLibskiaOverFlowJpegProcessing"
-  ]
 }
 ]
diff --git a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
index 9d7f566..f5b29cf 100644
--- a/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
+++ b/tests/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityEndToEndTest.java
@@ -332,7 +332,6 @@
                 .setTicker(message)
                 .setContentTitle("")
                 .setContentText("")
-                .setPriority(Notification.PRIORITY_MAX)
                 // Mark the notification as "interruptive" by specifying a vibration pattern. This
                 // ensures it's announced properly on watch-type devices.
                 .setVibrate(new long[] {})
diff --git a/tests/tests/content/Android.mk b/tests/tests/content/Android.mk
index 2c185d9..7d7858a 100644
--- a/tests/tests/content/Android.mk
+++ b/tests/tests/content/Android.mk
@@ -23,7 +23,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner services.core
 
 # Resource unit tests use a private locale and some densities
 LOCAL_AAPT_FLAGS = -c xx_YY -c cs -c small -c normal -c large -c xlarge \
diff --git a/tests/tests/content/src/android/content/cts/SyncStorageEngineTest.java b/tests/tests/content/src/android/content/cts/SyncStorageEngineTest.java
new file mode 100644
index 0000000..c53107f
--- /dev/null
+++ b/tests/tests/content/src/android/content/cts/SyncStorageEngineTest.java
@@ -0,0 +1,73 @@
+/*
+ * 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.content.cts;
+
+import android.accounts.Account;
+import android.content.ComponentName;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.ContextWrapper;
+import android.content.Intent;
+import android.content.PeriodicSync;
+import android.content.res.Resources;
+import android.content.SyncStatusInfo;
+import android.os.Bundle;
+import android.os.Looper;
+import android.test.AndroidTestCase;
+import android.test.RenamingDelegatingContext;
+import android.test.mock.MockContentResolver;
+import android.test.mock.MockContext;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.test.suitebuilder.annotation.MediumTest;
+import android.test.suitebuilder.annotation.SmallTest;
+import com.android.server.content.SyncStorageEngine;
+import com.android.internal.os.AtomicFile;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.List;
+
+public class SyncStorageEngineTest extends AndroidTestCase {
+    public void testMalformedAuthority() throws Exception {
+        Looper.prepare();
+        // Authority id is non integer. It should be discarded by SyncStorageEngine.
+        byte[] accountsFileData = ("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n"
+                + "<accounts>\n"
+                + "<listenForTickles user=\"0\" enabled=\"false\" />"
+                + "<listenForTickles user=\"1\" enabled=\"true\" />"
+                + "<authority id=\"nonint\" user=\"0\" account=\"account1\" type=\"type1\""
+                + " authority=\"auth1\" />\n"
+                + "</accounts>\n").getBytes();
+
+        File syncDir = getSyncDir();
+        syncDir.mkdirs();
+        AtomicFile accountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
+        FileOutputStream fos = accountInfoFile.startWrite();
+        fos.write(accountsFileData);
+        accountInfoFile.finishWrite(fos);
+
+        SyncStorageEngine engine = SyncStorageEngine.newTestInstance(getContext());
+        Account account = new Account("account1", "type1");
+        SyncStorageEngine.EndPoint endPoint = new SyncStorageEngine.EndPoint(account, "auth1", 0);
+        SyncStatusInfo info = engine.getStatusByAuthority(endPoint);
+        assertNull(info);
+    }
+
+    private File getSyncDir() {
+        return new File(new File(getContext().getFilesDir(), "system"), "sync");
+    }
+}
diff --git a/tests/tests/location/src/android/location/cts/LocationManagerTest.java b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
index 8ac56ae..5eb2b7a 100644
--- a/tests/tests/location/src/android/location/cts/LocationManagerTest.java
+++ b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
@@ -971,6 +971,19 @@
         }
     }
 
+    /**
+     * Test case for bug 33091107.
+     */
+    public void testLocationShouldStillBeMarkedMockWhenProvidersDoNotMatch()
+        throws InterruptedException {
+        double latitude = 20;
+        double longitude = 40;
+
+        // Register a listener for the location we are about to set.
+        updateLocationAndWait(
+                TEST_MOCK_PROVIDER_NAME, LocationManager.GPS_PROVIDER, latitude, longitude);
+    }
+
     @UiThreadTest
     public void testGpsStatusListener() {
         MockGpsStatusListener listener = new MockGpsStatusListener();
@@ -1114,22 +1127,38 @@
 
     private void updateLocationAndWait(String providerName, double latitude, double longitude)
             throws InterruptedException {
+        updateLocationAndWait(providerName, providerName, latitude, longitude);
+    }
+
+    /**
+     * Like {@link #updateLocationAndWait(String, double, double)}, but allows inconsistent providers
+     * to be used in the calls to {@link Location#Location(String)} and {@link
+     * LocationManager#setTestProviderLocation(String, Location)}
+     *
+     * @param testProviderName used in {@link LocationManager#setTestProviderLocation(String,
+     * Location)}
+     * @param locationProviderName used in {@link Location#Location(String)}
+     */
+    private void updateLocationAndWait(String testProviderName, String locationProviderName,
+        double latitude, double longitude) throws InterruptedException {
+
         // Register a listener for the location we are about to set.
         MockLocationListener listener = new MockLocationListener();
         HandlerThread handlerThread = new HandlerThread("updateLocationAndWait");
         handlerThread.start();
-        mManager.requestLocationUpdates(providerName, 0, 0, listener, handlerThread.getLooper());
+        mManager.requestLocationUpdates(locationProviderName, 0, 0, listener,
+                handlerThread.getLooper());
 
         // Set the location.
-        updateLocation(providerName, latitude, longitude);
+        updateLocation(testProviderName, locationProviderName, latitude, longitude);
 
         // Make sure we received the location, and it is the right one.
-        assertTrue(listener.hasCalledOnLocationChanged(TEST_TIME_OUT));
+        assertTrue("Listener not called", listener.hasCalledOnLocationChanged(TEST_TIME_OUT));
         Location location = listener.getLocation();
-        assertEquals(providerName, location.getProvider());
-        assertEquals(latitude, location.getLatitude());
-        assertEquals(longitude, location.getLongitude());
-        assertEquals(true, location.isFromMockProvider());
+        assertEquals("Bad provider name", locationProviderName, location.getProvider());
+        assertEquals("Bad latitude", latitude, location.getLatitude());
+        assertEquals("Bad longitude", longitude, location.getLongitude());
+        assertTrue("Bad isMock", location.isFromMockProvider());
 
         // Remove the listener.
         mManager.removeUpdates(listener);
@@ -1182,13 +1211,23 @@
 
     private void updateLocation(final String providerName, final double latitude,
             final double longitude) {
-        Location location = new Location(providerName);
+        updateLocation(providerName, providerName, latitude, longitude);
+    }
+
+    /**
+     * Like {@link #updateLocation(String, double, double)}, but allows inconsistent providers to be
+     * used in the calls to {@link Location#Location(String)} and
+     * {@link LocationManager#setTestProviderLocation(String, Location)}.
+     */
+    private void updateLocation(String testProviderName, String locationProviderName,
+        double latitude, double longitude) {
+        Location location = new Location(locationProviderName);
         location.setLatitude(latitude);
         location.setLongitude(longitude);
         location.setAccuracy(1.0f);
-        location.setTime(java.lang.System.currentTimeMillis());
+        location.setTime(System.currentTimeMillis());
         location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
-        mManager.setTestProviderLocation(providerName, location);
+        mManager.setTestProviderLocation(testProviderName, location);
     }
 
     private void updateLocation(final double latitude, final double longitude) {
diff --git a/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java b/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
index e2905d4..68f4e73 100644
--- a/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
+++ b/tests/tests/media/src/android/media/cts/ExifInterfaceTest.java
@@ -23,10 +23,12 @@
 import android.os.Environment;
 import android.test.AndroidTestCase;
 import android.util.Log;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
 
 import com.android.cts.media.R;
 
-import libcore.io.IoUtils;
 import libcore.io.Streams;
 
 import java.io.BufferedInputStream;
@@ -164,15 +166,11 @@
         for (int i = 0; i < IMAGE_RESOURCES.length; ++i) {
             String outputPath = new File(Environment.getExternalStorageDirectory(),
                     IMAGE_FILENAMES[i]).getAbsolutePath();
-            InputStream inputStream = null;
-            FileOutputStream outputStream = null;
-            try {
-                inputStream = getContext().getResources().openRawResource(IMAGE_RESOURCES[i]);
-                outputStream = new FileOutputStream(outputPath);
-                Streams.copy(inputStream, outputStream);
-            } finally {
-                IoUtils.closeQuietly(inputStream);
-                IoUtils.closeQuietly(outputStream);
+            try (InputStream inputStream = getContext().getResources().openRawResource(
+                    IMAGE_RESOURCES[i])) {
+                try (FileOutputStream outputStream = new FileOutputStream(outputPath)) {
+                    Streams.copy(inputStream, outputStream);
+                }
             }
         }
         super.setUp();
diff --git a/tests/tests/os/src/android/os/cts/SecurityPatchTest.java b/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
index 4531aa6..a857670 100644
--- a/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
+++ b/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
@@ -31,8 +31,8 @@
             "ro.build.version.security_patch should be in the format \"YYYY-MM-DD\". Found \"%s\"";
     private static final String SECURITY_PATCH_DATE_ERROR =
             "ro.build.version.security_patch should be \"%d-%02d\" or later. Found \"%s\"";
-    private static final int SECURITY_PATCH_YEAR = 2016;
-    private static final int SECURITY_PATCH_MONTH = 12;
+    private static final int SECURITY_PATCH_YEAR = 2017;
+    private static final int SECURITY_PATCH_MONTH = 01;
 
     private boolean mSkipTests = false;
 
diff --git a/tests/tests/security/Android.mk b/tests/tests/security/Android.mk
index 14ea8df..b1e8035 100644
--- a/tests/tests/security/Android.mk
+++ b/tests/tests/security/Android.mk
@@ -28,7 +28,8 @@
 LOCAL_JNI_SHARED_LIBRARIES := libctssecurity_jni libcts_jni
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)\
-                   src/android/security/cts/activity/ISecureRandomService.aidl
+                   src/android/security/cts/activity/ISecureRandomService.aidl\
+                   aidl/android/security/cts/IIsolatedService.aidl
 
 LOCAL_PACKAGE_NAME := CtsSecurityTestCases
 
diff --git a/tests/tests/security/AndroidManifest.xml b/tests/tests/security/AndroidManifest.xml
index 4068aba..c483bde 100644
--- a/tests/tests/security/AndroidManifest.xml
+++ b/tests/tests/security/AndroidManifest.xml
@@ -24,6 +24,7 @@
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.RECORD_AUDIO" />
 
     <application>
         <uses-library android:name="android.test.runner" />
@@ -36,14 +37,10 @@
 
         <service android:name="android.security.cts.activity.SecureRandomService"
                  android:process=":secureRandom"/>
-        <activity
-            android:name="android.security.cts.SkiaJpegDecodingActivity"
-            android:label="Test overflow in libskia JPG processing">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN"/>
-                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST"/>
-            </intent-filter>
-        </activity>
+
+        <service android:name="android.security.cts.IsolatedService"
+                 android:process=":Isolated"
+                 android:isolatedProcess="true"/>
     </application>
 
     <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
diff --git a/tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java b/tests/tests/security/aidl/android/security/cts/IIsolatedService.aidl
similarity index 60%
rename from tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java
rename to tests/tests/security/aidl/android/security/cts/IIsolatedService.aidl
index 79f166f..16db0fe 100644
--- a/tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java
+++ b/tests/tests/security/aidl/android/security/cts/IIsolatedService.aidl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright 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.
@@ -16,15 +16,7 @@
 
 package android.security.cts;
 
-import android.app.Activity;
-import android.os.Bundle;
-
-import com.android.cts.security.R;
-
-public class SkiaJpegDecodingActivity extends Activity {
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setContentView(R.layout.activity_skiajpegdecoding);
-    }
-}
\ No newline at end of file
+interface IIsolatedService {
+    String[] getCachedSystemServices();
+    IBinder getSystemService(String serviceName);
+}
diff --git a/tests/tests/security/jni/Android.mk b/tests/tests/security/jni/Android.mk
index 431135e..804a177 100644
--- a/tests/tests/security/jni/Android.mk
+++ b/tests/tests/security/jni/Android.mk
@@ -32,31 +32,17 @@
 		android_security_cts_MMapExecutableTest.cpp \
 		android_security_cts_AudioPolicyBinderTest.cpp \
 		android_security_cts_EncryptionTest.cpp \
-		android_security_cts_MediaCryptoTest.cpp \
 		android_security_cts_MediaPlayerInfoLeakTest.cpp \
-		android_security_cts_AudioFlingerBinderTest.cpp \
 		android_security_cts_AudioEffectBinderTest.cpp \
-		android_security_cts_IDRMInfoLeakTest.cpp \
-		android_security_cts_MediaCodecListTest.cpp
+		android_security_cts_AudioFlingerBinderTest.cpp \
+		android_security_cts_StagefrightFoundationTest.cpp \
+		android_security_cts_GraphicBufferInfoLeakTest.cpp \
+		android_security_cts_IDRMInfoLeakTest.cpp
 
+LOCAL_C_INCLUDES := $(JNI_H_INCLUDE) \
+										$(TOP)/frameworks/native/include/media/openmax
 
-LOCAL_C_INCLUDES := \
-	$(JNI_H_INCLUDE) \
-	system/core/include \
-	frameworks/base/media/jni \
-	frameworks/native/include/media/openmax
-
-LOCAL_SHARED_LIBRARIES := \
-	libnativehelper \
-	liblog \
-	libbinder \
-	libutils \
-	libmedia \
-	libselinux \
-	libdl \
-	libcutils \
-	libcrypto \
-	libstagefright_foundation 
+LOCAL_SHARED_LIBRARIES := libnativehelper liblog libbinder libutils libmedia libselinux libdl libcutils libcrypto libstagefright_foundation
 
 LOCAL_C_INCLUDES += ndk/sources/cpufeatures
 LOCAL_STATIC_LIBRARIES := cpufeatures
diff --git a/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp b/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
index d292e7a..3a1144c 100644
--- a/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
+++ b/tests/tests/security/jni/CtsSecurityJniOnLoad.cpp
@@ -29,8 +29,9 @@
 extern int register_android_security_cts_EncryptionTest(JNIEnv* env);
 extern int register_android_security_cts_MediaPlayerInfoLeakTest(JNIEnv* env);
 extern int register_android_security_cts_AudioEffectBinderTest(JNIEnv* env);
+extern int register_android_security_cts_StagefrightFoundationTest(JNIEnv* env);
+extern int register_android_security_cts_GraphicBufferInfoLeakTest(JNIEnv* env);
 extern int register_android_security_cts_IDRMInfoLeakTest(JNIEnv* env);
-extern int register_android_security_cts_MediaCodecListTest(JNIEnv* env);
 
 jint JNI_OnLoad(JavaVM *vm, void *reserved) {
     JNIEnv *env = NULL;
@@ -87,12 +88,16 @@
         return JNI_ERR;
     }
 
-    if (register_android_security_cts_IDRMInfoLeakTest(env)) {
+    if (register_android_security_cts_StagefrightFoundationTest(env)) {
         return JNI_ERR;
     }
 
-    if (register_android_security_cts_MediaCodecListTest(env)) {
-            return JNI_ERR;
+    if (register_android_security_cts_GraphicBufferInfoLeakTest(env)) {
+        return JNI_ERR;
+    }
+
+    if (register_android_security_cts_IDRMInfoLeakTest(env)) {
+        return JNI_ERR;
     }
 
     return JNI_VERSION_1_4;
diff --git a/tests/tests/security/jni/android_security_cts_AudioPolicyBinderTest.cpp b/tests/tests/security/jni/android_security_cts_AudioPolicyBinderTest.cpp
index 1e3fc86..6011920 100644
--- a/tests/tests/security/jni/android_security_cts_AudioPolicyBinderTest.cpp
+++ b/tests/tests/security/jni/android_security_cts_AudioPolicyBinderTest.cpp
@@ -152,12 +152,12 @@
         return false;
     }
 
-    status_t status = aps->isStreamActive((audio_stream_type_t)(-1), 0);
-    if (status == NO_ERROR) {
+    bool status = aps->isStreamActive((audio_stream_type_t)(-1), 0);
+    if (status) {
         return false;
     }
     status = aps->isStreamActive((audio_stream_type_t)AUDIO_STREAM_CNT, 0);
-    if (status == NO_ERROR) {
+    if (status) {
         return false;
     }
     return true;
diff --git a/tests/tests/security/jni/android_security_cts_GraphicBufferInfoLeakTest.cpp b/tests/tests/security/jni/android_security_cts_GraphicBufferInfoLeakTest.cpp
new file mode 100644
index 0000000..d0cd347
--- /dev/null
+++ b/tests/tests/security/jni/android_security_cts_GraphicBufferInfoLeakTest.cpp
@@ -0,0 +1,186 @@
+/*
+ * 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.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "GraphicBufferInfoLeakTest-JNI"
+
+#include <jni.h>
+#include <JNIHelp.h>
+
+#include <binder/Parcel.h>
+#include <binder/IServiceManager.h>
+
+#include <gui/IGraphicBufferProducer.h>
+#include <gui/IGraphicBufferConsumer.h>
+#include <media/IMediaPlayerService.h>
+#include <media/IMediaRecorder.h>
+#include <media/IOMX.h>
+#include <media/stagefright/MediaErrors.h>
+
+#include <sys/stat.h>
+#include <fcntl.h>
+
+using namespace android;
+
+static sp<IMediaPlayerService> getMediaPlayerService()
+{
+   sp<IServiceManager> sm = defaultServiceManager();
+   sp<IBinder> mediaPlayerService = sm->checkService(String16("media.player"));
+
+   sp<IMediaPlayerService> iMPService = IMediaPlayerService::asInterface(mediaPlayerService);
+   return iMPService;
+}
+
+jint android_security_cts_GraphicBuffer_test_attachBufferInfoLeak(JNIEnv* env,
+                                                           jobject thiz __unused)
+{
+    sp<IMediaPlayerService> iMPService = getMediaPlayerService();
+
+    // get IOMX
+    // Keep synchronized with IMediaPlayerService.cpp!
+    enum {
+        GET_OMX = 4,
+    };
+
+    status_t  err;
+    Parcel data, reply;
+    data.writeInterfaceToken(iMPService->getInterfaceDescriptor());
+    err = IMediaPlayerService::asBinder(iMPService)->transact(GET_OMX, data, &reply);
+    if (err != NO_ERROR) {
+        jniThrowException(env, "java/lang/RuntimeException", "GET_OMX failed");
+    }
+
+    // get IGraphicBufferConsumer
+    sp<IGraphicBufferProducer> iBufferProducer;
+    sp<IGraphicBufferConsumer> iBufferConsumer;
+    sp<IOMX> iOmx = interface_cast<IOMX>(reply.readStrongBinder());
+    err = iOmx->createPersistentInputSurface(&iBufferProducer, &iBufferConsumer);
+    if (err != NO_ERROR) {
+        jniThrowException(env, "java/lang/RuntimeException", "createPersistentInputSurface failed");
+        return err;
+    }
+
+    // Keep synchronized with IGraphicBufferConsumer.cpp!
+    enum {
+        ATTACH_BUFFER = 3,
+    };
+
+    for (;;) {
+        Parcel data2, reply2;
+        data2.writeInterfaceToken(iBufferConsumer->getInterfaceDescriptor());
+        err = IGraphicBufferConsumer::asBinder(iBufferConsumer)->transact(ATTACH_BUFFER, data2, &reply2);
+        if (err != NO_ERROR) {
+            jniThrowException(env, "java/lang/RuntimeException", "ATTACH_BUFFER failed");
+        }
+
+        int32_t slot = reply2.readInt32();
+        status_t result = reply2.readInt32();
+        ALOGV("slot %d", slot);
+        if (result != 0) {
+            // only check for leaked data in error case
+            return slot;
+        }
+    }
+}
+
+jint android_security_cts_GraphicBuffer_test_queueBufferInfoLeak(JNIEnv* env,
+                                                           jobject thiz __unused)
+{
+    sp<IMediaPlayerService> iMPService = getMediaPlayerService();
+    sp<IMediaRecorder> recorder = iMPService->createMediaRecorder(String16("GraphicBufferInfoLeakTest"));
+
+    const char *fileName = "/dev/null";
+    int fd = open(fileName, O_RDWR | O_CREAT, 0744);
+    if (fd < 0) {
+        jniThrowException(env, "java/lang/RuntimeException", "open output failed");
+        return fd;
+    }
+
+    recorder->setVideoSource(2);
+    recorder->setOutputFile(fd, 0, 0);
+    recorder->setOutputFormat(0);
+    recorder->init();
+    recorder->prepare();
+    recorder->start();
+
+    //get IGraphicBufferProducer
+    sp<IGraphicBufferProducer> iGBP = recorder->querySurfaceMediaSource();
+    ALOGV("fd %d, Get iGBP instance, 0x%08x\n", fd, iGBP.get());
+
+    // Keep synchronized with IGraphicBufferProducer.cpp!
+    enum {
+        QUEUE_BUFFER = 7,
+    };
+
+    for (;;) {
+        status_t err;
+        Parcel data, reply;
+        data.writeInterfaceToken(iGBP->getInterfaceDescriptor());
+        data.writeInt32(-1);
+        err = IGraphicBufferProducer::asBinder(iGBP)->transact(QUEUE_BUFFER, data, &reply);
+        if (err != NO_ERROR) {
+            recorder->stop();
+            recorder->release();
+            jniThrowException(env, "java/lang/RuntimeException", "QUEUE_BUFFER failed");
+            return err;
+        }
+
+        size_t len = reply.dataAvail();
+        int32_t result; // last sizeof(int32_t) bytes of Parcel
+        ALOGV("dataAvail = %zu\n", len);
+        if (len < sizeof(result)) {
+            // must contain result
+            recorder->stop();
+            recorder->release();
+            jniThrowException(env, "java/lang/RuntimeException", "reply malformed");
+            return ERROR_MALFORMED;
+        }
+
+        uint8_t *reply_data = (uint8_t *)reply.data();
+        memcpy(&result, reply_data + len - sizeof(result), sizeof(result));
+        if (result == NO_ERROR) {
+            // only check for leaked data in error case
+            continue;
+        }
+
+        uint8_t leaked_data = 0;
+        for (size_t i = 0; i < len - sizeof(result); ++i) {
+            ALOGV("IGraphicBufferProducer_InfoLeak reply_data[%d] = 0x%08x", i, reply_data[i]);
+            if (reply_data[i]) {
+                leaked_data = reply_data[i];
+                break;
+            }
+        }
+
+        recorder->stop();
+        recorder->release();
+        return leaked_data;
+    }
+}
+
+static JNINativeMethod gMethods[] = {
+    {  "native_test_attachBufferInfoLeak", "()I",
+            (void *) android_security_cts_GraphicBuffer_test_attachBufferInfoLeak },
+    {  "native_test_queueBufferInfoLeak", "()I",
+            (void *) android_security_cts_GraphicBuffer_test_queueBufferInfoLeak },
+};
+
+int register_android_security_cts_GraphicBufferInfoLeakTest(JNIEnv* env)
+{
+    jclass clazz = env->FindClass("android/security/cts/GraphicBufferInfoLeakTest");
+    return env->RegisterNatives(clazz, gMethods,
+            sizeof(gMethods) / sizeof(JNINativeMethod));
+}
diff --git a/tests/tests/security/jni/android_security_cts_MediaCodecListTest.cpp b/tests/tests/security/jni/android_security_cts_MediaCodecListTest.cpp
deleted file mode 100644
index 56effa2..0000000
--- a/tests/tests/security/jni/android_security_cts_MediaCodecListTest.cpp
+++ /dev/null
@@ -1,60 +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.
- */
-#include <jni.h>
-#include <cstring>
-#include <cstdio>
-#include <binder/IPCThreadState.h>
-#include <binder/Parcel.h>
-#include <binder/IServiceManager.h>
-#include <binder/ProcessState.h>
-#include <media/IMediaCodecList.h>
-#include <media/IMediaPlayerService.h>
-#include <media/MediaCodecInfo.h>
-
-using namespace android;
-
-static jboolean android_security_cts_MediaCodecListTest_doCodecInfoTest
-        (JNIEnv* env __unused, jobject thiz __unused) {
-    sp<IMediaPlayerService> service =
-            interface_cast<IMediaPlayerService>(defaultServiceManager()
-            ->getService(String16("media.player")));
-    sleep(1);
-    sp<IMediaCodecList> list = service->getCodecList();
-    sleep(1);
-    list = service->getCodecList();
-    size_t count = list->countCodecs();
-    /*
-     * Trying to access the index out of boundary
-     */
-    count = count + 5;
-    sp<MediaCodecInfo> codecValue = list->getCodecInfo(count);
-    /*
-     * Fix was available in getCodecInfo()
-     * checks for boundary condition and returns null if out of boundary
-     */
-    return (codecValue == NULL);
-}
-
-static JNINativeMethod gMethods[] = {
-    {"doCodecInfoTest", "()Z",
-        (void *) android_security_cts_MediaCodecListTest_doCodecInfoTest}
-};
-
-int register_android_security_cts_MediaCodecListTest(JNIEnv* env) {
-    jclass clazz = env->FindClass("android/security/cts/MediaCodecListTest");
-    return env->RegisterNatives(
-            clazz, gMethods, sizeof(gMethods) / sizeof(JNINativeMethod));
-}
\ No newline at end of file
diff --git a/tests/tests/security/jni/android_security_cts_StagefrightFoundationTest.cpp b/tests/tests/security/jni/android_security_cts_StagefrightFoundationTest.cpp
new file mode 100644
index 0000000..d16bd38
--- /dev/null
+++ b/tests/tests/security/jni/android_security_cts_StagefrightFoundationTest.cpp
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "AudioEffectBinderTest-JNI"
+
+#include <cstdio>
+#include <jni.h>
+#include <binder/Parcel.h>
+#include <media/stagefright/foundation/AMessage.h>
+
+using namespace android;
+
+/*
+ * Native methods used by
+ * cts/tests/tests/security/src/android/security/cts/StagefrightFoundationTest.java
+ */
+
+static jboolean android_security_cts_StagefrightFoundation_test_aMessageFromParcel(
+        JNIEnv* env __unused, jobject thiz __unused)
+{
+    const int kMaxNumItems = 64;
+    const int kNumItems = kMaxNumItems + 1 + 1000;
+    char name[128];
+
+    Parcel data;
+    data.writeInt32(0);  // what
+    data.writeInt32(kNumItems);  // numItems
+    for (int i = 0; i < kMaxNumItems; ++i) {
+        snprintf(name, sizeof(name), "item-%d", i);
+        data.writeCString(name);  // name
+        data.writeInt32(0);  // kTypeInt32
+        data.writeInt32(i);  // value
+    }
+    data.writeCString("evil");  // name
+    data.writeInt32(0);  // kTypeInt32
+    data.writeInt32(0);  // value
+    // NOTE: This could overwrite mNumItems!
+
+    for (int i = 0; i < 1000; ++i) {
+        snprintf(name, sizeof(name), "evil-%d", i);
+        data.writeCString(name);  // name
+        data.writeInt32(0);  // kTypeInt32
+        data.writeInt32(0);  // value
+    }
+
+    data.setDataPosition(0);
+    sp<AMessage> msg = AMessage::FromParcel(data);
+
+    for (int i = 0; i < kMaxNumItems; ++i) {
+        snprintf(name, sizeof(name), "item-%d", i);
+        int32_t value;
+        if (!msg->findInt32(name, &value)) {
+            ALOGE("cannot find value for %s", name);
+            return JNI_FALSE;
+        }
+        if (value != i) {
+            ALOGE("value is changed: expected %d actual %d", i, value);
+            return JNI_FALSE;
+        }
+    }
+    return JNI_TRUE;
+}
+
+int register_android_security_cts_StagefrightFoundationTest(JNIEnv *env)
+{
+    static JNINativeMethod methods[] = {
+        { "native_test_aMessageFromParcel", "()Z",
+                (void *) android_security_cts_StagefrightFoundation_test_aMessageFromParcel},
+    };
+
+    jclass clazz = env->FindClass("android/security/cts/StagefrightFoundationTest");
+    return env->RegisterNatives(clazz, methods, sizeof(methods) / sizeof(methods[0]));
+}
diff --git a/tests/tests/security/res/drawable/signal_sigsegv_in_jmem_ashmem.jpg b/tests/tests/security/res/drawable/signal_sigsegv_in_jmem_ashmem.jpg
deleted file mode 100644
index f63f6ef..0000000
--- a/tests/tests/security/res/drawable/signal_sigsegv_in_jmem_ashmem.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/layout/activity_skiajpegdecoding.xml b/tests/tests/security/res/layout/activity_skiajpegdecoding.xml
deleted file mode 100644
index 68a0d68..0000000
--- a/tests/tests/security/res/layout/activity_skiajpegdecoding.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-<LinearLayout
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
-    android:gravity="center"
-    android:orientation="vertical">
-
-    <ImageView
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:src="@drawable/signal_sigsegv_in_jmem_ashmem"
-        />
-
-</LinearLayout>
\ No newline at end of file
diff --git a/tests/tests/security/res/raw/bug_25765591.mp2 b/tests/tests/security/res/raw/bug_25765591.mp2
new file mode 100644
index 0000000..200f575
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_25765591.mp2
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_31647370.ogg b/tests/tests/security/res/raw/bug_31647370.ogg
new file mode 100644
index 0000000..31f602a
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_31647370.ogg
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_32322258.mp4 b/tests/tests/security/res/raw/bug_32322258.mp4
new file mode 100644
index 0000000..6fcab5e
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_32322258.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_32577290.mp3 b/tests/tests/security/res/raw/bug_32577290.mp3
new file mode 100644
index 0000000..1098bb0
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_32577290.mp3
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_32873375.mp4 b/tests/tests/security/res/raw/bug_32873375.mp4
new file mode 100644
index 0000000..71e9c7b
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_32873375.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_32915871.mp4 b/tests/tests/security/res/raw/bug_32915871.mp4
new file mode 100644
index 0000000..9e50aaa
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_32915871.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2015_3836.xmf b/tests/tests/security/res/raw/cve_2015_3836.xmf
deleted file mode 100644
index b897c09..0000000
--- a/tests/tests/security/res/raw/cve_2015_3836.xmf
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2015_3864_b23034759.mp4 b/tests/tests/security/res/raw/cve_2015_3864_b23034759.mp4
deleted file mode 100644
index 3d1b223..0000000
--- a/tests/tests/security/res/raw/cve_2015_3864_b23034759.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2015_6608_b_23680780.mp4 b/tests/tests/security/res/raw/cve_2015_6608_b_23680780.mp4
deleted file mode 100644
index 6d41ebc..0000000
--- a/tests/tests/security/res/raw/cve_2015_6608_b_23680780.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2016_2429_b_27211885.mp3 b/tests/tests/security/res/raw/cve_2016_2429_b_27211885.mp3
new file mode 100644
index 0000000..0232e70
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2016_2429_b_27211885.mp3
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2016_3755.mp4 b/tests/tests/security/res/raw/cve_2016_3755.mp4
new file mode 100644
index 0000000..014bd06
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2016_3755.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2016_3878_b_29493002.mp4 b/tests/tests/security/res/raw/cve_2016_3878_b_29493002.mp4
new file mode 100644
index 0000000..469a1b3
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2016_3878_b_29493002.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/midi_crash.midi b/tests/tests/security/res/raw/midi_crash.midi
new file mode 100644
index 0000000..1880229
--- /dev/null
+++ b/tests/tests/security/res/raw/midi_crash.midi
Binary files differ
diff --git a/tests/tests/security/res/raw/onekhzsine_90sec.mp3 b/tests/tests/security/res/raw/onekhzsine_90sec.mp3
new file mode 100644
index 0000000..3049011
--- /dev/null
+++ b/tests/tests/security/res/raw/onekhzsine_90sec.mp3
Binary files differ
diff --git a/tests/tests/security/res/raw/skia_sigsegv_in_skicoimagedecoder.ico b/tests/tests/security/res/raw/skia_sigsegv_in_skicoimagedecoder.ico
deleted file mode 100644
index f488a24..0000000
--- a/tests/tests/security/res/raw/skia_sigsegv_in_skicoimagedecoder.ico
+++ /dev/null
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/EffectBundleTest.java b/tests/tests/security/src/android/security/cts/EffectBundleTest.java
new file mode 100644
index 0000000..c57f73f
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/EffectBundleTest.java
@@ -0,0 +1,341 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import android.media.audiofx.AudioEffect;
+import android.media.audiofx.Equalizer;
+import android.media.MediaPlayer;
+import android.test.InstrumentationTestCase;
+import android.util.Log;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import com.android.cts.security.R;
+
+public class EffectBundleTest extends InstrumentationTestCase {
+    private static final String TAG = "EffectBundleTest";
+    private static final int[] INVALID_BAND_ARRAY = {Integer.MIN_VALUE, -10000, -100, -2, -1};
+    private static final int mValue0 = 9999; //unlikely values. Should not change
+    private static final int mValue1 = 13877;
+    private static final int PRESET_CUSTOM = -1; //keep in sync AudioEqualizer.h
+
+    private static final int MEDIA_SHORT = 0;
+    private static final int MEDIA_LONG = 1;
+
+    //Testing security bug: 32436341
+    public void testEqualizer_getParamCenterFreq() throws Exception {
+        testGetParam(MEDIA_SHORT, Equalizer.PARAM_CENTER_FREQ, INVALID_BAND_ARRAY, mValue0,
+                mValue1);
+    }
+
+    //Testing security bug: 32588352
+    public void testEqualizer_getParamCenterFreq_long() throws Exception {
+        testGetParam(MEDIA_LONG, Equalizer.PARAM_CENTER_FREQ, INVALID_BAND_ARRAY, mValue0, mValue1);
+    }
+
+    //Testing security bug: 32438598
+    public void testEqualizer_getParamBandLevel() throws Exception {
+        testGetParam(MEDIA_SHORT, Equalizer.PARAM_BAND_LEVEL, INVALID_BAND_ARRAY, mValue0, mValue1);
+    }
+
+    //Testing security bug: 32584034
+    public void testEqualizer_getParamBandLevel_long() throws Exception {
+        testGetParam(MEDIA_LONG, Equalizer.PARAM_BAND_LEVEL, INVALID_BAND_ARRAY, mValue0, mValue1);
+    }
+
+    //Testing security bug: 32247948
+    public void testEqualizer_getParamFreqRange() throws Exception {
+        testGetParam(MEDIA_SHORT, Equalizer.PARAM_BAND_FREQ_RANGE, INVALID_BAND_ARRAY, mValue0,
+                mValue1);
+    }
+
+    //Testing security bug: 32588756
+    public void testEqualizer_getParamFreqRange_long() throws Exception {
+        testGetParam(MEDIA_LONG, Equalizer.PARAM_BAND_FREQ_RANGE, INVALID_BAND_ARRAY, mValue0,
+                mValue1);
+    }
+
+    //Testing security bug: 32448258
+    public void testEqualizer_getParamPresetName() throws Exception {
+        testParamPresetName(MEDIA_SHORT);
+    }
+
+    //Testing security bug: 32588016
+    public void testEqualizer_getParamPresetName_long() throws Exception {
+        testParamPresetName(MEDIA_LONG);
+    }
+
+    private void testParamPresetName(int media) {
+        final int command = Equalizer.PARAM_GET_PRESET_NAME;
+        for (int invalidBand : INVALID_BAND_ARRAY)
+        {
+            final byte testValue = 7;
+            byte reply[] = new byte[Equalizer.PARAM_STRING_SIZE_MAX];
+            Arrays.fill(reply, testValue);
+            if (!eqGetParam(media, command, invalidBand, reply)) {
+                fail("getParam PARAM_GET_PRESET_NAME did not complete successfully");
+            }
+            //Compare
+            if (invalidBand == PRESET_CUSTOM) {
+                final String expectedName = "Custom";
+                int length = 0;
+                while (reply[length] != 0) length++;
+                try {
+                    final String presetName =  new String(reply, 0, length,
+                            StandardCharsets.ISO_8859_1.name());
+                    assertEquals("getPresetName custom preset name failed", expectedName,
+                            presetName);
+                } catch (Exception e) {
+                    Log.w(TAG,"Problem creating reply string.");
+                }
+            } else {
+                for (int i = 0; i < reply.length; i++) {
+                    assertEquals(String.format("getParam should not change reply at byte %d", i),
+                            testValue, reply[i]);
+                }
+            }
+        }
+    }
+
+    //testing security bug: 32095626
+    public void testEqualizer_setParamBandLevel() throws Exception {
+        final int command = Equalizer.PARAM_BAND_LEVEL;
+        short[] value = { 1000 };
+        for (int invalidBand : INVALID_BAND_ARRAY)
+        {
+            if (!eqSetParam(MEDIA_SHORT, command, invalidBand, value)) {
+                fail("setParam PARAM_BAND_LEVEL did not complete successfully");
+            }
+        }
+    }
+
+    //testing security bug: 32585400
+    public void testEqualizer_setParamBandLevel_long() throws Exception {
+        final int command = Equalizer.PARAM_BAND_LEVEL;
+        short[] value = { 1000 };
+        for (int invalidBand : INVALID_BAND_ARRAY)
+        {
+            if (!eqSetParam(MEDIA_LONG, command, invalidBand, value)) {
+                fail("setParam PARAM_BAND_LEVEL did not complete successfully");
+            }
+        }
+    }
+
+    //testing security bug: 32705438
+    public void testEqualizer_getParamFreqRangeCommand_short() throws Exception {
+        assertTrue("testEqualizer_getParamFreqRangeCommand_short did not complete successfully",
+                eqGetParamFreqRangeCommand(MEDIA_SHORT));
+    }
+
+    //testing security bug: 32703959
+    public void testEqualizer_getParamFreqRangeCommand_long() throws Exception {
+        assertTrue("testEqualizer_getParamFreqRangeCommand_long did not complete successfully",
+                eqGetParamFreqRangeCommand(MEDIA_LONG));
+    }
+
+    private boolean eqGetParamFreqRangeCommand(int media) {
+        MediaPlayer mp = null;
+        Equalizer eq = null;
+        boolean status = false;
+        try {
+            mp = MediaPlayer.create(getInstrumentation().getContext(), getMediaId(media));
+            eq = new Equalizer(0 /*priority*/, mp.getAudioSessionId());
+
+            short band = 2;
+            int intSize = 4; //bytes
+
+            //baseline
+            int cmdCode = 8; // EFFECT_CMD_GET_PARAM
+            byte command[] = concatArrays(/*status*/ intToByteArray(0),
+                    /*psize*/ intToByteArray(2 * intSize),
+                    /*vsize*/ intToByteArray(2 * intSize),
+                    /*data[0]*/ intToByteArray(Equalizer.PARAM_BAND_FREQ_RANGE),
+                    /*data[1]*/ intToByteArray((int) band));
+
+            byte reply[] = new byte[command.length];
+
+            AudioEffect af = eq;
+            Object o = AudioEffect.class.getDeclaredMethod("command", int.class, byte[].class,
+                    byte[].class).invoke(af, cmdCode, command, reply);
+
+            int methodStatus = AudioEffect.ERROR;
+            if (o != null) {
+                methodStatus = Integer.valueOf(o.toString()).intValue();
+            }
+
+            assertTrue("Command expected to fail", methodStatus <= 0);
+            int sum = 0;
+            for (int i = 0; i < reply.length; i++) {
+                sum += Math.abs(reply[i]);
+            }
+
+            assertEquals("reply expected to be all zeros", sum, 0);
+            status = true;
+        } catch (Exception e) {
+            Log.w(TAG,"Problem testing eqGetParamFreqRangeCommand");
+            status = false;
+        } finally {
+            if (eq != null) {
+                eq.release();
+            }
+            if (mp != null) {
+                mp.release();
+            }
+        }
+        return status;
+    }
+
+    private boolean eqGetParam(int media, int command, int band, byte[] reply) {
+        MediaPlayer mp = null;
+        Equalizer eq = null;
+        boolean status = false;
+        try {
+            mp = MediaPlayer.create(getInstrumentation().getContext(), getMediaId(media));
+            eq = new Equalizer(0 /*priority*/, mp.getAudioSessionId());
+
+            AudioEffect af = eq;
+            int cmd[] = {command, band};
+
+            AudioEffect.class.getDeclaredMethod("getParameter", int[].class,
+                    byte[].class).invoke(af, cmd, reply);
+            status = true;
+        } catch (Exception e) {
+            Log.w(TAG,"Problem testing equalizer");
+            status = false;
+        } finally {
+            if (eq != null) {
+                eq.release();
+            }
+            if (mp != null) {
+                mp.release();
+            }
+        }
+        return status;
+    }
+
+    private boolean eqGetParam(int media, int command, int band, int[] reply) {
+        MediaPlayer mp = null;
+        Equalizer eq = null;
+        boolean status = false;
+        try {
+            mp = MediaPlayer.create(getInstrumentation().getContext(), getMediaId(media));
+            eq = new Equalizer(0 /*priority*/, mp.getAudioSessionId());
+
+            AudioEffect af = eq;
+            int cmd[] = {command, band};
+
+            AudioEffect.class.getDeclaredMethod("getParameter", int[].class,
+                    int[].class).invoke(af, cmd, reply);
+            status = true;
+        } catch (Exception e) {
+            Log.w(TAG,"Problem getting parameter from equalizer");
+            status = false;
+        } finally {
+            if (eq != null) {
+                eq.release();
+            }
+            if (mp != null) {
+                mp.release();
+            }
+        }
+        return status;
+    }
+
+    private void testGetParam(int media, int command, int[] bandArray, int value0, int value1) {
+        int reply[] = {value0, value1};
+        for (int invalidBand : INVALID_BAND_ARRAY)
+        {
+            if (!eqGetParam(media, command, invalidBand, reply)) {
+                fail(String.format("getParam for command %d did not complete successfully",
+                        command));
+            }
+            assertEquals("getParam should not change value0", value0, reply[0]);
+            assertEquals("getParam should not change value1", value1, reply[1]);
+        }
+    }
+
+    private boolean eqSetParam(int media, int command, int band, short[] value) {
+        MediaPlayer mp = null;
+        Equalizer eq = null;
+        boolean status = false;
+        try {
+            mp = MediaPlayer.create(getInstrumentation().getContext(),  getMediaId(media));
+            eq = new Equalizer(0 /*priority*/, mp.getAudioSessionId());
+
+            AudioEffect af = eq;
+            int cmd[] = {command, band};
+
+            AudioEffect.class.getDeclaredMethod("setParameter", int[].class,
+                    short[].class).invoke(af, cmd, value);
+            status = true;
+        } catch (Exception e) {
+            Log.w(TAG,"Problem setting parameter in equalizer");
+            status = false;
+        } finally {
+            if (eq != null) {
+                eq.release();
+            }
+            if (mp != null) {
+                mp.release();
+            }
+        }
+        return status;
+    }
+
+    private int getMediaId(int media) {
+        switch (media) {
+            default:
+            case MEDIA_SHORT:
+                return R.raw.good;
+            case MEDIA_LONG:
+                return R.raw.onekhzsine_90sec;
+        }
+    }
+
+    private static byte[] intToByteArray(int value) {
+        ByteBuffer converter = ByteBuffer.allocate(4);
+        converter.order(ByteOrder.nativeOrder());
+        converter.putInt(value);
+        return converter.array();
+    }
+
+    private static byte[] shortToByteArray(short value) {
+        ByteBuffer converter = ByteBuffer.allocate(2);
+        converter.order(ByteOrder.nativeOrder());
+        short sValue = (short) value;
+        converter.putShort(sValue);
+        return converter.array();
+    }
+
+    private static  byte[] concatArrays(byte[]... arrays) {
+        int len = 0;
+        for (byte[] a : arrays) {
+            len += a.length;
+        }
+        byte[] b = new byte[len];
+
+        int offs = 0;
+        for (byte[] a : arrays) {
+            System.arraycopy(a, 0, b, offs, a.length);
+            offs += a.length;
+        }
+        return b;
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/GraphicBufferInfoLeakTest.java b/tests/tests/security/src/android/security/cts/GraphicBufferInfoLeakTest.java
new file mode 100644
index 0000000..6005e37
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/GraphicBufferInfoLeakTest.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import junit.framework.TestCase;
+
+public class GraphicBufferInfoLeakTest extends TestCase {
+
+    static {
+        System.loadLibrary("ctssecurity_jni");
+    }
+
+    /**
+     * Check that IGraphicBufferConsumer::attachBuffer does not leak info in error case
+     */
+    public void test_attachBufferInfoLeak() throws Exception {
+        int slot = native_test_attachBufferInfoLeak();
+        assertTrue(String.format("Leaked slot 0x%08X", slot), slot == -1);
+    }
+
+    /**
+     * Check that IGraphicBufferProducer::queueBuffer does not leak info in error case
+     */
+    public void test_queueBufferInfoLeak() throws Exception {
+        int data = native_test_queueBufferInfoLeak();
+        assertTrue(String.format("Leaked buffer data 0x%08X", data), data == 0);
+    }
+
+    private static native int native_test_attachBufferInfoLeak();
+    private static native int native_test_queueBufferInfoLeak();
+}
diff --git a/tests/tests/security/src/android/security/cts/IMemoryHeapCorruptionTest.java b/tests/tests/security/src/android/security/cts/IMemoryHeapCorruptionTest.java
deleted file mode 100644
index 8eeea4e..0000000
--- a/tests/tests/security/src/android/security/cts/IMemoryHeapCorruptionTest.java
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.security.cts;
-
-import android.content.Context;
-import android.os.Binder;
-import android.os.IBinder;
-import android.os.Parcel;
-import android.os.ParcelFileDescriptor;
-import android.os.RemoteException;
-import android.test.AndroidTestCase;
-
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.IntBuffer;
-import java.util.Arrays;
-
-/**
- * Checks IMemory.cpp so that it should not return arbitrary memory locations (by checking against
- * the size of IMemoryHeap) which can lead to memory corruption or segmentation fault.
- */
-
-public class IMemoryHeapCorruptionTest extends AndroidTestCase {
-
-    static class MediaPlayerServiceOps {
-        static int CREATE = IBinder.FIRST_CALL_TRANSACTION;
-        static int CREATE_MEDIA_RECORDER = CREATE + 1;
-        static int CREATE_METADATA_RETRIEVER = CREATE_MEDIA_RECORDER + 1;
-        static int GET_OMX = CREATE_METADATA_RETRIEVER + 1;
-        static int MAKE_CRYPTO = GET_OMX + 1;
-    }
-
-    static class SubSample {
-        int mNumBytesOfClearData;
-        int mNumBytesOfEncryptedData;
-
-        public SubSample(int clearData, int encryptedData) {
-            mNumBytesOfClearData = clearData;
-            mNumBytesOfEncryptedData = encryptedData;
-        }
-
-        public SubSample() {
-            this(0, 0);
-        }
-    }
-
-    static interface IMemoryHeap {
-        ParcelFileDescriptor getHeapID();
-
-        int getSize();
-
-        int getFlags();
-
-        int getOffset();
-    }
-
-    static class IMemoryHeapStub extends Binder {
-        static final String DESCRIPTOR = "android.utils.IMemoryHeap";
-        private FileDescriptor mFd;
-        private int mOffset;
-        private int mSize;
-        private int mFlags;
-
-        public static final int READ_ONLY = 0x00000001;
-        static final int HEAD_ID = IBinder.FIRST_CALL_TRANSACTION;
-
-        public IMemoryHeapStub(FileDescriptor fd, int offset, int size, int flags) {
-            mFd = fd;
-            mOffset = offset;
-            mSize = size;
-            mFlags = flags;
-        }
-
-        @Override
-        public boolean onTransact(int code, Parcel data, Parcel reply,
-                int flags) throws RemoteException {
-            switch (code) {
-                case INTERFACE_TRANSACTION: {
-                    reply.writeString(DESCRIPTOR);
-                    return true;
-                }
-                case HEAD_ID: {
-                    data.enforceInterface(DESCRIPTOR);
-                    reply.writeFileDescriptor(mFd);
-                    reply.writeInt(mSize);
-                    reply.writeInt(mFlags);
-                    reply.writeInt(mOffset);
-                    reply.writeNoException();
-                    return true;
-                }
-            }
-            return super.onTransact(code, data, reply, flags);
-        }
-    }
-
-    static class IMemoryHeapProxy implements IMemoryHeap {
-        private boolean mLoaded;
-        private int mFlags;
-        private int mOffset;
-        private int mSize;
-        private ParcelFileDescriptor mHeapID;
-        private IBinder mBinder;
-        static int HEAP_ID = IBinder.FIRST_CALL_TRANSACTION;
-        static final String DESCRIPTOR = "android.utils.IMemoryHeap";
-
-        private void loadFromProxy() {
-            if (!mLoaded) {
-                mLoaded = true;
-                try {
-                    Parcel data = Parcel.obtain();
-                    Parcel reply = Parcel.obtain();
-                    data.writeInterfaceToken(DESCRIPTOR);
-                    mBinder.transact(HEAP_ID, data, reply, 0);
-                    mHeapID = reply.readFileDescriptor();
-                    mSize = reply.readInt();
-                    mFlags = reply.readInt();
-                    mOffset = reply.readInt();
-                } catch (RemoteException ex) {
-                }
-            }
-        }
-
-        @Override
-        public ParcelFileDescriptor getHeapID() {
-            loadFromProxy();
-            return mHeapID;
-        }
-
-        @Override
-        public int getSize() {
-            loadFromProxy();
-            return mSize;
-        }
-
-        @Override
-        public int getFlags() {
-            loadFromProxy();
-            return mFlags;
-        }
-
-        @Override
-        public int getOffset() {
-            loadFromProxy();
-            return mOffset;
-        }
-
-        public IMemoryHeapProxy(IBinder binder) {
-            mBinder = binder;
-        }
-    }
-
-    static interface IMemory {
-        IMemoryHeap getHeap();
-
-        int getSize();
-
-        int getOffset();
-    }
-
-    static class IMemoryStub extends Binder {
-        static String DESCRIPTOR = "android.utils.IMemory";
-        private IMemoryHeapStub mHeap;
-        private int mOffset;
-        private int mSize;
-
-        public IMemoryStub(FileDescriptor fd, int offset, int size, int heapoffset,
-                int heapsize, boolean readonly) {
-            mHeap = new IMemoryHeapStub(fd, heapoffset, heapsize,
-                    readonly ? IMemoryHeapStub.READ_ONLY : 0);
-            mOffset = offset;
-            mSize = size;
-        }
-
-        public IMemoryStub(FileDescriptor fd, int offset, int size) {
-            this(fd, offset, size, offset, size, true);
-        }
-
-        static final int GET_MEMORY = IBinder.FIRST_CALL_TRANSACTION;
-
-        @Override
-        public boolean onTransact(int code, Parcel data, Parcel reply,
-                int flags) throws android.os.RemoteException {
-            switch (code) {
-                case INTERFACE_TRANSACTION: {
-                    reply.writeString(DESCRIPTOR);
-                    return true;
-                }
-                case GET_MEMORY: {
-                    data.enforceInterface(DESCRIPTOR);
-                    reply.writeStrongBinder(mHeap);
-                    reply.writeInt(mOffset);
-                    reply.writeInt(mSize);
-                    reply.writeNoException();
-                    return true;
-                }
-            }
-            return super.onTransact(code, data, reply, flags);
-        }
-    }
-
-    static class CryptoProxy {
-        static int INIT_CHECK = IBinder.FIRST_CALL_TRANSACTION;
-        static int IS_CRYPTO_SUPPORTED = INIT_CHECK + 1;
-        static int CREATE_PLUGIN = IS_CRYPTO_SUPPORTED + 1;
-        static int DESTROY_PLUGIN = CREATE_PLUGIN + 1;
-        static int REQUIRES_SECURE_COMPONENT = DESTROY_PLUGIN + 1;
-        static int DECRYPT = REQUIRES_SECURE_COMPONENT + 1;
-
-        /**
-         * For these error values, please refer MediaErrors.h under the path
-         * /frameworks/av/include/media/stagefright/
-         */
-        static int DRM_ERROR_BASE = -2000;
-        static int ERROR_DRM_UNKNOWN = DRM_ERROR_BASE;
-        static int ERROR_DRM_LAST_USED_ERRORCODE = DRM_ERROR_BASE - 11;
-
-        private IBinder mBinder;
-
-        public CryptoProxy(IBinder binder) {
-            mBinder = binder;
-        }
-
-        public boolean getIsCryptoSupported(byte[] uuid) throws RemoteException {
-            Parcel data = Parcel.obtain();
-            Parcel reply = Parcel.obtain();
-            data.writeInterfaceToken("android.hardware.ICrypto");
-            writeRawBytes(data, uuid);
-            mBinder.transact(CryptoProxy.IS_CRYPTO_SUPPORTED, data, reply, 0);
-            return reply.readInt() != 0;
-        }
-
-        public int createPlugin(byte[] uuid, byte[] opaqueData) throws RemoteException {
-            Parcel data = Parcel.obtain();
-            Parcel reply = Parcel.obtain();
-            data.writeInterfaceToken("android.hardware.ICrypto");
-            writeRawBytes(data, uuid);
-            int length = opaqueData == null ? 0 : opaqueData.length;
-            data.writeInt(length);
-            if (length > 0) {
-                writeRawBytes(data, opaqueData);
-            }
-            mBinder.transact(CryptoProxy.CREATE_PLUGIN, data, reply, 0);
-            return reply.readInt();
-        }
-
-        byte[] decrypt(boolean secure, byte[] key, byte[] iv, int mode, IMemoryStub sharedBuffer,
-                int offset, SubSample[] subSamples, long dstPtr) throws RemoteException {
-            Parcel data = Parcel.obtain();
-            Parcel reply = Parcel.obtain();
-            data.writeInterfaceToken("android.hardware.ICrypto");
-            data.writeInt(secure ? 1 : 0);
-            data.writeInt(mode);
-            if (key == null) {
-                key = new byte[16];
-            }
-            if (iv == null) {
-                iv = new byte[16];
-            }
-            writeRawBytes(data, key);
-            writeRawBytes(data, iv);
-            int totalSize = 0;
-            for (SubSample ss : subSamples) {
-                totalSize += ss.mNumBytesOfEncryptedData;
-                totalSize += ss.mNumBytesOfClearData;
-            }
-            data.writeInt(totalSize);
-            data.writeStrongBinder(sharedBuffer);
-            data.writeInt(offset);
-            data.writeInt(subSamples.length);
-            for (SubSample ss : subSamples) {
-                data.writeInt(ss.mNumBytesOfClearData);
-                data.writeInt(ss.mNumBytesOfEncryptedData);
-            }
-            if (secure) {
-                data.writeLong(dstPtr);
-            }
-            mBinder.transact(DECRYPT, data, reply, 0);
-            int length = reply.readInt();
-
-            /**
-             * If the length value returned is negative and within the error range, this means the
-             * call to mBinder.transact didn't go through and hence raise a Binder
-             * remote-invocation error. For more information, refer decrypt method
-             * in ICrypto.cpp under the path /frameworks/av/media/libmedia/
-             */
-            if ((length > ERROR_DRM_LAST_USED_ERRORCODE) && (length <= ERROR_DRM_UNKNOWN)) {
-                throw new RemoteException(readCString(reply));
-            }
-
-            if (!secure && length > 0) {
-                    return readRawBytes(reply, length);
-            }
-
-            return new byte[0];
-        }
-    }
-
-    static int[] convertBytesToInts(byte[] byteArray) {
-        IntBuffer intBuf = ByteBuffer.wrap(byteArray).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
-        int[] array = new int[intBuf.remaining()];
-        intBuf.get(array);
-        return array;
-    }
-
-    static void writeRawBytes(Parcel data, byte[] bytes) {
-        int len = bytes.length;
-        if ((len & 3) != 0) {
-            bytes = Arrays.copyOf(bytes, (len + 3) & ~3);
-        }
-        for (int i : convertBytesToInts(bytes)) {
-            data.writeInt(i);
-        }
-    }
-
-    static byte[] convertIntToBytes(int i) {
-        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
-        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
-        byteBuffer.putInt(0, i);
-        byte[] ret = new byte[4];
-        byteBuffer.get(ret);
-        return ret;
-    }
-
-    static String readCString(Parcel data) {
-        StringBuilder builder = new StringBuilder();
-        while (data.dataAvail() > 4) {
-            int len;
-            byte[] bytes = convertIntToBytes(data.readInt());
-            for (len = 0; len < 4; ++len) {
-                if (bytes[len] == 0) {
-                    break;
-                }
-            }
-            builder.append(new String(bytes, 0, len));
-            if (len < 4) {
-                break;
-            }
-        }
-        return builder.toString();
-    }
-
-    static byte[] readRawBytes(Parcel data, int length) {
-        int readLen = (length + 3) & ~3;
-        byte[] ret = new byte[length];
-        ByteBuffer byteBuffer = ByteBuffer.allocate(readLen);
-        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
-        for (int i = 0; i < readLen / 4; ++i) {
-            byteBuffer.putInt(data.readInt());
-        }
-        byteBuffer.position(0);
-        byteBuffer.get(ret, 0, length);
-        return ret;
-    }
-
-    static IBinder getService(String service) throws ClassNotFoundException, NoSuchMethodException,
-            InvocationTargetException, IllegalAccessException {
-        Class mClass = Class.forName("android.os.ServiceManager");
-        Method mMethod = mClass.getMethod("getService", String.class);
-        return (IBinder) mMethod.invoke(null, service);
-    }
-
-    public void mediaPlayerTest(Context ctx) throws Throwable {
-        IBinder serviceBinder = getService("media.player");
-        serviceBinder.getInterfaceDescriptor();
-        Parcel data = Parcel.obtain();
-        Parcel reply = Parcel.obtain();
-        data.writeInterfaceToken("android.media.IMediaPlayerService");
-        serviceBinder.transact(MediaPlayerServiceOps.MAKE_CRYPTO, data, reply, 0);
-        IBinder crypto = reply.readStrongBinder();
-        crypto.getInterfaceDescriptor();
-
-        /**
-         * Crypto schemes are assigned 16 byte UUIDs and they can be used to query if a given
-         * scheme is supported on the device.
-         * The following bytes indicate the UUID of the crypto scheme.
-         */
-        byte cryptoSchemeUUID[] = {
-                (byte) 0x10, (byte) 0x77, (byte) 0xEF, (byte) 0xEC, (byte) 0xC0, (byte) 0xB2,
-                (byte) 0x4D, (byte) 0x02, (byte) 0xAC, (byte) 0xE3, (byte) 0x3C, (byte) 0x1E,
-                (byte) 0x52, (byte) 0xE2, (byte) 0xFB, (byte) 0x4B
-        };
-        CryptoProxy cryptoProxy = new CryptoProxy(crypto);
-        cryptoProxy.getIsCryptoSupported(cryptoSchemeUUID);
-        cryptoProxy.createPlugin(cryptoSchemeUUID, null);
-        FileOutputStream fos = ctx.openFileOutput("dummy.bin", 0);
-        byte[] byteArray = new byte[10];
-        for (int i = 0; i < byteArray.length; ++i) {
-            byteArray[i] = (byte) i;
-        }
-        fos.write(byteArray);
-        fos.close();
-        FileInputStream fis = ctx.openFileInput("dummy.bin");
-        IMemoryStub sharedBuffer = new IMemoryStub(fis.getFD(), -1024 * 1024 * 1024,
-                0xFFFFFFFF, 0, 10, true);
-        SubSample[] subSamples = new SubSample[1];
-        subSamples[0] = new SubSample(10, 0);
-        cryptoProxy.decrypt(false, null, null, 0, sharedBuffer, 0x1234, subSamples, 0);
-    }
-
-    public void testIMemoryElevationOfPrivilegeExploit() {
-        try {
-            mediaPlayerTest(getContext());
-        } catch (Throwable throwable) {
-            fail("Device is vulnerable to bug #26877992!! For more information, refer - " +
-                    "https://android.googlesource.com/platform/frameworks/native/+/" +
-                    "f3199c228aced7858b75a8070b8358c155ae0149");
-        }
-    }
-}
\ No newline at end of file
diff --git a/tests/tests/security/src/android/security/cts/IsolatedProcessTest.java b/tests/tests/security/src/android/security/cts/IsolatedProcessTest.java
new file mode 100644
index 0000000..ac264d0
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/IsolatedProcessTest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.security.cts;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.security.cts.IIsolatedService;
+import android.security.cts.IsolatedService;
+import android.test.AndroidTestCase;
+import android.util.Log;
+import com.android.internal.util.ArrayUtils;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import junit.framework.Assert;
+
+public class IsolatedProcessTest extends AndroidTestCase {
+    static final String TAG = IsolatedProcessTest.class.getSimpleName();
+
+    private static final long BIND_SERVICE_TIMEOUT = 5000;
+
+    // No service other than these should be visible to an isolated process
+    private static final String[] SERVICES_ALLOWED_TO_ISOLATED_PROCESS = {
+            "package",
+            Context.ACTIVITY_SERVICE
+    };
+    // Arbitrary set of services to test accessibility from an isolated process
+    private static final String[] RESTRICTED_SERVICES_TO_TEST = {
+            Context.ALARM_SERVICE,
+            Context.WINDOW_SERVICE,
+            Context.POWER_SERVICE
+    };
+
+    private CountDownLatch mLatch;
+    private IIsolatedService mService;
+    private final ServiceConnection mServiceConnection = new ServiceConnection() {
+
+        @Override
+        public void onServiceDisconnected(ComponentName name) {
+            Log.e(TAG, "Isolated service " + name + " died abruptly");
+        }
+
+        @Override
+        public void onServiceConnected(ComponentName name, IBinder service) {
+            mService = IIsolatedService.Stub.asInterface(service);
+            mLatch.countDown();
+        }
+    };
+
+    @Override
+    public void setUp() throws InterruptedException {
+        mLatch = new CountDownLatch(1);
+        Intent serviceIntent = new Intent(mContext, IsolatedService.class);
+        mContext.bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
+        Assert.assertTrue("Timed out while waiting to bind to isolated service",
+                mLatch.await(BIND_SERVICE_TIMEOUT, TimeUnit.MILLISECONDS));
+    }
+
+    public void testGetCachedServicesFromIsolatedService() throws RemoteException {
+        String[] cachedServices = mService.getCachedSystemServices();
+        for (String serviceName : cachedServices) {
+            Assert.assertTrue(serviceName + " should not be accessbible from an isolated process",
+                    ArrayUtils.contains(SERVICES_ALLOWED_TO_ISOLATED_PROCESS, serviceName));
+        }
+    }
+
+    public void testGetServiceFromIsolatedService() throws RemoteException {
+        for (String serviceName : RESTRICTED_SERVICES_TO_TEST) {
+            IBinder service = mService.getSystemService(serviceName);
+            Assert.assertNull(serviceName + " should not be accessible from an isolated process",
+                    service);
+        }
+    }
+
+    @Override
+    public void tearDown() {
+        mContext.unbindService(mServiceConnection);
+    }
+
+}
diff --git a/tests/tests/security/src/android/security/cts/IsolatedService.java b/tests/tests/security/src/android/security/cts/IsolatedService.java
new file mode 100644
index 0000000..28d2a65
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/IsolatedService.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import android.app.Service;
+import android.content.Intent;
+import android.os.IBinder;
+import android.util.Log;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+public class IsolatedService extends Service {
+
+    private static final String TAG = IsolatedService.class.getSimpleName();
+    private static final String SERVICE_MANAGER_CLASS_NAME = "android.os.ServiceManager";
+    private static final String SERVICE_MANAGER_INTERNAL_CACHE_NAME = "sCache";
+    private static final String GET_SERVICE_METHOD_NAME = "getService";
+
+    private String[] getServicesCachedInServiceManager() {
+        ArrayList<String> cachedServices = new ArrayList<String>();
+        try {
+            Class<?> serviceManager = Class.forName(SERVICE_MANAGER_CLASS_NAME);
+            Field cacheField = serviceManager.getDeclaredField(SERVICE_MANAGER_INTERNAL_CACHE_NAME);
+            cacheField.setAccessible(true);
+            HashMap<String, IBinder> sCache = (HashMap<String, IBinder>) cacheField.get(null);
+            for (Map.Entry<String, IBinder> serviceEntry : sCache.entrySet()) {
+                if (serviceEntry.getValue() != null) {
+                    cachedServices.add(serviceEntry.getKey());
+                }
+            }
+        } catch (ClassCastException | ReflectiveOperationException exc) {
+            Log.w(TAG, "Unable to retrieve service manager cache via reflection ", exc);
+        }
+        return cachedServices.toArray(new String[cachedServices.size()]);
+    }
+
+    private IBinder getServiceFromServiceManager(String serviceName) {
+        try {
+            Class<?> serviceManager = Class.forName(SERVICE_MANAGER_CLASS_NAME);
+            Method getServiceMethod =
+                    serviceManager.getDeclaredMethod(GET_SERVICE_METHOD_NAME, String.class);
+            IBinder service = (IBinder) getServiceMethod.invoke(null, serviceName);
+            return service;
+        } catch (ClassCastException | ReflectiveOperationException exc) {
+            Log.w(TAG, "Unable to call ServiceManager.getService() ", exc);
+        }
+        return null;
+    }
+
+    private final IIsolatedService.Stub mBinder = new IIsolatedService.Stub() {
+
+        public String[] getCachedSystemServices() {
+            return getServicesCachedInServiceManager();
+        }
+
+        public IBinder getSystemService(String serviceName) {
+            return getServiceFromServiceManager(serviceName);
+        }
+    };
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return mBinder;
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/ListeningPortsTest.java b/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
index 87e957d..54fa406 100644
--- a/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
+++ b/tests/tests/security/src/android/security/cts/ListeningPortsTest.java
@@ -18,11 +18,14 @@
 
 import android.content.pm.PackageManager;
 import android.test.AndroidTestCase;
+import android.util.Log;
 import junit.framework.AssertionFailedError;
 
 import java.io.File;
 import java.io.IOException;
 import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
 import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -37,15 +40,31 @@
  * is considered a security best practice.
  */
 public class ListeningPortsTest extends AndroidTestCase {
+    private static final String TAG = "ListeningPortsTest";
+
+    private static final int CONN_TIMEOUT_IN_MS = 5000;
 
     /** Ports that are allowed to be listening. */
     private static final List<String> EXCEPTION_PATTERNS = new ArrayList<String>(6);
 
     static {
         // IPv4 exceptions
-        EXCEPTION_PATTERNS.add("0.0.0.0:5555");   // emulator port
-        EXCEPTION_PATTERNS.add("10.0.2.15:5555"); // net forwarding for emulator
-        EXCEPTION_PATTERNS.add("127.0.0.1:5037"); // adb daemon "smart sockets"
+        // Patterns containing ":" are allowed address port combinations
+        // Pattterns contains " " are allowed address UID combinations
+        // Patterns containing both are allowed address, port, and UID combinations
+        EXCEPTION_PATTERNS.add("0.0.0.0:5555");     // emulator port
+        EXCEPTION_PATTERNS.add("0.0.0.0:9101");     // verified ports
+        EXCEPTION_PATTERNS.add("0.0.0.0:9551");     // verified ports
+        EXCEPTION_PATTERNS.add("0.0.0.0:9552");     // verified ports
+        EXCEPTION_PATTERNS.add("10.0.2.15:5555");   // net forwarding for emulator
+        EXCEPTION_PATTERNS.add("127.0.0.1:5037");   // adb daemon "smart sockets"
+        EXCEPTION_PATTERNS.add("0.0.0.0 1020");     // used by the cast receiver
+        EXCEPTION_PATTERNS.add("0.0.0.0 10000");    // used by the cast receiver
+        EXCEPTION_PATTERNS.add("127.0.0.1 10000");  // used by the cast receiver
+        EXCEPTION_PATTERNS.add(":: 1002");          // used by remote control
+        EXCEPTION_PATTERNS.add(":: 1020");          // used by remote control
+        //no current patterns involve address, port and UID combinations
+        //Example for when necessary: EXCEPTION_PATTERNS.add("0.0.0.0:5555 10000")
     }
 
     /**
@@ -185,10 +204,16 @@
         List<ParsedProcEntry> entries = ParsedProcEntry.parse(procFilePath);
         for (ParsedProcEntry entry : entries) {
             String addrPort = entry.localAddress.getHostAddress() + ':' + entry.port;
+            String addrUid = entry.localAddress.getHostAddress() + ' ' + entry.uid;
+            String addrPortUid = addrPort + ' ' + entry.uid;
 
             if (isPortListening(entry.state, isTcp)
-                && !isException(addrPort)
-                && (!entry.localAddress.isLoopbackAddress() ^ loopback)) {
+                    && !(isException(addrPort) || isException(addrUid) || isException(addrPortUid))
+                    && (!entry.localAddress.isLoopbackAddress() ^ loopback)) {
+                if (isTcp && !isTcpConnectable(entry.localAddress, entry.port)) {
+                    continue;
+                }
+
                 errors += "\nFound port listening on addr="
                         + entry.localAddress.getHostAddress() + ", port="
                         + entry.port + ", UID=" + entry.uid
@@ -210,6 +235,33 @@
         return Arrays.asList(packages).toString();
     }
 
+    private boolean isTcpConnectable(InetAddress address, int port) {
+        Socket socket = new Socket();
+
+        try {
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                Log.d(TAG, "Trying to connect " + address + ":" + port);
+            }
+            socket.connect(new InetSocketAddress(address, port), CONN_TIMEOUT_IN_MS);
+        } catch (IOException ioe) {
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                Log.d(TAG, "Unable to connect:" + ioe);
+            }
+            return false;
+        } finally {
+            try {
+                socket.close();
+            } catch (IOException closeError) {
+                Log.e(TAG, "Unable to close socket: " + closeError);
+            }
+        }
+
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, address + ":" + port + " is connectable.");
+        }
+        return true;
+    }
+
     private static boolean isException(String localAddress) {
         return isPatternMatch(EXCEPTION_PATTERNS, localAddress);
     }
diff --git a/tests/tests/security/src/android/security/cts/MediaCodecListTest.java b/tests/tests/security/src/android/security/cts/MediaCodecListTest.java
deleted file mode 100644
index 4a6a87d..0000000
--- a/tests/tests/security/src/android/security/cts/MediaCodecListTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.security.cts;
-
-import junit.framework.TestCase;
-
-public class MediaCodecListTest extends TestCase {
-
-    static {
-        System.loadLibrary("ctssecurity_jni");
-    }
-
-    public void testMediaCodecList() throws Exception {
-        assertTrue("Device is vulnerable to CVE-2015-6620. "
-                        + "Please apply the security patch at "
-                        + "https://android.googlesource.com/"
-                        + "platform%2Fframeworks%2Fav/"
-                        + "+/77c185d5499d6174e7a97b3e1512994d3a803151",
-                doCodecInfoTest());
-    }
-
-    /**
-     * ANDROID-24445127 / CVE-2015-6620
-     *
-     * Returns true if the device is patched against the getCodecInfo().
-     *
-     * More information on this vulnreability is available at
-     * https://android.googlesource.com/platform%2Fframeworks%2Fav
-     * /a+/77c185d5499d6174e7a97b3e1512994d3a803151/
-     */
-    private static native boolean doCodecInfoTest();
-}
diff --git a/tests/tests/security/src/android/security/cts/MediaServerCrashTest.java b/tests/tests/security/src/android/security/cts/MediaServerCrashTest.java
index ff31208..5ee1ae5 100644
--- a/tests/tests/security/src/android/security/cts/MediaServerCrashTest.java
+++ b/tests/tests/security/src/android/security/cts/MediaServerCrashTest.java
@@ -90,6 +90,31 @@
         }
     }
 
+    public void testInvalidMidiNullPointerAccess() throws Exception {
+        testIfMediaServerDied(R.raw.midi_crash);
+    }
+
+    private void testIfMediaServerDied(int res) throws Exception {
+        AssetFileDescriptor afd = getContext().getResources().openRawResourceFd(res);
+        mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
+        afd.close();
+        try {
+            mMediaPlayer.prepareAsync();
+            if (!mOnPrepareCalled.block(5000)) {
+                Log.w(TAG, "testIfMediaServerDied: Timed out waiting for prepare");
+                return;
+            }
+            mMediaPlayer.start();
+            if (!mOnCompletionCalled.block(5000)) {
+                Log.w(TAG, "testIfMediaServerDied: Timed out waiting for Error/Completion");
+            }
+        } catch (Exception e) {
+            Log.w(TAG, "playback failed", e);
+        } finally {
+            mMediaPlayer.release();
+        }
+    }
+
     public void testDrmManagerClientReset() throws Exception {
         checkIfMediaServerDiedForDrm(R.raw.drm_uaf);
     }
diff --git a/tests/tests/security/src/android/security/cts/SkICOImageDecoderTest.java b/tests/tests/security/src/android/security/cts/SkICOImageDecoderTest.java
deleted file mode 100644
index 717772a..0000000
--- a/tests/tests/security/src/android/security/cts/SkICOImageDecoderTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.security.cts;
-
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.test.AndroidTestCase;
-
-import java.io.InputStream;
-
-import com.android.cts.security.R;
-
-public class SkICOImageDecoderTest extends AndroidTestCase {
-
-    /**
-     * Verifies that the device is not vulnerable to ANDROID-17265206: Buffer overflow in libskia
-     */
-    public void testAllocateJavaPixelRefOverflow() {
-        InputStream exploitImage = mContext.getResources().openRawResource(
-                R.raw.skia_sigsegv_in_skicoimagedecoder);
-        /**
-         * Pass/Fail not required as the target method for the exploit
-         * results in SIGSEGV (Segmentation fault) which will lead to process crash
-         */
-        BitmapFactory.decodeStream(exploitImage);
-    }
-}
\ No newline at end of file
diff --git a/tests/tests/security/src/android/security/cts/SkiaJpegDecodingTest.java b/tests/tests/security/src/android/security/cts/SkiaJpegDecodingTest.java
deleted file mode 100644
index 64a9143..0000000
--- a/tests/tests/security/src/android/security/cts/SkiaJpegDecodingTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.security.cts;
-
-import android.app.Activity;
-import android.test.ActivityInstrumentationTestCase2;
-
-public class SkiaJpegDecodingTest extends
-        ActivityInstrumentationTestCase2<SkiaJpegDecodingActivity> {
-    private Activity mActivity;
-
-    public SkiaJpegDecodingTest() {
-        super(SkiaJpegDecodingActivity.class);
-    }
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mActivity = getActivity();
-        assertNotNull("Failed to get the activity instance", mActivity);
-    }
-
-    public void testLibskiaOverFlowJpegProcessing() {
-        /**
-         * This is an empty test case. The activity attached with this class
-         * loads a corrupt JPEG Image on an ImageView. On a patched device
-         * this will work but on an unpatched device it will crash.
-         */
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        if (mActivity != null) {
-            mActivity.finish();
-        }
-        super.tearDown();
-    }
-}
diff --git a/tests/tests/security/src/android/security/cts/StagefrightFoundationTest.java b/tests/tests/security/src/android/security/cts/StagefrightFoundationTest.java
new file mode 100644
index 0000000..9999d88
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/StagefrightFoundationTest.java
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+package android.security.cts;
+
+import junit.framework.TestCase;
+
+public class StagefrightFoundationTest extends TestCase {
+
+    static {
+        System.loadLibrary("ctssecurity_jni");
+    }
+
+    /**
+     * Checks that IEffect::command() cannot leak data.
+     */
+    public void test_aMessageFromParcel() throws Exception {
+        assertTrue(native_test_aMessageFromParcel());
+    }
+
+    private static native boolean native_test_aMessageFromParcel();
+}
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index eba41f8..afc0ae4 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 The Android Open Source Project
+ * 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.
@@ -60,6 +60,14 @@
     public StagefrightTest() {
     }
 
+    public void testStagefright_bug_31647370() throws Exception {
+        doStagefrightTest(R.raw.bug_31647370);
+    }
+
+    public void testStagefright_bug_32577290() throws Exception {
+        doStagefrightTest(R.raw.bug_32577290);
+    }
+
     public void testStagefright_cve_2015_1538_1() throws Exception {
         doStagefrightTest(R.raw.cve_2015_1538_1);
     }
@@ -100,26 +108,34 @@
         doStagefrightTest(R.raw.cve_2015_3829);
     }
 
-    public void testStagefright_cve_2015_3836() throws Exception {
-        doStagefrightTest(R.raw.cve_2015_3836);
-    }
-
     public void testStagefright_cve_2015_3864() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3864);
     }
 
-    public void testStagefright_cve_2015_3864_b23034759() throws Exception {
-        doStagefrightTest(R.raw.cve_2015_3864_b23034759);
-    }
-
     public void testStagefright_cve_2015_6598() throws Exception {
         doStagefrightTest(R.raw.cve_2015_6598);
     }
 
+    public void testStagefright_bug_32873375() throws Exception {
+        doStagefrightTest(R.raw.bug_32873375);
+    }
+
     public void testStagefright_bug_26366256() throws Exception {
         doStagefrightTest(R.raw.bug_26366256);
     }
 
+    public void testStagefright_bug_25765591() throws Exception {
+        doStagefrightTest(R.raw.bug_25765591);
+    }
+
+    public void testStagefright_bug_25812590() throws Exception {
+        doStagefrightTest(R.raw.bug_25812590);
+    }
+
+    public void testStagefright_bug_26070014() throws Exception {
+        doStagefrightTest(R.raw.bug_26070014);
+    }
+
     public void testStagefright_cve_2015_3867() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3867);
     }
@@ -128,6 +144,10 @@
         doStagefrightTest(R.raw.cve_2015_3869);
     }
 
+    public void testStagefright_bug_32322258() throws Exception {
+        doStagefrightTest(R.raw.bug_32322258);
+    }
+
     public void testStagefright_cve_2015_3873_b_23248776() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3873_b_23248776);
     }
@@ -148,26 +168,30 @@
         doStagefrightTest(R.raw.cve_2015_3873_b_21814993);
     }
 
-    public void testStagefright_bug_25812590() throws Exception {
-        doStagefrightTest(R.raw.bug_25812590);
-    }
-
-    public void testStagefright_bug_26070014() throws Exception {
-        doStagefrightTest(R.raw.bug_26070014);
-    }
-
-    public void testStagefright_cve_2015_6608_b_23680780() throws Exception {
-        doStagefrightTest(R.raw.cve_2015_6608_b_23680780);
+    public void testStagefright_bug_32915871() throws Exception {
+        doStagefrightTest(R.raw.bug_32915871);
     }
 
     public void testStagefright_bug_28333006() throws Exception {
         doStagefrightTest(R.raw.bug_28333006);
     }
 
-   public void testStagefright_bug_14388161() throws Exception {
+    public void testStagefright_bug_14388161() throws Exception {
         doStagefrightTestMediaPlayer(R.raw.bug_14388161);
     }
 
+    public void testStagefright_cve_2016_3755() throws Exception {
+        doStagefrightTest(R.raw.cve_2016_3755);
+    }
+
+    public void testStagefright_cve_2016_3878_b_29493002() throws Exception {
+        doStagefrightTest(R.raw.cve_2016_3878_b_29493002);
+    }
+
+    public void testStagefright_cve_2016_2429_b_27211885() throws Exception {
+        doStagefrightTest(R.raw.cve_2016_2429_b_27211885);
+    }
+
     public void testStagefright_bug_27855419_CVE_2016_2463() throws Exception {
         doStagefrightTest(R.raw.bug_27855419);
     }
@@ -313,6 +337,7 @@
         assertFalse("Device *IS* vulnerable to " + cve,
                     mpcl.waitForError() == MediaPlayer.MEDIA_ERROR_SERVER_DIED);
         t.stopLooper();
+        t.join(); // wait for thread to exit so we're sure the player was released
     }
 
     private void doStagefrightTestMediaCodec(final int rid) throws Exception {
diff --git a/tests/tests/security/src/android/security/cts/VisualizerEffectTest.java b/tests/tests/security/src/android/security/cts/VisualizerEffectTest.java
new file mode 100644
index 0000000..7067242
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/VisualizerEffectTest.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import junit.framework.TestCase;
+
+import android.content.Context;
+import android.media.audiofx.AudioEffect;
+import android.media.MediaPlayer;
+import android.media.audiofx.Visualizer;
+import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
+import android.util.Log;
+import com.android.cts.security.R;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.UUID;
+
+public class VisualizerEffectTest extends InstrumentationTestCase {
+    private String TAG = "VisualizerEffectTest";
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+    }
+
+    //Testing security bug: 30229821
+    public void testVisualizer_MalformedConstructor() throws Exception {
+        final String VISUALIZER_TYPE = "e46b26a0-dddd-11db-8afd-0002a5d5c51b";
+        final int VISUALIZER_CMD_MEASURE = 0x10001;
+
+        AudioEffect.Descriptor[] descriptors = AudioEffect.queryEffects();
+        int i, visualizerIndex = -1;
+        for (i = 0; i < descriptors.length; ++i) {
+            AudioEffect.Descriptor descriptor = descriptors[i];
+            if (descriptor.type.compareTo(UUID.fromString(VISUALIZER_TYPE)) == 0) {
+                visualizerIndex = i;
+
+                AudioEffect ae = null;
+                MediaPlayer mp = null;
+                try {
+                    mp = MediaPlayer.create(getInstrumentation().getContext(), R.raw.good);
+                    Constructor ct = AudioEffect.class.getConstructor(UUID.class, UUID.class,
+                            int.class, int.class);
+                    ae = (AudioEffect) ct.newInstance(descriptors[visualizerIndex].type,
+                            descriptors[visualizerIndex].uuid, 0, mp.getAudioSessionId());
+                    Method command = AudioEffect.class.getDeclaredMethod("command", int.class,
+                            byte[].class, byte[].class);
+                    Integer ret = (Integer) command.invoke(ae, new Object[]{VISUALIZER_CMD_MEASURE,
+                            new byte[0], new byte[0]});
+                    assertTrue("Audio server might have crashed", ret != -7);
+                } catch (Exception e) {
+                    Log.w(TAG,"Problem testing visualizer");
+                } finally {
+                    if (ae != null) {
+                        ae.release();
+                    }
+                    if (mp != null) {
+                        mp.release();
+                    }
+                }
+            }
+        }
+
+        if (visualizerIndex == -1) {
+            Log.w(TAG,"No visualizer found to test");
+        }
+    }
+}
diff --git a/tests/tests/telecom/AndroidManifest.xml b/tests/tests/telecom/AndroidManifest.xml
index 359923d..b57e0b6 100644
--- a/tests/tests/telecom/AndroidManifest.xml
+++ b/tests/tests/telecom/AndroidManifest.xml
@@ -42,7 +42,6 @@
 
         <service android:name="android.telecom.cts.MockInCallService"
             android:permission="android.permission.BIND_INCALL_SERVICE" >
-            <meta-data android:name="android.telecom.IN_CALL_SERVICE_UI" android:value="true" />
             <intent-filter>
                 <action android:name="android.telecom.InCallService"/>
             </intent-filter>
diff --git a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
index 052e820..d874dbf 100644
--- a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
+++ b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
@@ -297,7 +297,6 @@
         if (mInCallCallbacks.getService() != null) {
             currentCallCount = mInCallCallbacks.getService().getCallCount();
         }
-        int currentConnectionCount = getNumberOfConnections();
         placeNewCallWithPhoneAccount(extras, videoState);
 
         try {
@@ -312,20 +311,6 @@
         assertEquals("InCallService should contain 1 more call after adding a call.",
                 currentCallCount + 1,
                 mInCallCallbacks.getService().getCallCount());
-
-        // The connectionService.lock is released in
-        // MockConnectionService#onCreateOutgoingConnection, however the connection will not
-        // actually be added to the list of connections in the ConnectionService until shortly
-        // afterwards.  So there is still a potential for the lock to be released before it would
-        // be seen by calls to ConnectionService#getAllConnections().
-        // We will wait here until the list of connections includes one more connection to ensure
-        // that placing the call has fully completed.
-        final int expectedConnectionCount = currentConnectionCount + 1;
-        assertCSConnections(expectedConnectionCount);
-    }
-
-    int getNumberOfConnections() {
-        return CtsConnectionService.getAllConnectionsFromTelecom().size();
     }
 
     MockConnection verifyConnectionForOutgoingCall() {
@@ -535,24 +520,6 @@
     );
     }
 
-    void assertCSConnections(final int numConnections) {
-        waitUntilConditionIsTrueOrTimeout(new Condition() {
-                                              @Override
-                                              public Object expected() {
-                                                  return numConnections;
-                                              }
-
-                                              @Override
-                                              public Object actual() {
-                                                  return CtsConnectionService
-                                                          .getAllConnectionsFromTelecom()
-                                                          .size();
-                                              }
-                                          },
-                WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
-                "ConnectionService should contain " + numConnections + " connections."
-        );
-    }
 
     void assertNumConnections(final MockConnectionService connService, final int numConnections) {
         waitUntilConditionIsTrueOrTimeout(new Condition() {
diff --git a/tests/tests/telecom/src/android/telecom/cts/CtsConnectionService.java b/tests/tests/telecom/src/android/telecom/cts/CtsConnectionService.java
index e820e10..2364986 100644
--- a/tests/tests/telecom/src/android/telecom/cts/CtsConnectionService.java
+++ b/tests/tests/telecom/src/android/telecom/cts/CtsConnectionService.java
@@ -29,7 +29,6 @@
 import android.util.Log;
 
 import java.util.Collection;
-import java.util.Collections;
 
 /**
  * This is the official ConnectionService for Telecom's CTS App. Since telecom requires that a
@@ -155,9 +154,6 @@
 
     public static Collection<Connection> getAllConnectionsFromTelecom() {
         synchronized(sLock) {
-            if (sTelecomConnectionService == null) {
-                return Collections.EMPTY_LIST;
-            }
             return sTelecomConnectionService.getAllConnections();
         }
     }
diff --git a/tests/tests/uirendering/res/layout/simple_shadow_layout.xml b/tests/tests/uirendering/res/layout/simple_shadow_layout.xml
index f97974b..2f21df0 100644
--- a/tests/tests/uirendering/res/layout/simple_shadow_layout.xml
+++ b/tests/tests/uirendering/res/layout/simple_shadow_layout.xml
@@ -23,4 +23,4 @@
         android:translationY="25px"
         android:elevation="10dp"
         android:background="#fff" />
-</FrameLayout>
+</FrameLayout>
\ No newline at end of file
diff --git a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/ShadowTests.java b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/ShadowTests.java
index 5c06f0f..ffcbf30 100644
--- a/tests/tests/uirendering/src/android/uirendering/cts/testclasses/ShadowTests.java
+++ b/tests/tests/uirendering/src/android/uirendering/cts/testclasses/ShadowTests.java
@@ -27,10 +27,10 @@
 public class ShadowTests extends ActivityTestBase {
     @SmallTest
     public void testShadowLayout() {
-        int shadowColorValue = 0xD7;
+        int shadowColorValue = 0xDB;
         // Android TV theme overrides shadow opacity to be darker.
         if (getActivity().getOnTv()) {
-            shadowColorValue = 0xB7;
+            shadowColorValue = 0xBB;
         }
         // Use a higher threshold (36) than default value (20);
         SamplePointVerifier verifier = new SamplePointVerifier(
@@ -53,4 +53,4 @@
                 .addLayout(R.layout.simple_shadow_layout, null, true/* HW only */)
                 .runWithVerifier(verifier);
     }
-}
+}
\ No newline at end of file
diff --git a/tests/tests/webkit/assets/webkit/jsunload.html b/tests/tests/webkit/assets/webkit/jsunload.html
index f016eb7..fb0673e 100644
--- a/tests/tests/webkit/assets/webkit/jsunload.html
+++ b/tests/tests/webkit/assets/webkit/jsunload.html
@@ -19,7 +19,7 @@
     </head>
     <script type="text/javascript">
         function fireUnload() {
-            return "this message will be a hardcoded string in chrome.";
+            return "testOnJsBeforeUnload";
         }
         window.onbeforeunload = fireUnload;
     </script>
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebChromeClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebChromeClientTest.java
index 424d856..150fd86 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebChromeClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebChromeClientTest.java
@@ -198,7 +198,7 @@
         runWindowTest(false);
     }
 
-    public void testOnJsBeforeUnloadIsCalled() throws Exception {
+    public void testOnJsBeforeUnload() throws Exception {
         if (!NullWebViewUtils.isWebViewAvailable()) {
             return;
         }
@@ -221,6 +221,7 @@
                 return webChromeClient.hadOnJsBeforeUnload();
             }
         }.run();
+        assertEquals(webChromeClient.getMessage(), "testOnJsBeforeUnload");
     }
 
     public void testOnJsAlert() throws Exception {
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
index 3b6db7c..0697429 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewClientTest.java
@@ -34,14 +34,11 @@
 import android.webkit.WebView;
 import android.webkit.WebViewClient;
 import android.webkit.cts.WebViewOnUiThread.WaitForLoadedClient;
-import android.util.Pair;
 
 import java.io.ByteArrayInputStream;
 import java.nio.charset.StandardCharsets;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.List;
-import java.util.ArrayList;
 
 public class WebViewClientTest extends ActivityInstrumentationTestCase2<WebViewCtsActivity> {
     private static final long TEST_TIMEOUT = 5000;
@@ -213,41 +210,6 @@
         }.run();
     }
 
-    public void testOnReceivedLoginRequest() throws Exception {
-        if (!NullWebViewUtils.isWebViewAvailable()) {
-            return;
-        }
-        final MockWebViewClient webViewClient = new MockWebViewClient();
-        mOnUiThread.setWebViewClient(webViewClient);
-        TestWebServer testServer = null;
-        //set the url and html
-        final String path = "/main";
-        final String page = "<head></head><body>test onReceivedLoginRequest</body>";
-        final String headerName = "x-auto-login";
-        final String headerValue = "realm=com.google&account=foo%40bar.com&args=random_string";
-        List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
-        headers.add(Pair.create(headerName, headerValue));
-
-        try {
-            testServer = new TestWebServer(false);
-            String url = testServer.setResponse(path, page, headers);
-            assertFalse(webViewClient.hasOnReceivedLoginRequest());
-            mOnUiThread.loadUrlAndWaitForCompletion(url);
-            assertTrue(webViewClient.hasOnReceivedLoginRequest());
-            new PollingCheck(TEST_TIMEOUT) {
-                @Override
-                protected boolean check() {
-                    return webViewClient.hasOnReceivedLoginRequest();
-                }
-            }.run();
-           assertEquals("com.google", webViewClient.getLoginRequestRealm());
-           assertEquals("foo@bar.com", webViewClient.getLoginRequestAccount());
-           assertEquals("random_string", webViewClient.getLoginRequestArgs());
-        } finally {
-            testServer.shutdown();
-        }
-    }
-
     public void testOnReceivedError() throws Exception {
         if (!NullWebViewUtils.isWebViewAvailable()) {
             return;
@@ -579,10 +541,6 @@
         private boolean mOnFormResubmissionCalled;
         private boolean mDoUpdateVisitedHistoryCalled;
         private boolean mOnReceivedHttpAuthRequestCalled;
-        private boolean mOnReceivedLoginRequest;
-        private String mOnReceivedLoginAccount;
-        private String mOnReceivedLoginArgs;
-        private String mOnReceivedLoginRealm;
         private boolean mOnUnhandledKeyEventCalled;
         private boolean mOnScaleChangedCalled;
         private int mShouldOverrideUrlLoadingCallCount;
@@ -608,10 +566,6 @@
             return mOnReceivedErrorCode;
         }
 
-        public boolean hasOnReceivedLoginRequest() {
-            return mOnReceivedLoginRequest;
-        }
-
         public WebResourceError hasOnReceivedResourceError() {
             return mOnReceivedResourceError;
         }
@@ -648,18 +602,6 @@
             return mLastShouldOverrideUrl;
         }
 
-        public String getLoginRequestRealm() {
-            return mOnReceivedLoginRealm;
-        }
-
-        public String getLoginRequestAccount() {
-            return mOnReceivedLoginAccount;
-        }
-
-        public String getLoginRequestArgs() {
-            return mOnReceivedLoginArgs;
-        }
-
         @Override
         public void onPageStarted(WebView view, String url, Bitmap favicon) {
             super.onPageStarted(view, url, favicon);
diff --git a/tests/tests/widget/AndroidManifest.xml b/tests/tests/widget/AndroidManifest.xml
index 46cdd4d..bc43106 100644
--- a/tests/tests/widget/AndroidManifest.xml
+++ b/tests/tests/widget/AndroidManifest.xml
@@ -213,8 +213,7 @@
         </activity>
 
         <activity android:name="android.widget.cts.TextViewCtsActivity"
-            android:label="TextViewCtsActivity"
-            android:windowSoftInputMode="stateAlwaysHidden">
+            android:label="TextViewCtsActivity">
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST" />
diff --git a/tests/tests/widget/src/android/widget/cts/TextViewTest.java b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
index a4c27f4..12818d3 100644
--- a/tests/tests/widget/src/android/widget/cts/TextViewTest.java
+++ b/tests/tests/widget/src/android/widget/cts/TextViewTest.java
@@ -27,7 +27,6 @@
 import android.content.pm.PackageManager;
 import android.content.res.ColorStateList;
 import android.content.res.Resources.NotFoundException;
-import android.cts.util.KeyEventUtil;
 import android.cts.util.PollingCheck;
 import android.cts.util.WidgetTestUtils;
 import android.graphics.Bitmap;
@@ -120,7 +119,6 @@
             + "this text, I would love to see the kind of devices you guys now use!";
     private static final long TIMEOUT = 5000;
     private CharSequence mTransformedText;
-    private KeyEventUtil mKeyEventUtil;
 
     public TextViewTest() {
         super("com.android.cts.widget", TextViewCtsActivity.class);
@@ -137,7 +135,6 @@
             }
         }.run();
         mInstrumentation = getInstrumentation();
-        mKeyEventUtil = new KeyEventUtil(mInstrumentation);
     }
 
     /**
@@ -260,7 +257,7 @@
         assertSame(movementMethod, mTextView.getMovementMethod());
         assertEquals(selectionStart, Selection.getSelectionStart(mTextView.getText()));
         assertEquals(selectionEnd, Selection.getSelectionEnd(mTextView.getText()));
-        mKeyEventUtil.sendKeys(mTextView, KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_ALT_LEFT,
+        sendKeys(KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_ALT_LEFT,
                 KeyEvent.KEYCODE_DPAD_UP);
         // the selection has been removed.
         assertEquals(selectionStart, Selection.getSelectionStart(mTextView.getText()));
@@ -279,7 +276,7 @@
         assertNull(mTextView.getMovementMethod());
         assertEquals(selectionStart, Selection.getSelectionStart(mTextView.getText()));
         assertEquals(selectionEnd, Selection.getSelectionEnd(mTextView.getText()));
-        mKeyEventUtil.sendKeys(mTextView, KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_ALT_LEFT,
+        sendKeys(KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_ALT_LEFT,
                 KeyEvent.KEYCODE_DPAD_UP);
         // the selection will not be changed.
         assertEquals(selectionStart, Selection.getSelectionStart(mTextView.getText()));
@@ -1273,7 +1270,7 @@
         initTextViewForTyping();
 
         // Type some text.
-        mKeyEventUtil.sendString(mTextView, "abc");
+        mInstrumentation.sendStringSync("abc");
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Precondition: The cursor is at the end of the text.
@@ -1305,9 +1302,8 @@
         initTextViewForTyping();
 
         // Simulate deleting text and undoing it.
-        mKeyEventUtil.sendString(mTextView, "xyz");
-        mKeyEventUtil.sendKeys(mTextView, KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL, KeyEvent
-                .KEYCODE_DEL);
+        mInstrumentation.sendStringSync("xyz");
+        sendKeys(KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL);
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Precondition: The text was actually deleted.
@@ -1437,8 +1433,8 @@
         initTextViewForTyping();
 
         // Create two undo operations, an insert and a delete.
-        mKeyEventUtil.sendString(mTextView, "xyz");
-        mKeyEventUtil.sendKeys(mTextView, KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL);
+        mInstrumentation.sendStringSync("xyz");
+        sendKeys(KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_DEL);
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Calling setText() clears both undo operations, so undo doesn't happen.
@@ -1459,7 +1455,7 @@
         initTextViewForTyping();
 
         // Type some text. This creates an undo entry.
-        mKeyEventUtil.sendString(mTextView, "abc");
+        mInstrumentation.sendStringSync("abc");
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Undo the typing to create a redo entry.
@@ -1478,7 +1474,7 @@
         initTextViewForTyping();
 
         // Type some text.
-        mKeyEventUtil.sendString(mTextView, "abc");
+        mInstrumentation.sendStringSync("abc");
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Programmatically append some text.
@@ -1501,7 +1497,7 @@
         initTextViewForTyping();
 
         // Type some text.
-        mKeyEventUtil.sendString(mTextView, "abc");
+        mInstrumentation.sendStringSync("abc");
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Directly modify the underlying Editable to insert some text.
@@ -1550,7 +1546,7 @@
         mTextView.addTextChangedListener(new ConvertToSpacesTextWatcher());
 
         // Type some text.
-        mKeyEventUtil.sendString(mTextView, "abc");
+        mInstrumentation.sendStringSync("abc");
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // TextWatcher altered the text.
@@ -1588,7 +1584,7 @@
         initTextViewForTyping();
 
         // Type some text.
-        mKeyEventUtil.sendString(mTextView, "abc");
+        mInstrumentation.sendStringSync("abc");
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Pressing Control-Z triggers undo.
@@ -1611,7 +1607,7 @@
         initTextViewForTyping();
 
         // Type some text to create an undo operation.
-        mKeyEventUtil.sendString(mTextView, "abc");
+        mInstrumentation.sendStringSync("abc");
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Parcel and unparcel the TextView.
@@ -1622,7 +1618,7 @@
         mInstrumentation.waitForIdleSync();
 
         // Delete a character to create a new undo operation.
-        mKeyEventUtil.sendKeys(mTextView, KeyEvent.KEYCODE_DEL);
+        sendKeys(KeyEvent.KEYCODE_DEL);
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 assertEquals("ab", mTextView.getText().toString());
@@ -1649,8 +1645,8 @@
         initTextViewForTyping();
 
         // Type and delete to create two new undo operations.
-        mKeyEventUtil.sendString(mTextView, "a");
-        mKeyEventUtil.sendKeys(mTextView, KeyEvent.KEYCODE_DEL);
+        mInstrumentation.sendStringSync("a");
+        sendKeys(KeyEvent.KEYCODE_DEL);
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Empty the undo stack then parcel and unparcel the TextView. While the undo
@@ -1664,8 +1660,8 @@
         mInstrumentation.waitForIdleSync();
 
         // Create two more undo operations.
-        mKeyEventUtil.sendString(mTextView, "b");
-        mKeyEventUtil.sendKeys(mTextView, KeyEvent.KEYCODE_DEL);
+        mInstrumentation.sendStringSync("b");
+        sendKeys(KeyEvent.KEYCODE_DEL);
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 // Verify undo still works.
@@ -1900,7 +1896,7 @@
 
         assertEquals(errorText, mTextView.getError().toString());
 
-        mKeyEventUtil.sendString(mTextView, "a");
+        mInstrumentation.sendStringSync("a");
         // a key event that will not change the TextView's text
         assertEquals("", mTextView.getText().toString());
         // The icon and error message will not be reset to null
@@ -1916,7 +1912,7 @@
         });
         mInstrumentation.waitForIdleSync();
 
-        mKeyEventUtil.sendString(mTextView, "1");
+        mInstrumentation.sendStringSync("1");
         // a key event cause changes to the TextView's text
         assertEquals("1", mTextView.getText().toString());
         // the error message and icon will be cleared.
@@ -1942,13 +1938,13 @@
 
         assertSame(expected, mTextView.getFilters());
 
-        mKeyEventUtil.sendString(mTextView, "a");
+        mInstrumentation.sendStringSync("a");
         // the text is capitalized by InputFilter.AllCaps
         assertEquals("A", mTextView.getText().toString());
-        mKeyEventUtil.sendString(mTextView, "b");
+        mInstrumentation.sendStringSync("b");
         // the text is capitalized by InputFilter.AllCaps
         assertEquals("AB", mTextView.getText().toString());
-        mKeyEventUtil.sendString(mTextView, "c");
+        mInstrumentation.sendStringSync("c");
         // 'C' could not be accepted, because there is a length filter.
         assertEquals("AB", mTextView.getText().toString());
 
@@ -2145,11 +2141,11 @@
     public void testPressKey() {
         initTextViewForTyping();
 
-        mKeyEventUtil.sendString(mTextView, "a");
+        mInstrumentation.sendStringSync("a");
         assertEquals("a", mTextView.getText().toString());
-        mKeyEventUtil.sendString(mTextView, "b");
+        mInstrumentation.sendStringSync("b");
         assertEquals("ab", mTextView.getText().toString());
-        mKeyEventUtil.sendKeys(mTextView, KeyEvent.KEYCODE_DEL);
+        sendKeys(KeyEvent.KEYCODE_DEL);
         assertEquals("a", mTextView.getText().toString());
     }
 
@@ -2461,7 +2457,7 @@
         assertSame(PasswordTransformationMethod.getInstance(),
                 mTextView.getTransformationMethod());
 
-        mKeyEventUtil.sendKeys(mTextView, "H E 2*L O");
+        sendKeys("H E 2*L O");
         mActivity.runOnUiThread(new Runnable() {
             public void run() {
                 mTextView.append(" ");
diff --git a/tools/Android.mk b/tools/Android.mk
index 8cb90db..8377036 100644
--- a/tools/Android.mk
+++ b/tools/Android.mk
@@ -19,13 +19,12 @@
 TF_JAR := $(HOST_OUT_JAVA_LIBRARIES)/tradefed-prebuilt.jar
 CTS_TF_JAR := $(HOST_OUT_JAVA_LIBRARIES)/cts-tradefed.jar
 CTS_TF_EXEC_PATH ?= $(HOST_OUT_EXECUTABLES)/cts-tradefed
-PRECONDITIONS_APK := $(CTS_TESTCASES_OUT)/CtsPreconditionsApp.apk
 
 cts_prebuilt_jar := $(HOST_OUT)/cts/android-cts/tools/cts-prebuilt.jar
 $(cts_prebuilt_jar): PRIVATE_TESTS_DIR := $(HOST_OUT)/cts/android-cts/repository/testcases
 $(cts_prebuilt_jar): PRIVATE_PLANS_DIR := $(HOST_OUT)/cts/android-cts/repository/plans
 $(cts_prebuilt_jar): PRIVATE_TOOLS_DIR := $(HOST_OUT)/cts/android-cts/tools
-$(cts_prebuilt_jar): $(JUNIT_HOST_JAR) $(HOSTTESTLIB_JAR) $(TF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(ADDITIONAL_TF_JARS) $(PRECONDITIONS_APK) | $(ACP) $(HOST_OUT_EXECUTABLES)/adb
+$(cts_prebuilt_jar): $(JUNIT_HOST_JAR) $(HOSTTESTLIB_JAR) $(TF_JAR) $(CTS_TF_JAR) $(CTS_TF_EXEC_PATH) $(ADDITIONAL_TF_JARS) | $(ACP) $(HOST_OUT_EXECUTABLES)/adb
 	mkdir -p $(PRIVATE_TESTS_DIR)
 	mkdir -p $(PRIVATE_PLANS_DIR)
 	mkdir -p $(PRIVATE_TOOLS_DIR)
diff --git a/tools/tradefed-host/preconditions/Android.mk b/tools/tradefed-host/preconditions/Android.mk
deleted file mode 100644
index bcd7b49..0000000
--- a/tools/tradefed-host/preconditions/Android.mk
+++ /dev/null
@@ -1,36 +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
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
-
-LOCAL_PACKAGE_NAME := CtsPreconditionsApp
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tools/tradefed-host/preconditions/AndroidManifest.xml b/tools/tradefed-host/preconditions/AndroidManifest.xml
deleted file mode 100644
index 02b3534..0000000
--- a/tools/tradefed-host/preconditions/AndroidManifest.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.android.cts.preconditions">
-    <application>
-        <uses-library android:name="android.test.runner" />
-    </application>
-
-    <!--  self-instrumenting test package. -->
-    <instrumentation
-        android:name="android.support.test.runner.AndroidJUnitRunner"
-        android:label="CTS device-side preconditions test"
-        android:targetPackage="com.android.cts.preconditions" >
-    </instrumentation>
-</manifest>
diff --git a/tools/tradefed-host/preconditions/src/com/android/cts/preconditions/PreconditionsTest.java b/tools/tradefed-host/preconditions/src/com/android/cts/preconditions/PreconditionsTest.java
deleted file mode 100644
index f1576a3..0000000
--- a/tools/tradefed-host/preconditions/src/com/android/cts/preconditions/PreconditionsTest.java
+++ /dev/null
@@ -1,59 +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.
- */
-package com.android.cts.preconditions;
-
-import android.app.KeyguardManager;
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.os.Environment;
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-/**
- * An AndroidTestCase class to verify that device-side preconditions are met for CTS
- */
-public class PreconditionsTest extends AndroidTestCase {
-
-    private static final String TAG = "PreconditionsTest";
-
-    /**
-     * Test if device has no screen lock
-     * @throws Exception
-     */
-    public void testScreenUnlocked() throws Exception {
-        PackageManager pm = getContext().getPackageManager();
-        if (pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
-                || pm.hasSystemFeature(PackageManager.FEATURE_WATCH)
-                || pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
-            Log.i(TAG, "Skipping screen lock precondition for this device type");
-            return; // do not test for unlocked screen on devices with no screen lock
-        }
-        KeyguardManager km =
-                (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
-        assertFalse("Device must have screen lock disabled", km.isDeviceSecure());
-    }
-
-    /**
-     * Test if device has accessible external storage
-     * @throws Exception
-     */
-    public void testExternalStoragePresent() throws Exception {
-        String state = Environment.getExternalStorageState();
-        assertTrue("Device must have writable external storage mounted in order to run CTS",
-                Environment.MEDIA_MOUNTED.equals(state));
-    }
-
-}
diff --git a/tools/tradefed-host/res/config/cts.xml b/tools/tradefed-host/res/config/cts.xml
index a5665be..416b400 100644
--- a/tools/tradefed-host/res/config/cts.xml
+++ b/tools/tradefed-host/res/config/cts.xml
@@ -19,8 +19,6 @@
     <option name="enable-root" value="false" />
     <build_provider class="com.android.cts.tradefed.build.CtsBuildProvider" />
     <device_recovery class="com.android.tradefed.device.WaitDeviceRecovery" />
-    <target_preparer class="com.android.cts.tradefed.targetprep.DevicePreconditionPreparer" />
-    <target_preparer class="com.android.cts.tradefed.targetprep.HostPreconditionPreparer" />
     <test class="com.android.cts.tradefed.testtype.CtsTest" />
     <logger class="com.android.tradefed.log.FileLogger" />
     <result_reporter class="com.android.cts.tradefed.result.CtsXmlResultReporter" />
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildProvider.java b/tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildProvider.java
index 758b639..900b217 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildProvider.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/build/CtsBuildProvider.java
@@ -31,7 +31,7 @@
     @Option(name="cts-install-path", description="the path to the cts installation to use")
     private String mCtsRootDirPath = System.getProperty("CTS_ROOT");
 
-    public static final String CTS_BUILD_VERSION = "6.0_r14";
+    public static final String CTS_BUILD_VERSION = "6.0_r201702s";
     public static final String CTS_PACKAGE = "com.android.cts.tradefed.testtype";
 
     /**
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/DevicePreconditionPreparer.java b/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/DevicePreconditionPreparer.java
deleted file mode 100644
index 1c0f193..0000000
--- a/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/DevicePreconditionPreparer.java
+++ /dev/null
@@ -1,224 +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.
- */
-
-package com.android.cts.tradefed.targetprep;
-
-import com.android.cts.tradefed.build.CtsBuildHelper;
-import com.android.cts.tradefed.testtype.Abi;
-import com.android.ddmlib.Log;
-import com.android.ddmlib.testrunner.TestIdentifier;
-import com.android.tradefed.build.IBuildInfo;
-import com.android.tradefed.build.IFolderBuildInfo;
-import com.android.tradefed.config.Option;
-import com.android.tradefed.config.OptionClass;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.log.LogUtil;
-import com.android.tradefed.result.InputStreamSource;
-import com.android.tradefed.result.ITestInvocationListener;
-import com.android.tradefed.result.LogDataType;
-import com.android.tradefed.result.TestSummary;
-import com.android.tradefed.testtype.IAbi;
-import com.android.tradefed.testtype.InstrumentationTest;
-import com.android.tradefed.targetprep.BuildError;
-import com.android.tradefed.targetprep.ITargetPreparer;
-import com.android.tradefed.targetprep.TargetSetupError;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * A {@link ITargetPreparer} that performs precondition checks on the device-side for CTS.
- * <p/>
- * This class instruments an APK containing tests verifying that the device meets CTS
- * preconditions. At present, the APK contains tests to ensure that the device's screen is not
- * locked, and that the device's external storage is present and writable. The test lives under
- * //cts/tools/tradefed-host/preconditions, and can be modified to perform further checks and tasks
- * from the device-side.
- */
-@OptionClass(alias="device-precondition-preparer")
-public class DevicePreconditionPreparer implements ITargetPreparer {
-
-    /* This option also exists in the HostPreconditionPreparer */
-    @Option(name = "skip-preconditions",
-            description = "Whether to skip precondition checks and automation")
-    protected boolean mSkipPreconditions = false;
-
-    /* Constants for the InstrumentationTest */
-    private static final String APK_NAME = "CtsPreconditionsApp.apk";
-    private static final String PACKAGE_NAME = "com.android.cts.preconditions";
-    private static final String RUNNER_NAME = "android.support.test.runner.AndroidJUnitRunner";
-
-    private static final String LOG_TAG = DevicePreconditionPreparer.class.getSimpleName();
-
-    /* Map used to track test failures */
-    private ConcurrentHashMap<TestIdentifier, String> testFailures = new ConcurrentHashMap<>();
-
-    /* Helper that logs a message with LogLevel.WARN */
-    private static void printWarning(String msg) {
-        LogUtil.printLog(Log.LogLevel.WARN, LOG_TAG, msg);
-    }
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    public void setUp(ITestDevice device, IBuildInfo buildInfo) throws TargetSetupError,
-            BuildError, DeviceNotAvailableException {
-        if (mSkipPreconditions) {
-            return; // skipping device-side preconditions
-        }
-
-        try {
-            if (!instrument(device, buildInfo)) {
-                printWarning("Not all device-side preconditions met, " +
-                        "CTS tests may fail as a result.");
-            }
-        } catch (FileNotFoundException e) {
-            throw new TargetSetupError(
-                    String.format("Couldn't find %s to instrument", APK_NAME), e);
-        }
-    }
-
-    /* Instruments the APK on the device, and logs precondition test failures, if any are found.
-     * Returns true if all tests pass, and otherwise returns false */
-    private boolean instrument(ITestDevice device, IBuildInfo buildInfo)
-            throws DeviceNotAvailableException, FileNotFoundException {
-        ITestInvocationListener listener = new PreconditionPreparerListener();
-        CtsBuildHelper mCtsBuild = CtsBuildHelper.createBuildHelper(buildInfo);
-        File apkFile = mCtsBuild.getTestApp(APK_NAME); // get the APK file with the CtsBuildHelper
-        InstrumentationTest instrTest = new InstrumentationTest();
-        instrTest.setDevice(device);
-        instrTest.setInstallFile(apkFile);
-        instrTest.setPackageName(PACKAGE_NAME);
-        instrTest.setRunnerName(RUNNER_NAME);
-        instrTest.run(listener);
-        boolean success = true;
-        if (!testFailures.isEmpty()) {
-            success = false; // at least one precondition has failed
-            for (TestIdentifier test : testFailures.keySet()) {
-                String trace = testFailures.get(test);
-                printWarning(String.format(
-                        "Precondition test %s failed.\n%s", test.getTestName(), trace));
-            }
-        }
-        return success;
-    }
-
-    /**
-     * The PreconditionPreparerListener is an implementation of ITestInvocationListener
-     * that adds entries to the ConcurrentHashMap 'testFailures' of the outer class whenever
-     * a test fails. The listener also logs information if the test run fails, for debugging
-     * purposes.
-     */
-    public class PreconditionPreparerListener implements ITestInvocationListener {
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testFailed(TestIdentifier test, String trace) {
-            testFailures.put(test, trace);
-        }
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testRunFailed(String errorMessage) {
-            printWarning(String.format(
-                    "Device-side preconditions test run failed: %s", errorMessage));
-        }
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testEnded(TestIdentifier test, Map<String, String> metrics) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void invocationStarted(IBuildInfo buildInfo) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testLog(String dataName, LogDataType dataType, InputStreamSource dataStream) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void invocationEnded(long elapsedTime) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void invocationFailed(Throwable cause) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public TestSummary getSummary() {
-            return null;
-        }
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testRunStarted(String runName, int testCount) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testStarted(TestIdentifier test) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testAssumptionFailure(TestIdentifier test, String trace) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testIgnored(TestIdentifier test) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testRunStopped(long elapsedTime) {}
-
-        /**
-         * {@inheritDoc}
-         */
-        @Override
-        public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {}
-    }
-}
diff --git a/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/HostPreconditionPreparer.java b/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/HostPreconditionPreparer.java
deleted file mode 100644
index 2b85660..0000000
--- a/tools/tradefed-host/src/com/android/cts/tradefed/targetprep/HostPreconditionPreparer.java
+++ /dev/null
@@ -1,545 +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.
- */
-package com.android.cts.tradefed.targetprep;
-
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.Log;
-import com.android.tradefed.build.IBuildInfo;
-import com.android.tradefed.config.Option;
-import com.android.tradefed.config.OptionClass;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.log.LogUtil;
-import com.android.tradefed.targetprep.BuildError;
-import com.android.tradefed.targetprep.ITargetPreparer;
-import com.android.tradefed.targetprep.TargetSetupError;
-import com.android.tradefed.util.FileUtil;
-import com.android.tradefed.util.ZipUtil;
-
-import java.awt.Dimension;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.zip.ZipFile;
-
-/**
- * A {@link ITargetPreparer} that performs steps on the host-side to meet the preconditions of CTS.
- * <p/>
- * This class is intended for runs of CTS against a device running a user build.
- * <p/>
- * This class performs checks to verify that the location services are on, WiFi is connected,
- * the device locale is set to 'en-US', and that the device runs a user build. The class also
- * performs automation to ensure that 3rd party app installs are enabled, the 'Stay Awake' setting
- * is turned on, and that the appropriate media files are pushed to the device for the media tests.
- * Additionally, options are provided for automatically connecting to a specific WiFi network.
- */
-@OptionClass(alias="host-precondition-preparer")
-public class HostPreconditionPreparer implements ITargetPreparer {
-
-    /* This option also exists in the DevicePreconditionPreparer */
-    @Option(name = "skip-preconditions",
-            description = "Whether to skip precondition checks and automation")
-    protected boolean mSkipPreconditions = false;
-
-    @Option(name = "wifi-ssid", description = "Name of the WiFi network with which to connect")
-    protected String mWifiSsid = null;
-
-    @Option(name = "wifi-psk", description = "The WPA-PSK associated with option 'wifi-ssid'")
-    protected String mWifiPsk = null;
-
-    @Option(name = "skip-media-download",
-            description = "Whether to skip verifying/downloading media files")
-    protected boolean mSkipMediaDownload = false;
-
-    @Option(name = "skip-wifi-check",
-            description = "Whether to skip verification of network connection")
-    protected boolean mSkipWifiCheck = false;
-
-    @Option(name = "local-media-path",
-            description = "Absolute path of the media files directory on the host, containing" +
-            "'bbb_short' and 'bbb_full' directories")
-    protected String mLocalMediaPath = null;
-
-    private static final String LOG_TAG = HostPreconditionPreparer.class.getSimpleName();
-
-    private static final String WIFI_FEATURE = "android.hardware.wifi";
-    private static final String LOCATION_GPS_FEATURE = "android.hardware.location.gps";
-    private static final String LOCATION_NETWORK_FEATURE = "android.hardware.location.network";
-
-    /* Constants found in android.provider.Settings */
-    protected static final String STAY_ON_WHILE_PLUGGED_IN = "stay_on_while_plugged_in";
-    protected static final String PACKAGE_VERIFIER_INCLUDE_ADB = "verifier_verify_adb_installs";
-    protected static final String LOCATION_PROVIDERS_ALLOWED = "location_providers_allowed";
-    /* Constant from android.os.BatteryManager */
-    private static final int BATTERY_PLUGGED_ANY = 7;
-
-    /* Name and expected value of the device's locale property */
-    private static final String LOCALE_PROPERTY_STRING = "ro.product.locale";
-    private static final String US_EN_LOCALE_STRING = "en-US";
-    /* Name and expected value of the device's build type property */
-    private static final String BUILD_TYPE_PROPERTY_STRING = "ro.build.type";
-    private static final String USER_BUILD_STRING = "user";
-
-    /* Logged if the preparer fails to identify the device's maximum video playback resolution */
-    private static final String MAX_PLAYBACK_RES_FAILURE_MSG =
-            "Unable to parse maximum video playback resolution, pushing all media files";
-
-    /*
-     * The URL from which to download the compressed media files
-     * TODO: Find a way to retrieve this programmatically
-     */
-    private static final String MEDIA_URL_STRING =
-            "https://dl.google.com/dl/android/cts/android-cts-media-1.1.zip";
-
-    /*
-     * A default name for the local directory into which media files will be downloaded, if option
-     * "local-media-path" is not provided. This name is intentionally predetermined and final, so
-     * that when running CTS repeatedly, media files downloaded to the host in a previous run of
-     * CTS can be found in this directory, which will live inside the local temp directory.
-     */
-    private static final String MEDIA_FOLDER_NAME = "android-cts-media";
-
-    /* Constants identifying video playback resolutions of the media files to be copied */
-    protected static final int RES_176_144 = 0; // 176x144 resolution
-    protected static final int RES_DEFAULT = 1; // 480x360, the default max playback resolution
-    protected static final int RES_720_480 = 2; // 720x480 resolution
-    protected static final int RES_1280_720 = 3; // 1280x720 resolution
-    protected static final int RES_1920_1080 = 4; // 1920x1080 resolution
-
-    /* Array of Dimensions aligning with and corresponding to the resolution constants above */
-    protected static final Dimension[] resolutions = {
-            new Dimension(176, 144),
-            new Dimension(480, 360),
-            new Dimension(720, 480),
-            new Dimension(1280, 720),
-            new Dimension(1920, 1080)
-    };
-
-    /*********************************************************************************************
-     * HELPER METHODS
-     *********************************************************************************************/
-
-    /* Helper that logs a message with LogLevel.INFO */
-    private static void printInfo(String msg) {
-        LogUtil.printLog(Log.LogLevel.INFO, LOG_TAG, msg);
-    }
-
-    /* Helper that logs a message with LogLevel.WARN */
-    private static void printWarning(String msg) {
-        LogUtil.printLog(Log.LogLevel.WARN, LOG_TAG, msg);
-    }
-
-    /* Helper that determines whether the device supports a feature */
-    private boolean hasFeature(ITestDevice device, String feature)
-            throws DeviceNotAvailableException {
-        String pmFeatures = device.executeShellCommand("pm list features");
-        return pmFeatures.contains(feature);
-    }
-
-    /*
-     * Returns a string representation of the dimension
-     * For dimension of width = 480 and height = 360, the resolution string is "480x360"
-     */
-    protected static String resolutionString(Dimension resolution) {
-        return String.format("%dx%d", resolution.width, resolution.height);
-    }
-
-    /*
-     * Returns the device's absolute path to the directory containing 'short' media files, given
-     * a resolution. The instance of ITestDevice is used to identify the mount point for
-     * external storage.
-     */
-    protected String getDeviceShortDir(ITestDevice device, Dimension resolution) {
-        String mountPoint = device.getMountPoint(IDevice.MNT_EXTERNAL_STORAGE);
-        return String.format("%s/test/bbb_short/%s", mountPoint, resolutionString(resolution));
-    }
-
-    /*
-     * Returns the device's absolute path to the directory containing 'full' media files, given
-     * a resolution. The instance of ITestDevice is used to identify the mount point for
-     * external storage.
-     */
-    protected String getDeviceFullDir(ITestDevice device, Dimension resolution) {
-        String mountPoint = device.getMountPoint(IDevice.MNT_EXTERNAL_STORAGE);
-        return String.format("%s/test/bbb_full/%s", mountPoint, resolutionString(resolution));
-    }
-
-    /*
-     * Loops through the predefined maximum video playback resolutions from largest to smallest,
-     * And returns the greatest resolution that is strictly smaller than the width and height
-     * provided in the arguments.
-     */
-    private Dimension getMaxVideoPlaybackResolution(int width, int height) {
-        for (int resIndex = resolutions.length - 1; resIndex >= RES_DEFAULT; resIndex--) {
-            Dimension resolution = resolutions[resIndex];
-            if (width >= resolution.width && height >= resolution.height) {
-                return resolution;
-            }
-        }
-        return resolutions[RES_DEFAULT];
-    }
-
-    /**
-     * Returns the maximum video playback resolution of the device, in the form of a Dimension
-     * object. This method parses dumpsys output to find resolutions listed under the
-     * 'mBaseDisplayInfo' field. The value of the 'smallest app' field is used as an estimate for
-     * maximum video playback resolution, and is rounded down to the nearest dimension in the
-     * resolutions array.
-     */
-    protected Dimension getMaxVideoPlaybackResolution(ITestDevice device)
-            throws DeviceNotAvailableException{
-        String dumpsysOutput =
-                device.executeShellCommand("dumpsys display | grep mBaseDisplayInfo");
-        Pattern pattern = Pattern.compile("smallest app (\\d+) x (\\d+)");
-        Matcher matcher = pattern.matcher(dumpsysOutput);
-        if(!matcher.find()) {
-            // could not find resolution in dumpsysOutput, return largest max playback resolution
-            // so that preparer copies all media files
-            printInfo(MAX_PLAYBACK_RES_FAILURE_MSG);
-            return resolutions[RES_1920_1080];
-        }
-
-        int first;
-        int second;
-        try {
-            first = Integer.parseInt(matcher.group(1));
-            second = Integer.parseInt(matcher.group(2));
-        } catch (NumberFormatException e) {
-            // match was found, but not an identifiable resolution
-            printInfo(MAX_PLAYBACK_RES_FAILURE_MSG);
-            return resolutions[RES_1920_1080];
-        }
-        // ensure that the larger of the two values found is assigned to 'width'
-        int height = Math.min(first, second);
-        int width = Math.max(first, second);
-        return getMaxVideoPlaybackResolution(width, height);
-    }
-
-    /*
-     * After downloading and unzipping the media files, mLocalMediaPath must be the path to the
-     * directory containing 'bbb_short' and 'bbb_full' directories, as it is defined in its
-     * description as an option.
-     * After extraction, this directory exists one level below the the directory 'mediaFolder'.
-     * If the 'mediaFolder' contains anything other than exactly one subdirectory, a
-     * TargetSetupError is thrown. Otherwise, the mLocalMediaPath variable is set to the path of
-     * this subdirectory.
-     */
-    private void updateLocalMediaPath(File mediaFolder) throws TargetSetupError {
-        String[] subDirs = mediaFolder.list();
-        if (subDirs.length != 1) {
-            throw new TargetSetupError(String.format(
-                    "Unexpected contents in directory %s", mLocalMediaPath));
-        }
-        File newMediaFolder = new File(mediaFolder, subDirs[0]);
-        mLocalMediaPath = newMediaFolder.toString();
-    }
-
-    /*
-     * Copies the media files to the host from predefined url MEDIA_URL_STRING.
-     * The compressed file is downloaded and unzipped into mLocalMediaPath.
-     */
-    private void downloadMediaToHost() throws TargetSetupError {
-
-        URL url;
-        try {
-            url = new URL(MEDIA_URL_STRING);
-        } catch (MalformedURLException e) {
-            throw new TargetSetupError(
-                    String.format("Trouble finding android media files at %s", MEDIA_URL_STRING));
-        }
-
-        File mediaFolder = new File(mLocalMediaPath);
-        File mediaFolderZip = new File(mediaFolder.getAbsolutePath() + ".zip");
-        try {
-
-            mediaFolder.mkdirs();
-            mediaFolderZip.createNewFile();
-
-            URLConnection conn = url.openConnection();
-            InputStream in = conn.getInputStream();
-            BufferedOutputStream out =
-                    new BufferedOutputStream(new FileOutputStream(mediaFolderZip));
-            byte[] buffer = new byte[1024];
-            int count;
-            printInfo("Downloading media files to host");
-            while ((count = in.read(buffer)) >= 0) {
-                out.write(buffer, 0, count);
-            }
-            out.flush();
-            out.close();
-            in.close();
-
-            printInfo("Unzipping media files");
-            ZipUtil.extractZip(new ZipFile(mediaFolderZip), mediaFolder);
-
-        } catch (IOException e) {
-            FileUtil.recursiveDelete(mediaFolder);
-            FileUtil.recursiveDelete(mediaFolderZip);
-            throw new TargetSetupError("Failed to open media files on host");
-        }
-    }
-
-    /**
-     * Pushes directories containing media files to the device for all directories that:
-     * - are not already present on the device
-     * - contain video files of a resolution less than or equal to the device's
-     *       max video playback resolution
-     */
-    protected void copyMediaFiles(ITestDevice device, Dimension mvpr)
-            throws DeviceNotAvailableException {
-
-        int resIndex = RES_176_144;
-        while (resIndex <= RES_1920_1080) {
-            Dimension copiedResolution = resolutions[resIndex];
-            String resString = resolutionString(copiedResolution);
-            if (copiedResolution.width > mvpr.width || copiedResolution.height > mvpr.height) {
-                printInfo(String.format(
-                        "Device cannot support resolutions %s and larger, media copying complete",
-                        resString));
-                return;
-            }
-            String deviceShortFilePath = getDeviceShortDir(device, copiedResolution);
-            String deviceFullFilePath = getDeviceFullDir(device, copiedResolution);
-            if (!device.doesFileExist(deviceShortFilePath) ||
-                    !device.doesFileExist(deviceFullFilePath)) {
-                printInfo(String.format("Copying files of resolution %s to device", resString));
-                String localShortDirName = "bbb_short/" + resString;
-                String localFullDirName = "bbb_full/" + resString;
-                File localShortDir = new File(mLocalMediaPath, localShortDirName);
-                File localFullDir = new File(mLocalMediaPath, localFullDirName);
-                // push short directory of given resolution, if not present on device
-                if(!device.doesFileExist(deviceShortFilePath)) {
-                    device.pushDir(localShortDir, deviceShortFilePath);
-                }
-                // push full directory of given resolution, if not present on device
-                if(!device.doesFileExist(deviceFullFilePath)) {
-                    device.pushDir(localFullDir, deviceFullFilePath);
-                }
-            }
-            resIndex++;
-        }
-    }
-
-    /*
-     * Returns true if all media files of a resolution less than or equal to 'mvpr' exist on the
-     * device, and otherwise returns false.
-     */
-    private boolean mediaFilesExistOnDevice(ITestDevice device, Dimension mvpr)
-            throws DeviceNotAvailableException{
-        int resIndex = RES_176_144;
-        while (resIndex <= RES_1920_1080) {
-            Dimension copiedResolution = resolutions[resIndex];
-            if (copiedResolution.width > mvpr.width || copiedResolution.height > mvpr.height) {
-                break; // we don't need to check for resolutions greater than or equal to this
-            }
-            String deviceShortFilePath = getDeviceShortDir(device, copiedResolution);
-            String deviceFullFilePath = getDeviceFullDir(device, copiedResolution);
-            if (!device.doesFileExist(deviceShortFilePath) ||
-                    !device.doesFileExist(deviceFullFilePath)) {
-                // media files of valid resolution not found on the device, and must be pushed
-                return false;
-            }
-            resIndex++;
-        }
-        return true;
-    }
-
-    /* Static method that returns a directory called 'dirName' in the system's temp directory */
-    private static File createSimpleTempDir(String dirName) throws IOException {
-        // find system's temp directory
-        File throwaway = File.createTempFile(dirName, null);
-        String systemTempDir = throwaway.getParent();
-        // create directory with simple name within temp directory
-        File simpleTempDir = new File(systemTempDir, dirName);
-        // delete file used to find temp directory
-        throwaway.delete();
-        return simpleTempDir;
-    }
-
-    /* Method that creates a local media path, and ensures that the necessary media files live
-     * within that path */
-    private void createLocalMediaPath() throws TargetSetupError {
-        File mediaFolder;
-        try {
-            mediaFolder = createSimpleTempDir(MEDIA_FOLDER_NAME);
-        } catch (IOException e) {
-            throw new TargetSetupError("Unable to create host temp directory for media files");
-        }
-        mLocalMediaPath = mediaFolder.getAbsolutePath();
-        if (!mediaFolder.exists()) {
-            // directory has not been created or filled by previous runs of MediaPreparer
-            downloadMediaToHost(); //download media into mLocalMediaPath
-        }
-        updateLocalMediaPath(mediaFolder);
-    }
-
-    /*********************************************************************************************
-     * PRECONDITION METHODS
-     *********************************************************************************************/
-
-    /**
-     * Prevents the screen from sleeping while charging via USB
-     */
-    protected void enableStayAwakeSetting(ITestDevice device) throws DeviceNotAvailableException {
-        String shellCmd = String.format("settings put global %s %d",
-                STAY_ON_WHILE_PLUGGED_IN, BATTERY_PLUGGED_ANY);
-        device.executeShellCommand(shellCmd);
-    }
-
-    /**
-     * Prevents package verification on apps installed through ADB/ADT/USB
-     */
-    protected void disableAdbAppVerification(ITestDevice device)
-            throws DeviceNotAvailableException {
-        String shellCmd = String.format("settings put global %s 0", PACKAGE_VERIFIER_INCLUDE_ADB);
-        device.executeShellCommand(shellCmd);
-    }
-
-    /**
-     * Prevents the keyguard from re-emerging during the CTS test, which can cause some failures
-     * Note: the shell command run here is not supported on L
-     */
-    protected void disableKeyguard(ITestDevice device) throws DeviceNotAvailableException {
-        device.executeShellCommand("wm disable-keyguard");
-    }
-
-    /**
-     * Prints a warning if the device's locale is something other than US English, as some tests
-     * may pass or fail depending on the 'en-US' locale.
-     */
-    protected void verifyLocale(ITestDevice device) throws DeviceNotAvailableException {
-        String locale = device.getProperty(LOCALE_PROPERTY_STRING);
-        if (locale == null) {
-            printWarning(String.format("Property %s not found on device", LOCALE_PROPERTY_STRING));
-            return;
-        }
-        if (!locale.equalsIgnoreCase(US_EN_LOCALE_STRING)) {
-            printWarning(String.format("Expected locale en-US, detected locale \"%s\"", locale));
-        }
-    }
-
-    /**
-     * Prints a warning if the device is not running a user build. This is not allowed for
-     * testing production devices, but should not block testers from running CTS on a userdebug
-     * build.
-     */
-    protected void verifyUserBuild(ITestDevice device) throws DeviceNotAvailableException {
-        String buildType = device.getProperty(BUILD_TYPE_PROPERTY_STRING);
-        if (buildType == null) {
-            printWarning(
-                    String.format("Property %s not found on device", BUILD_TYPE_PROPERTY_STRING));
-            return;
-        }
-        if (!buildType.equalsIgnoreCase(USER_BUILD_STRING)) {
-            printWarning(String.format("Expected user build, detected type \"%s\"", buildType));
-        }
-    }
-
-    /**
-     * Throws a TargetSetupError if location services are not enabled by gps or a network
-     */
-    protected void checkLocationServices(ITestDevice device)
-            throws DeviceNotAvailableException, TargetSetupError {
-
-        String shellCmd = String.format("settings get secure %s", LOCATION_PROVIDERS_ALLOWED);
-        String locationServices = device.executeShellCommand(shellCmd);
-        if (!locationServices.contains("gps") && !locationServices.contains("network")) {
-            // location services are not enabled by gps nor by the network
-            throw new TargetSetupError(
-                    "Location services must be enabled for several CTS test packages");
-        }
-    }
-
-    /**
-     * Throws a TargetSetupError if the device is not connected to a WiFi network. Testers can
-     * optionally supply a 'wifi-ssid' and 'wifi-psk' (in the options above) to attempt connection
-     * to a specific network.
-     */
-    protected void runWifiPrecondition(ITestDevice device)
-            throws TargetSetupError, DeviceNotAvailableException {
-        if (mSkipWifiCheck) {
-            return; // skip this precondition
-        }
-        if (mWifiSsid == null) {
-            // no connection to create, check for existing connectivity
-            if (!device.checkConnectivity()) {
-                printWarning("Device has no network connection, option --wifi-ssid was not " +
-                        "provided. Some CTS tests require an active network connection to pass");
-            }
-        } else {
-            // network provided in options, attempt to create new connection if needed
-            if (!device.connectToWifiNetworkIfNeeded(mWifiSsid, mWifiPsk)) {
-                printWarning("Unable to establish network connection, some CTS tests require " +
-                        "an active network connection to pass");
-            }
-        }
-    }
-
-    /**
-     * Checks that media files for the mediastress tests are present on the device, and if not,
-     * pushes them onto the device.
-     */
-    protected void runMediaPrecondition(ITestDevice device)
-            throws TargetSetupError, DeviceNotAvailableException {
-        if (mSkipMediaDownload) {
-            return; // skip this precondition
-        }
-        Dimension mvpr = getMaxVideoPlaybackResolution(device);
-        if (mediaFilesExistOnDevice(device, mvpr)) {
-            return; // media files already found on the device
-        }
-        if (mLocalMediaPath == null) {
-            createLocalMediaPath(); // make new path on host containing media files
-        }
-        printInfo(String.format("Media files located on host at: %s", mLocalMediaPath));
-        copyMediaFiles(device, mvpr);
-    }
-
-    public void setUp(ITestDevice device, IBuildInfo buildInfo)
-            throws TargetSetupError, BuildError, DeviceNotAvailableException {
-        if (mSkipPreconditions) {
-            return; // skipping host-side preconditions
-        }
-
-        /* run each host-side precondition */
-        enableStayAwakeSetting(device);
-        disableAdbAppVerification(device);
-        disableKeyguard(device);
-        verifyLocale(device);
-        verifyUserBuild(device);
-
-        if (hasFeature(device, LOCATION_NETWORK_FEATURE) ||
-                hasFeature(device, LOCATION_GPS_FEATURE)) {
-            checkLocationServices(device); // only check location services if supported
-        }
-
-        if (hasFeature(device, WIFI_FEATURE)) {
-            runWifiPrecondition(device); // check wifi precondition only if device supports wifi
-        }
-
-        runMediaPrecondition(device);
-    }
-
-}
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
index 6fa648e..29c1324 100644
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
+++ b/tools/tradefed-host/tests/src/com/android/cts/tradefed/UnitTests.java
@@ -22,7 +22,6 @@
 import com.android.cts.tradefed.result.TestSummaryXmlTest;
 import com.android.cts.tradefed.result.TestTest;
 import com.android.cts.tradefed.result.TestLogTest;
-import com.android.cts.tradefed.targetprep.HostPreconditionPreparerTest;
 import com.android.cts.tradefed.testtype.Abi;
 import com.android.cts.tradefed.testtype.CtsTestTest;
 import com.android.cts.tradefed.testtype.DeqpTestRunnerTest;
@@ -60,9 +59,6 @@
         addTestSuite(TestTest.class);
         addTestSuite(TestLogTest.class);
 
-        // targetprep package
-        addTestSuite(HostPreconditionPreparerTest.class);
-
         // testtype package
         addTestSuite(CtsTestTest.class);
         addTestSuite(DeqpTestRunnerTest.class);
diff --git a/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetprep/HostPreconditionPreparerTest.java b/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetprep/HostPreconditionPreparerTest.java
deleted file mode 100644
index 44c6a4d..0000000
--- a/tools/tradefed-host/tests/src/com/android/cts/tradefed/targetprep/HostPreconditionPreparerTest.java
+++ /dev/null
@@ -1,190 +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.
- */
-package com.android.cts.tradefed.targetprep;
-
-import com.android.ddmlib.IDevice;
-import com.android.tradefed.config.OptionSetter;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.targetprep.TargetSetupError;
-
-import java.awt.Dimension;
-
-import junit.framework.TestCase;
-
-import org.easymock.EasyMock;
-
-/**
- * Unit tests for {@link HostPreconditionPreparer}.
- */
-public class HostPreconditionPreparerTest extends TestCase {
-
-    private HostPreconditionPreparer mHostPreconditionPreparer;
-    private ITestDevice mMockDevice;
-    private OptionSetter mOptionSetter;
-
-    private final Dimension DEFAULT_DIMENSION =
-            HostPreconditionPreparer.resolutions[HostPreconditionPreparer.RES_DEFAULT];
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mHostPreconditionPreparer = new HostPreconditionPreparer();
-        mMockDevice = EasyMock.createMock(ITestDevice.class);
-        mOptionSetter = new OptionSetter(mHostPreconditionPreparer);
-
-        EasyMock.expect(mMockDevice.getMountPoint(IDevice.MNT_EXTERNAL_STORAGE)).andReturn(
-                "/sdcard").anyTimes();
-    }
-
-    public void testLocationServicesOnGpsNetwork() throws Exception {
-        String shellCmd = String.format(
-                "settings get secure %s", HostPreconditionPreparer.LOCATION_PROVIDERS_ALLOWED);
-
-        // expect location to be enabled by both gps and network
-        EasyMock.expect(
-                mMockDevice.executeShellCommand(shellCmd)).andReturn("\ngps,network\n").once();
-        EasyMock.replay(mMockDevice);
-        mHostPreconditionPreparer.checkLocationServices(mMockDevice);
-    }
-
-    public void testLocationServicesOnGps() throws Exception {
-        String shellCmd = String.format(
-                "settings get secure %s", HostPreconditionPreparer.LOCATION_PROVIDERS_ALLOWED);
-
-        // expect location to be enabled by gps only
-        EasyMock.expect(
-                mMockDevice.executeShellCommand(shellCmd)).andReturn("\ngps\n").once();
-        EasyMock.replay(mMockDevice);
-        mHostPreconditionPreparer.checkLocationServices(mMockDevice);
-    }
-
-    public void testLocationServicesOnNetwork() throws Exception {
-        String shellCmd = String.format(
-                "settings get secure %s", HostPreconditionPreparer.LOCATION_PROVIDERS_ALLOWED);
-
-        // expect location to be enabled by network only
-        EasyMock.expect(
-                mMockDevice.executeShellCommand(shellCmd)).andReturn("\nnetwork\n").once();
-        EasyMock.replay(mMockDevice);
-        mHostPreconditionPreparer.checkLocationServices(mMockDevice);
-    }
-
-    public void testLocationServicesOff() throws Exception {
-        String shellCmd = String.format(
-                "settings get secure %s", HostPreconditionPreparer.LOCATION_PROVIDERS_ALLOWED);
-
-        // expect location to be disabled
-        EasyMock.expect(
-                mMockDevice.executeShellCommand(shellCmd)).andReturn("\n\n").once();
-        EasyMock.replay(mMockDevice);
-        try {
-            mHostPreconditionPreparer.checkLocationServices(mMockDevice);
-            fail("TargetSetupError expected");
-        } catch (TargetSetupError e) {
-            // Expected
-        }
-    }
-
-    public void testWifiConnected() throws Exception {
-        EasyMock.expect(mMockDevice.checkConnectivity()).andReturn(true).once();
-        EasyMock.replay(mMockDevice);
-        mHostPreconditionPreparer.runWifiPrecondition(mMockDevice);
-    }
-
-    public void testWifiDisconnected() throws Exception {
-        EasyMock.expect(mMockDevice.checkConnectivity()).andReturn(false).once();
-        EasyMock.replay(mMockDevice);
-        try {
-            mHostPreconditionPreparer.runWifiPrecondition(mMockDevice);
-            fail("TargetSetupError expected");
-        } catch (TargetSetupError e) {
-            // Expected
-        }
-    }
-
-    public void testWifiConnectionSuccessful() throws Exception {
-        EasyMock.expect(
-                mMockDevice.connectToWifiNetworkIfNeeded("wifi-ssid", "wifi-psk")).andReturn(true).once();
-        mOptionSetter.setOptionValue("wifi-ssid", "wifi-ssid");
-        mOptionSetter.setOptionValue("wifi-psk", "wifi-psk");
-        EasyMock.replay(mMockDevice);
-        mHostPreconditionPreparer.runWifiPrecondition(mMockDevice);
-    }
-
-    public void testWifiConnectionUnuccessful() throws Exception {
-        EasyMock.expect(
-                mMockDevice.connectToWifiNetworkIfNeeded("wifi-ssid", "wifi-psk")).andReturn(false).once();
-        mOptionSetter.setOptionValue("wifi-ssid", "wifi-ssid");
-        mOptionSetter.setOptionValue("wifi-psk", "wifi-psk");
-        EasyMock.replay(mMockDevice);
-        try {
-            mHostPreconditionPreparer.runWifiPrecondition(mMockDevice);
-            fail("TargetSetupError expected");
-        } catch (TargetSetupError e) {
-            // Expected
-        }
-    }
-
-    public void testResolutionString() throws Exception {
-        assertEquals("480x360", mHostPreconditionPreparer.resolutionString(DEFAULT_DIMENSION));
-    }
-
-    public void testGetDeviceDirs() throws Exception {
-        EasyMock.replay(mMockDevice);
-        String shortDir =
-                mHostPreconditionPreparer.getDeviceShortDir(mMockDevice, DEFAULT_DIMENSION);
-        String fullDir =
-                mHostPreconditionPreparer.getDeviceFullDir(mMockDevice, DEFAULT_DIMENSION);
-        assertEquals(shortDir, "/sdcard/test/bbb_short/480x360");
-        assertEquals(fullDir, "/sdcard/test/bbb_full/480x360");
-    }
-
-    public void testGetMaxVideoPlaybackResolutionFound() throws Exception {
-        // set "smallest app" field to DEFAULT_DIMENSION
-        String mockDumpsysOutput = "mBaseDisplayInfo=DisplayInfo{\"Built-in Screen\", uniqueId " +
-                "\"local:0\", app 1440 x 2560, real 1440 x 2560, largest app 1440 x 2560, " +
-                "smallest app 360 x 480, mode 1, defaultMode 1, modes [{id=1, width=1440, " +
-                "height=2560, fps=60.0}], rotation 0, density 560 (494.27 x 492.606) dpi, " +
-                "layerStack 0, appVsyncOff 2500000, presDeadline 17666667, type BUILT_IN, state " +
-                "ON, FLAG_SECURE, FLAG_SUPPORTS_PROTECTED_BUFFERS}\n";
-        EasyMock.expect(mMockDevice.executeShellCommand(
-                "dumpsys display | grep mBaseDisplayInfo")).andReturn(mockDumpsysOutput).once();
-        EasyMock.replay(mMockDevice);
-        Dimension result = mHostPreconditionPreparer.getMaxVideoPlaybackResolution(mMockDevice);
-        assertEquals(result, DEFAULT_DIMENSION);
-    }
-
-    public void testGetMaxVideoPlaybackResolutionNotFound() throws Exception {
-        String mockDumpsysOutput = "incorrect output";
-        EasyMock.expect(mMockDevice.executeShellCommand(
-                "dumpsys display | grep mBaseDisplayInfo")).andReturn(mockDumpsysOutput).once();
-        EasyMock.replay(mMockDevice);
-        Dimension result = mHostPreconditionPreparer.getMaxVideoPlaybackResolution(mMockDevice);
-        Dimension maxRes =
-                HostPreconditionPreparer.resolutions[HostPreconditionPreparer.RES_1920_1080];
-        assertEquals(result,maxRes);
-    }
-
-    public void testSkipMediaDownload() throws Exception {
-        mOptionSetter.setOptionValue("skip-media-download", "true");
-        EasyMock.replay();
-        mHostPreconditionPreparer.runMediaPrecondition(mMockDevice);
-    }
-
-}
diff --git a/tools/utils/buildCts.py b/tools/utils/buildCts.py
index a6c76b1..9f462ca 100755
--- a/tools/utils/buildCts.py
+++ b/tools/utils/buildCts.py
@@ -310,6 +310,12 @@
     plan.Exclude('.*')
     self.__WritePlan(plan, 'CTS-webview')
 
+    # CTS - sub plan for Security
+    plan = tools.TestPlan(packages)
+    plan.Exclude('.*')
+    plan.Include(r'android\.security$')
+    plan.Include('android\.host\.jdwpsecurity$')
+    self.__WritePlan(plan, 'Security')
 
 def BuildAospMediumSizeTestList():
   """ Construct a defaultdic that lists package names of medium tests